Example #1
0
def lsog(bot, args):
    excludes = [ k.strip() for k in bot.config.get("module: open_graph", "excludes").split(",") ]
    og = "off" if re.match("(no|false|off|0)", bot.config.get("module: open_graph", "enabled")) else "on"
    yt = "off" if re.match("(no|false|off|0)", bot.config.get("module: open_graph", "youtube")) else "on"

    fmt = "Open Graph scanning: %s, YouTube scanning: %s\nHandlers: %s\nDisabled for: %s" % (og, yt, ", ".join(library['url']), ", ".join(excludes))
    util.answer(bot, fmt)
Example #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>")
Example #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>")
Example #4
0
def og_miscan(bot, url):
    res = miscan(bot, url)

    if res:
        util.answer(bot, "\x02Mishimmie:\x02 %s" % res['desc'])
    else:
        util.answer(bot, "\x02Mishimmie:\x02 No results.")
Example #5
0
File: _io.py Project: 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]")
Example #6
0
def write(bot, args):
    responses = [
        "Only if you do!",
        "After you get 100 more words~~~",
        "Talk less, write more!"
    ]
    util.answer(bot, __import__('random').choice(responses))
Example #7
0
def clever_scan(bot):
    # someone is talking to the bot
    if re.search('^%s(?:\:|,)' % re.escape(bot.nick.lower()), bot.remote['message'].lower()):
        if 'cleverbot' not in bot.inv: bot.inv['cleverbot'] = {}
        if bot.remote['receiver'] not in bot.inv['cleverbot']:
            bot.inv['cleverbot'][bot.remote['receiver']] = CleverBot()
        query = bot.remote['message'][len(bot.nick)+2:].decode('ascii', 'ignore')
        util.answer(bot, "%s: %s" % (bot.remote['nick'], re.compile('cleverbot', re.IGNORECASE).sub(bot.nick, bot.inv['cleverbot'][bot.remote['receiver']].query(bot, query))))
Example #8
0
File: _io.py Project: 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>")
Example #9
0
def lick(bot, args):
    botresponses = ["L-lewd!", "\x01ACTION blushes\x01", "\x01ACTION licks %s\x01" % bot.remote["nick"]]

    if len(args) != 1:
        tonick = " ".join(args[1:])
        responses = ["%s licks %s" % (bot.remote["nick"], tonick), "%s doesn't lick %s" % (bot.remote["nick"], tonick)]
        util.answer(bot, __import__("random").choice(responses))
    else:
        util.answer(bot, __import__("random").choice(botresponses))
Example #10
0
def fill(bot, args):
    botresponses = ["B-but jetto will never fill me!", "L-lewd!"]

    if len(args) != 1:
        tonick = " ".join(args[1:])
        responses = ["lolis~", "candy~", "a daki pillow"]
        util.answer(bot, "%s fills %s with %s" % (bot.remote["nick"], tonick, __import__("random").choice(responses)))
    else:
        util.answer(bot, __import__("random").choice(botresponses))
Example #11
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.")
Example #12
0
def og_scan(bot):
    # scan for urls, check to see if OpenGraph validity and return site name and page title.
    # if OpenGraph not found, tries <title> tag.
    for url in re.findall('(?P<url>(https?://|www.)[^\s]+)', bot.remote['message']):
        bot._debug("Found a URL: %s" % url[0])
        try:
            util.answer(bot, open_graph(bot, url[0]).encode('utf8'))
        except AttributeError:
            pass
Example #13
0
File: _io.py Project: 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: !@#$%^&*()[]{}\\|:;\"'<>.,?~`-_=+>")
Example #14
0
File: _io.py Project: 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.")
Example #15
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>")
Example #16
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>")
Example #17
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")
Example #18
0
File: _io.py Project: 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>")
Example #19
0
def get_results(bot, args):
    tree = lxml.etree.parse('http://www.lottoresults.co.nz/', lxml.etree.HTMLParser())
    images = tree.xpath("//td/img[contains(@src, 'img/lotto/')]")
    draw = tree.xpath("//input[@name='draw']")[0].get('value')
    results = [re.match('img/lotto/([0-9]+)\.gif', result.get('src')).group(1) for result in images]
    
    lotto = results[0:6]
    bonus_ball = results[6]
    strike = results[7:11]
    powerball = results[11]
    
    util.answer(bot, "Weekly draw #%d as follows\nLotto: %s, bonus %d, powerball %d. Strike order: %s." % (int(draw), ', '.join(lotto), int(bonus_ball), int(powerball), ', '.join(strike)))
Example #20
0
def poke(bot, args):
    botresponses = ["B-baka!", "L-lewd!", "\x01ACTION pokes %s\x01" % bot.remote["nick"]]

    if len(args) != 1:
        tonick = " ".join(args[1:])
        responses = [
            "%s pokes %s" % (bot.remote["nick"], args[1]),
            "%s doesn't poke %s" % (bot.remote["nick"], args[1]),
        ]
        util.answer(bot, __import__("random").choice(responses))
    else:
        util.answer(bot, __import__("random").choice(botresponses))
Example #21
0
def show_help(bot, args):
    can_do = bot.remote['host'] in [host.strip() for host in bot.config.get(bot.network, 'admin_hostnames').split(',')]
    #can_do = can_do or bot.remote['nick'] in [nick.strip() for nick in bot.config.get(bot.network, 'admin').split(',')]
    if can_do:
        if len(args) == 2 and args[1] == "admin":
            coms = library['admin']
        else:
            coms = library['common']
    else:
        coms = library['common']
    
    util.answer(bot, "Available commands: %s" % ', '.join(sorted(coms)))
Example #22
0
File: _io.py Project: 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.")
Example #23
0
def marry(bot, args):
    botresponses = ["\x01ACTION agrees\x01", "\x01ACTION refuses\x01", "W-why would I want to do that?"]

    if len(args) != 1:
        tonick = " ".join(args[1:])
        responses = [
            "%s marries %s" % (bot.remote["nick"], tonick),
            "%s agrees" % tonick,
            "%s refuses" % tonick,
            "\x01ACTION sets up a huge wedding for %s and %s\x01" % (bot.remote["nick"], tonick),
        ]
    else:
        util.answer(bot, __import__("random").choice(botresponses))
Example #24
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>")
Example #25
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>")
Example #26
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]")
Example #27
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>")
Example #28
0
def butt_scan(bot):
    # per 1% chance, butt into someone's conversation
    if random.random() > 0.99:
        if not bot.remote['message'].startswith("\x01"):
            words = bot.remote['message'].split()
            if len(words) > 2:
                for n in range(random.randint(1, 3)):
                    if random.random() > 0.5:
                        words[random.randint(1, len(words)-1)] = "butt"
                    else:
                        for m, word in enumerate(words):
                            if len(word) > 4 and m > 0:
                                if random.random() > 0.3:
                                    words[m] = words[m][:-4] + "butt"
            
                util.answer(bot, ' '.join(words))
Example #29
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>")
Example #30
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], "")