Exemplo n.º 1
0
def wa(bot, args):
    if len(args) > 1:
        response = urllib2.urlopen("http://api.wolframalpha.com/v2/query?appid=%s&input=%s&format=plaintext" % (bot.config.get('module: wolframalpha', 'wa_app_id'), urllib2.quote(' '.join(args[1:]))), timeout = 10)
        result = lxml.etree.parse(response)
        acceptable = [
            'Result', 'Results', 'Solution', 'Value', 'Name', 'Derivative', 'Indefinite integral', 'Distance', 'Current result*',
            'Scientific notation', 'Truth table', 'Differential equation solution', 'Decimal form', 'Decimal approximation',
            'Exact result', 'Rational approximation', 'Geometric figure', 'Definition', 'Basic definition', 'Result for *',
            'Number length', 'Definitions', 'Unit conversions', 'Electromagnetic frequency range', 'IP address registrant',
            'Address properties', 'Web hosting information', 'Current age', 'Basic information', 'Latest result', 'Response',
            'Names and airport codes', 'Latest recorded weather *', 'Series information', 'Latest trade', 'Definitions of *',
            'Possible interpretation*', 'Lifespan', 'Cipher text', 'Statement', 'Events on *', 'Time span', 'Unicode block',
            'Eclipse date', 'Total eclipse*', 'Solar wind', 'Weather forecast for *', 'Notable events in *', 'Events on *',
            'Possible sequence identification', 'Length of data', 'Properties', 'Approximate results', 'Summary', 'Nearest named HTML colors'
        ]
        for title in acceptable:
            success = xml(result, title)
            if success: break
        failure = result.xpath("/queryresult[@success='false']")
        if success:
            success = unicode(success.replace("\:", "\u"))
            util.answer(bot, success.encode('utf-8').replace("Wolfram|Alpha", bot.name).replace("Stephen Wolfram", "Milos Ivanovic").strip())
        elif failure:
            alternatives = result.xpath("/queryresult/relatedexamples/relatedexample[@input]")
            if alternatives:
                util.answer(bot, "Query not understood; suggestion%s: %s" % ('s' if len(alternatives) > 1 else '', ' | '.join([alt.values()[0].strip() for alt in alternatives])))
            else:
                util.answer(bot, __import__('random').choice(['Are you a wizard?', 'You must be a wizard.', "Plong.", "I like bytes.", "Mmmm... chocolate...", "Oooh look, a boat.", 'Boob.']))
        else:
            util.answer(bot, "No acceptable mathematical result.")
    else:
        util.give_help(bot, args[0], "<mathematical query>")
Exemplo n.º 2
0
def mishimmie(bot, args):
    if len(args) >= 2:
        url = "";
        if re.match("id:", args[1]):
            terms = re.sub('id:', '', args[1])
            url = "http://shimmie.katawa-shoujo.com/post/view/%s" % urllib2.quote(terms)
        else:
            terms = ' '.join(args[1:])
            url = "http://shimmie.katawa-shoujo.com/post/list/%s/1" % urllib2.quote(terms)
        rawres = urllib2.urlopen(url, timeout = 5)
        result = rawres.read().encode('utf8')
        doc = html.document_fromstring(result)   
        try:
            posturl = ""
            postdesc = ""
            bot._debug('URL: %s' % rawres.geturl())
            if re.search('/post/view/', rawres.geturl()):
                bot._debug('On a post page.')
                posturl = rawres.geturl()
                postdesc = doc.get_element_by_id('imgdata').xpath('form')[0].xpath('table')[0].xpath('tr')[0].xpath('td')[1].xpath('input')[0].get('value')
            else:
                bot._debug('On a search result page.')
                posturl = "http://shimmie.katawa-shoujo.com%s" % doc.find_class('thumb')[0].xpath('a')[0].get('href')
                postdesc = doc.find_class('thumb')[0].xpath('a')[0].xpath('img')[0].get('alt').partition(' // ')[0]
            posturl = re.sub('\?.*', '', posturl)
            util.answer(bot, "\x02Mishimmie:\x02 %s // %s" % (postdesc, posturl))
        except IndexError:
           util.answer(bot, "\x02Mishimmie:\x02 No results.")
    else:
        util.give_help(bot, args[0], "<query> -- search the Mishimmie for <query>")
Exemplo n.º 3
0
def lookup(bot, args):
    if len(args) in [2, 3]:
        addresses = None
        
        if len(args) == 2:
            host = args[1]
            addresses = lookitup(host, "A")
        elif len(args) == 3:
            host = args[2]
            if args[1] == "-6":
                addresses = lookitup(host, "AAAA")
            elif args[1] == "-r":
                addresses = lookitup(host, "PTR")
            else:
                util.give_help(bot, args[0], "[-6 (IPv6), -r (rDNS)] <server>")
                return None
            
        if addresses != -1:
            if addresses:
                plural = "others" if len(addresses) > 2 else "other"
                others = " (%s %s)" % (len(addresses), plural) if len(addresses) > 1 else ''
                util.answer(bot, "Address: %s%s" % (addresses[0] if not str(addresses[0]).endswith(".") else str(addresses[0])[:-1], others))
            else:
                util.answer(bot, "%s: NXDOMAIN" % host)
        else:
            answer("Invalid host for this type of lookup.")
    else:
        util.give_help(bot, args[0], "[-6 (IPv6), -r (rDNS)] <server>")
Exemplo n.º 4
0
Arquivo: _io.py Projeto: txanatan/xbot
def admin(bot, args):
    diff = lambda l1,l2: filter(lambda x: x not in l2, l1)
    
    if len(args) > 1:
        admins = [nick.strip() for nick in bot.config.get(bot.network, 'admin').split(',')]
        if args[1] == "list":
            util.answer(bot, "Admin%s: %s" % ('' if len(admins) == 1 else 's', ', '.join(admins)))
            return None
        if args[1] == "add":
            if len(args) > 2:
                bot._debug("Adding %d admins: %s." % (len(args[2:]), ', '.join(args[2:])))
                admins += args[2:]
                bot.config.set(bot.network, 'admin', ', '.join(admins))
                return None
        if args[1] == "remove":
            if len(args) > 2:
                if bot.admin in args[2:]:
                    util.answer(bot, "Can't remove root, noob.")
                
                bot._debug("Removing %d admins: %s." % (len(args[2:]), ', '.join(args[2:])))
                admins = diff(admins, args[2:])
                bot.config.set(bot.network, 'admin', ', '.join(admins))
                return None
    
    util.give_help(bot, args[0], "list|add|remove [nick]")
Exemplo n.º 5
0
def get_quote(bot, args):

    db = BotDB(bot).connect()
    
    def gen_kw(keywords):
        result = ""
        for keyword in keywords:
            result += (" AND message LIKE '%%%s%%'" % re.escape(keyword)).replace("%", "%%")
        return result
        
        
    if len(args) > 1:
    
        channel = bot.remote['receiver']
        nick = bot.remote['nick']
        
        if not args[1].lower() in bot.nick.lower():
            if len(args) == 2:
                if args[1] != "*":
                    quotes = Quote.select().where(Quote.channel == channel, Quote.nick ** ("%%%s%%" % args[1]))
                    
                    if quotes.count() > 0:
                        util.answer(bot, output_quote(bot, quotes))
                    else:
                        util.answer(bot, "No quotes from %s found." % args[1])
                else:
                    quotes = Quote.select().where(Quote.channel == channel, Quote.nick != re.escape(bot.nick))
                    
                    if quotes.count() > 0:
                        util.answer(bot, output_quote(bot, quotes))
                    else:
                        util.answer(bot, "No quotes in database yet.")
                        
            elif len(args) >= 3:
                search = ' '.join(args[2:])
                if args[1] != "*":
                    if search.startswith("/") and search.endswith("/"):
                        type = "regexp"
                        quotes = Quote.select().where(Quote.channel == channel, Quote.nick ** ("%%%s%%" % args[1]))
                        regexp = search[1:-1]
                    else:
                        type = "keywords"
                        quotes = Quote.select().where(Quote.channel == channel, Quote.nick ** ("%%%s%%" % args[1]), Quote.message ** ("%%%s%%" % search[1:-1]))
                else:
                    if search.startswith("/") and search.endswith("/"):
                        type = "regexp"
                        quotes = Quote.select().where(Quote.channel == channel, Quote.nick != re.escape(bot.nick))
                        regexp = search[1:-1]
                    else:
                        type = "keywords"
                        quotes = Quote.select().where(Quote.channel == channel, Quote.nick != re.escape(bot.nick), Quote.message ** ("%%%s%%" % search[1:-1]))
                
                if type == "regexp":
                    util.answer(bot, output_quote(bot, quotes, regexp))
                else:
                    util.answer(bot, output_quote(bot, quotes))
        else:
            util.answer(bot, "Nah. My own quotes are too contaminated.")
    else:
        util.give_help(bot, args[0], "<nick|*> [<keywords|/regexp/>]")
Exemplo n.º 6
0
def jslib(bot, args):
    if not bot.config.has_option('module: github', 'jslib_gist'):
        util.answer(bot, "%s%s: Not configured." % (bot.prefix, args[0]))
        return None
    
    if len(args) > 1:
        if args[1] == "propose" and len(args) == 3:
            pub.sendMessage('js.eval', bot=bot, callback="propose|%s|%s" % (bot.remote['nick'], args[2]), command=args[2], filters=['pretty'])
            return None
            
        elif args[1] == "list":
            l = []
            for j in os.listdir(os.path.join(os.path.dirname(__file__), "js")):
                if not re.match(".+\.js$", j):
                    continue
                l.append(j.replace(".js",''))
            
            util.answer(bot, ', '.join(l))
            return None
            
        elif args[1] == "future":
            gh = gh_inst(bot)
            if isinstance(gh, basestring):
                util.answer(bot, gh)
                return None
            gi = gh.get_gist(bot.config.get('module: github', 'jslib_gist'))
            
            util.answer(bot, "Gist: %s\nProposed: %s" % ("https://gist.github.com/%s" % bot.config.get('module: github', 'jslib_gist'),
                    ', '.join(gi.files).encode('utf8')))
            return None
    else:
        util.give_help(bot, args[0], "(propose|list|future) [proposed-func-name]")
Exemplo n.º 7
0
def tell(bot, args):
    if len(args) >= 4 and args[2] == "about":
        what = ' '.join(args[3:]).lower()
        library = {
                'yourself': "I'm an awesome lil bot n.n",
                'irc': "IRC stands for Internet Relay Chat, and you're using it this very minute! :O",
                'enter': "Stop pressing the Enter key so much! Grrrrr. Rage rage rage.",
                'sleep': "Sleep's pretty good, yep. You should do it sometime.",
                'bacon': "Lemme tell you something. Bacon, is good for you. (see http://www.youtube.com/watch?v=2T_obaO46Bo for details.)",
                'cubestormer': "The CubeStormer II is an awesome LEGO Mindstorms\x99 NXT robot that can solve Rubik's Cubes in a matter of seconds. See http://www.youtube.com/watch?v=_d0LfkIut2M for a video demonstration.",
                'ql': "Quantum Levitation is fecking awesome. See http://www.youtube.com/watch?v=Ws6AAhTw7RA and http://www.youtube.com/watch?v=VyOtIsnG71U",
                'xbot': "See https://github.com/aki--aki/xbot :D"
        }
        if library.get(what):
            if bot.inv['rooms'].get(bot.remote['receiver']):
                if args[1].lower() in [nick.lower() for nick in bot.inv['rooms'].get(bot.remote['receiver'])]:
                    util.answer(bot, "%s: %s" % (args[1], library[what]))
                else:
                    util.answer(bot, "%s: %s isn't in this channel." % (bot.remote['nick'], args[1]))
            else:
                util.answer(bot, "Triggering this command privately is not allowed.")
        else:
            util.answer(bot, "Dunno about that, n***a.")
    else:
        util.give_help(bot, args[0], "<nick> about <item>")
Exemplo n.º 8
0
Arquivo: _io.py Projeto: txanatan/xbot
def join(bot, args):
    if len(args) == 2:
        if args[1] not in Bot.inv['rooms']:
            write(("JOIN", args[1]))
        else:
            util.answer(bot, "I'm already in that channel, noob.")
    else:
        util.give_help(bot, args[0], "<channel>")
Exemplo n.º 9
0
def times(bot, args):

    def plural(word, num):
        return word if num == 1 else word + "s"
    
    error = "%s%s: Invalid bus stop number." % (bot.prefix, args[0])
    
    if len(args) == 2:
        try:
            if len(args[1]) == 4:
                stop = int(args[1])
                if stop < 1 or stop > 9999:
                    raise ValueError
            else:
                raise ValueError
        except ValueError:
            util.answer(bot, error)
            return None
        
        stops = json.loads(urllib2.urlopen('http://www.maxx.co.nz/base/StopInfo/FindStopsByNumber/%d.aspx' % stop).read())
        if not stops['recordcount']:
            util.answer(bot, error)
            return None
            
        raw_services = json.loads(urllib2.urlopen('http://www.maxx.co.nz/base/DepartureBoard2/RealTime/%d.aspx' % stop).read())
        #services = json.loads('[{"route":"974","toLocation":"BEACH HAVEN","scheduledDeparture":"2012-08-13T12:00:00.000Z","estimatedDeparture":"2012-08-13T01:00:00.000Z","timestamp":"2012-08-13T11:52:12.937Z"}]')
        results = []
        
        services = sorted(raw_services, key=lambda d: d['estimatedDeparture'])
        
        if services:
            for service in services:
                dt_shd = datetime.datetime.strptime(service['scheduledDeparture'], '%Y-%m-%dT%H:%M:%S.000Z')
                dt_est = datetime.datetime.strptime(service['estimatedDeparture'], '%Y-%m-%dT%H:%M:%S.000Z')
                dt_dif = dt_est - datetime.datetime.utcnow()
                dt_dly = dt_est - dt_shd
                delay = dt_dly.seconds / 60
                departure = dt_dif.seconds / 60
                
                if dt_dif.seconds > 3600:
                    continue
                
                if dt_dly.seconds > 3600:
                    delay = 1440 - delay
                    offset = '(%d %s early)' % (delay, plural('minute', delay))
                else:
                    if delay != 0:
                        offset = '(%d %s late)' % (delay, plural('minute', delay))
                    else:
                        offset = '(on schedule)'
                
                results.append(("%s: %s %s %s" % (service['route'], service['toLocation'], ('in %d %s' % (departure, plural('minute', departure))) if departure != 0 else 'is DUE', offset)).encode('utf-8'))
        
        util.answer(bot, '\n'.join(results) or "No buses imminent.")
    
    else:
        util.give_help(bot, args[0], "<bus stop number>")
Exemplo n.º 10
0
def twss(bot, args):
    if len(args) > 1:
        quote = ' '.join(args[1:])
        if quote.startswith('"') and quote.endswith('"'):
            util.answer(bot, "%s <- that's what she said." % quote)
        else:
            util.give_help(bot, args[0], "<quote>")
    else:
        util.answer(bot, "That's what she said.")
Exemplo n.º 11
0
Arquivo: _io.py Projeto: txanatan/xbot
def raw(bot, args):
    if len(args) > 1:
        arguments = ' '.join(args[1:]).split(" :")
        left = arguments[0].split()
        try: message = arguments[1]
        except: message = None
        Bot._sendq(left, message)
    else:
        util.give_help(bot, args[0], "<raw command>")
Exemplo n.º 12
0
Arquivo: _io.py Projeto: txanatan/xbot
def set_prefix(bot, args):
    if len(args) > 1:
        if not re.match("^[!@#\\$%^&*()\[\]{}\\\\|:;\"'<>.,?~`\\-_=+]$", args[1]):
            return "Invalid prefix."
        old = bot.prefix
        bot.prefix = args[1]
        util.answer(bot, "Prefix set to %s (was %s)." % (args[1], old))
    else:
        util.give_help(bot, args[0], "<one of: !@#$%^&*()[]{}\\|:;\"'<>.,?~`-_=+>")
Exemplo n.º 13
0
Arquivo: _io.py Projeto: txanatan/xbot
def reset(bot, args):
    if len(args) > 1:
        if args[1] in library['reset']:
            pub.sendMessage("func.reset.%s" % library['reset'][args[1]], bot=bot, args=args[2:])
            return None
    
    if len(library['reset']) > 0:
        util.give_help(bot, args[0], '|'.join(library['reset']))
    else:
        util.answer(bot, "No resets registered.")
Exemplo n.º 14
0
def m8b(bot, args):
    if len(args) > 1:
        responses = [
            "It is certain.", "It is decidedly so.", "Without a doubt.", "Yes - definitely.", "You may rely on it.", "As I see it, yes.", "Most likely.", "Outlook good.", "Signs point to yes.", "Yes.",
            "Reply hazy, try again.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.",
            "Don't count on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful."
        ]
        util.answer(bot, __import__('random').choice(responses))
    else:
        util.give_help(bot, args[0], "<herp>")
Exemplo n.º 15
0
def tpb(bot, args):
    if len(args) >= 2:
        terms = " ".join(args[2:])
        res = tpb_search(terms)
        if res:
            util.answer(bot, "%s %s" % (tpb_getinfo(res), res))
        else:
            util.answer(bot, "\x02TPB:\x0f No results.")
    else:
        util.give_help(bot, args[0], "<query")
Exemplo n.º 16
0
def wiki(bot, args):
    if len(args) > 1:
        result = lookitup('%s.wp.dg.cx' % '_'.join(args[1:]), 'TXT')
        if result:
            bot._sendq(("NOTICE", bot.remote['nick']), ''.join(str(result[0]).split('"')))
            return None
        else:
            util.answer(bot, "No such article found.")
    else:    
        util.give_help(bot, args[0], "<article>")
Exemplo n.º 17
0
Arquivo: _io.py Projeto: txanatan/xbot
def kick(bot, args):
    if len(args) >= 2:
        if args[1].lower() == Bot.nick.lower():
            reply(Bot.remote['sendee'], ":(")
        else:
            if Bot.inv['rooms'][Bot.remote['receiver']][Bot.nick]['mode'] == "o":
                write(("KICK", Bot.remote['sendee'], args[1]), ' '.join(args[2:]))
            else:
                util.answer(bot, "No ops lol.")
    else:
        util.give_help(bot, args[0], "<nick>")
Exemplo n.º 18
0
def topic(bot, args):
    if len(args) >= 2:
        topic = ' '.join(args[1:])
        if Bot.remote['sendee'] == "#ualug":
            if len(topic) <= 250:
                write(("TOPIC", Bot.remote['sendee']), 'UALUG: %s [/%s] | UALUG website: http://ualug.ece.auckland.ac.nz/' % (topic, Bot.remote['nick']))
            else:
                reply(Bot.remote['sendee'], "Sorry %s that topic is too long." % Bot.remote['nick'])
        else:
            write(("TOPIC", Bot.remote['sendee']), ' '.join(args[1:]))
    else:
        util.give_help(bot, args[0], "<topic>")
Exemplo n.º 19
0
def sorting_hat(bot, args):
    if len(args) == 2:
        nicks = bot.inv['rooms'].get(bot.remote['receiver'])
        if nicks:
            if args[1].lower() in [nick.lower() for nick in nicks]:
                houses = ['Gryffindor', 'Hufflepuff', 'Ravenclaw', 'Slytherine']
                util.answer(bot, houses[sum(ord(c) for c in args[1]) % 4] + '!')
            else:
                util.answer(bot, "But they're not here!")
        else:
            util.answer(bot, "It's a secret.")
    else:    
        util.give_help(bot, args[0], "<nick>")
Exemplo n.º 20
0
def man(bot, args):
    if len(args) == 2:
        if len(args[1]) < 15:
            url = "http://unixhelp.ed.ac.uk/CGI/man-cgi?%s" % args[1]
            result = urllib2.urlopen(url, timeout = 5)
            if len(result.read(401)) > 400:
                util.answer(bot, "Linux man page for %s: %s" % (args[1], url))
            else:
                util.answer(bot, "No man page for '%s' found." % args[1])
        else:
            util.answer(bot, "That's probably bs.")
    else:
        util.give_help(bot, args[0], "<binary file>")
Exemplo n.º 21
0
Arquivo: _io.py Projeto: txanatan/xbot
def part(bot, args):
    if len(args) == 1:
        channel = Bot.remote['sendee']
    elif len(args) == 2:
        channel = args[1]
    else:
        util.give_help(bot, args[0], "[channel]")
        return None
    
    if channel in Bot.inv['rooms']:
        write(("PART", channel))
    else:
        util.answer(bot, "I'm not in that channel, noob.")
Exemplo n.º 22
0
Arquivo: _io.py Projeto: txanatan/xbot
def voice(bot, args):
    args = [arg.lower() for arg in args]
    if len(args) == 2:
        if args[1] == "off":
            write(("PRIVMSG", Bot.remote['sendee']), "\x01ACTION stays quiet.\x01")
            Bot.voice = False
            return None
        elif args[1] == "on":
            write(("PRIVMSG", Bot.remote['sendee']), "\x01ACTION resumes normal operation.\x01")
            Bot.voice = True
            return None
    
    util.give_help(bot, args[0], "on|off")
Exemplo n.º 23
0
def info(bot, args):
    if len(args) > 1:
        title = ' '.join(args[1:])
        data = json.load(urllib2.urlopen('http://www.imdbapi.com/?%s' % urllib.urlencode({'t': title}), timeout = 45))
        if 'Plot' in data:
            response = "%s (%s): %s\n%s, %s/10, %s. %s" % (data['Title'], data['Year'], data['Plot'],
                                                            data['Rated'] if data['Rated'] != 'N/A' else 'Unrated',
                                                            data['imdbRating'] if data['imdbRating'] != 'N/A' else '?',
                                                            data['Genre'], 'http://www.imdb.com/title/%s/' % data['imdbID'])
            util.answer(bot, response.encode('utf-8'))
        else:
            util.answer(bot, '%s%s: No such movie found.' % (bot.prefix, args[0]))
    else:
        util.give_help(bot, args[0], "<movie title>")
Exemplo n.º 24
0
Arquivo: _io.py Projeto: txanatan/xbot
def perms(bot, args):
    if len(args) == 3:
        user = args[2].lower()
        if args[1] == "deny":
            if user not in Bot.inv['banned']:
                Bot.inv['banned'].append(user)
            else:
                reply(Bot.remote['sendee'], "User already denied.")
        elif args[1] == "allow":
            if user in Bot.inv['banned']:
                Bot.inv['banned'].remove(user)
            else:
                reply(Bot.remote['sendee'], "User wasn't denied to start with.")
    else:
        util.give_help(bot, args[0], "allow|deny <nick>")
Exemplo n.º 25
0
def cookie(bot, args):
    if len(args) == 2:
        nicks = bot.inv['rooms'].get(bot.remote['receiver'])
        if nicks:
            if args[1].lower() in [nick.lower() for nick in nicks]:
                if args[1].lower() != bot.name.lower():
                    util.answer(bot, "\x01ACTION gives %s a cookie.\x01" % args[1])
                else:
                    util.answer(bot, "OM NOM NOM NOM.")
            else:
                util.answer(bot, "Who?")
        else:
            util.answer(bot, "Triggering this command privately is not allowed.")
    else:
        util.give_help(bot, args[0], "<nick>")
Exemplo n.º 26
0
Arquivo: js.py Projeto: txanatan/xbot
def js_run(bot, args):
    if len(args) > 1:
        if re.match(".+:$", args[1]):
            filters = re.sub(":$", '', args[1]).split(',')
            command = ' '.join(args[2:])
        else:
            filters = []
            command = ' '.join(args[1:])
        
        if 'http' in filters:
            bot._debug("Getting js from http: %s" % command)
            command = urllib2.urlopen(command, timeout = 5).read()
            filters.remove('http')
        
        if 'gist' in filters:
            bot._debug("Getting js from gist: %s" % command)
            command = urllib2.urlopen("https://raw.github.com/gist/%s" % command, timeout = 5).read()
            filters.remove('gist')
        
        result = execute(bot, command, filters)
        
        if result == False:
            util.answer(bot, "Took too long, n***a.")
            return None
        
        if result != None and len(result) > 0:
            if len(result.split('\n')) > 4 or len(result) > 200:
                bot._debug('Going to upload to sprunge...')
                service = ['curl', '-F', 'sprunge=<-', 'http://sprunge.us']
                for n in range(2):
                    p = subprocess.Popen(service, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
                    paste = p.communicate(input="/* >>> %s\n<<< */\n\n%s" % (command, result))[0]
                    try:
                        util.answer(bot, "%s?js" % re.findall('(http://.*)', paste, re.S)[0].strip())
                        return None
                    except IndexError:
                        pass
                util.answer(bot, "!%s: error pasting output." % args[0])
            else:
                bot._debug('Returning locally...')
                message = "\n".join([("\x01ACTION %s\x01" % re.sub("^\\/me ","", r) if re.match("^\\/me ", r) else r) for r in result.split("\n")])
                util.answer(bot, message)
    else:
        util.give_help(bot, args[0], "[FILTERS:] <expr>")
        util.answer(bot, "\tAvailable filters: pretty, coffee, http, gist.")
        util.answer(bot, "\tE.g. %s%s pretty,coffee: <coffee_expr>" % (bot.prefix, args[0]))
        util.answer(bot, "\t     %s%s http: <url>" % (bot.prefix, args[0]))
        util.answer(bot, "\t     %s%s gist: <gist_id>" % (bot.prefix, args[0]))
Exemplo n.º 27
0
def mishimmie(bot, args):
    if len(args) >= 2:
        url = "";
        if re.match("id:", args[1]):
            terms = re.sub('id:', '', args[1])
            url = "http://shimmie.katawa-shoujo.com/post/view/%s" % urllib2.quote(terms)
        else:
            terms = ' '.join(args[1:])
            url = "http://shimmie.katawa-shoujo.com/post/list/%s/1" % urllib2.quote(terms)

        res = miscan(bot, url)
        if res:
            util.answer(bot, "\x02Mishimmie:\x02 %s // %s" % (res['desc'], res['url']))
        else:
            util.answer(bot, "\x02Mishimmie:\x02 No results.")

    else:
        util.give_help(bot, args[0], "<query> -- search the Mishimmie for <query>")
Exemplo n.º 28
0
def usage(bot, args):
    if len(args) == 1:
        result = ""
        
        if not re.match("(off|false|disabled|n)", bot.config.get('module: usage', 'two_degrees')):
            session = cookielib.CookieJar()
            opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(session))
            opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko/20100101 Firefox/11.0')]
            
            form = lxml.html.fromstring(opener.open('https://secure.2degreesmobile.co.nz/web/ip/login').read()).xpath("//form[@name='loginFrm']")
            
            if not form:
                result += "2degrees: Error, cannot find login form."
            else:
                account = opener.open(form[0].get('action'), urllib.urlencode(
                    {
                        'userid': bot.config.get('module: usage', 'td_login'),
                        'password': bot.config.get('module: usage', 'td_pass'),
                        'hdnAction': 'login',
                        'hdnAuthenticationType': 'M'
                    }
                )).read()
                remaining = lxml.html.fromstring(account).xpath("//td[@class='tableBillamount']/text()")
                
                if not remaining:
                    result += "2degrees: Error, cannot get remaining data.\n"
                else:
                    result += "3G: %s remaining\n" % ', '.join(remaining).encode('utf-8')
        
        
        if not re.match("(off|false|disabled|n)", bot.config.get('module: usage', 'orcon')):
            orcon = lxml.html.fromstring(opener.open('http://www.orcon.net.nz/modules/usagemeter/view/CosmosController.php').read()).xpath('//dd[last()]/text()')
            if not orcon:
                result += "Orcon: Error, cannot fetch details."
            else:
                result += "ADSL: %s used" % orcon[0].encode('utf-8')
        
        if len(result) > 0:
            util.answer(bot, result)
        else:
            util.answer(bot, "%s%s: Not configured." % (bot.prefix, args[0]))
    else:
        util.give_help(bot, args[0], "")
Exemplo n.º 29
0
Arquivo: _io.py Projeto: txanatan/xbot
def set_debug(bot, args):
    result = []
    if len(args) > 2:
        if re.search("(on|yes|true|1)", args[2]):
            bot.verbose = True
            result.append("Verbose logging: on")
        else:
            bot.verbose = False
            result.append("Verbose logging: off")
    if len(args) > 1:
        if re.search("(on|yes|true|1)", args[1]):
            bot.debug = True
            result.append("Debug: on")
        else:
            bot.debug = False
            result.append("Debug: off")
        
        util.answer(bot, "\n".join(result))
    else:
        util.give_help(bot, args[0], "on|off [verbose?(on|off)]")
Exemplo n.º 30
0
def set_og(bot, args):
    result = []
    if len(args) > 2:
        if re.search("(on|yes|true|1)", args[2]):
            bot.config.set("module: open_graph", "youtube", "on")
            result.append("YouTube: on")
        else:
            bot.config.set("module: open_graph", "youtube", "off")
            result.append("YouTube: off")
    if len(args) > 1:
        if re.search("(on|yes|true|1)", args[1]):
            bot.config.set("module: open_graph", "enabled", "on")
            result.append("Open Graph scanning: on")
        else:
            bot.config.set("module: open_graph", "enabled", "off")
            result.append("Open Graph scanning: off")
        
        util.answer(bot, ", ".join(result))
    else:
        util.give_help(bot, args[0], "on|off [youtube?(on|off)]")