Пример #1
0
def auto_honeypot(code, input):
    """Check joining users against the Project Honeypot Database"""
    if not code.config('honeypot_on_join') or input.nick == code.nick:
        return
    global db

    ip = get_ip(input.host)
    try:
        abuser = check(ip)
    except:
        return output.error(
            'Failed to get IP information. Project Honeypot seems to be down!')
    if abuser:
        # First, we need to check if we've already checked for it, and got a
        # match...
        if ip in db:
            return
        db.append(ip)
        database.set(code.default, db, 'honeypot')
        if code.config('kickban_on_honeypot') and code.chan[input.sender][
                code.nick]['op']:
            # Wants to kickban, and we've got op. BANHAMMER TIME!
            code.write(['MODE', input.sender, '+b', '*!*@' + input.host])
            code.write(['KICK', input.sender, input.nick], abuser)
        code.say(abuser)
Пример #2
0
def ignore(inp, notice=None, bot=None, chan=None, db=None):
    """ignore [channel] <nick|host> -- Makes the bot ignore <nick|host>."""
    ignorelist = database.get(db, 'channels', 'ignored', 'chan', chan)
    targets = inp.split()
    for target in targets:
        target = user.get_hostmask(target, db)
        if (user.is_admin(target, chan, db, bot)):
            notice(
                u"[{}]: {} is an admin and cannot be ignored.".format(
                    chan, inp))
        else:
            if ignorelist and target in ignorelist:
                notice(u"[{}]: {} is already ignored.".format(chan, target))
            else:
                ignorelist = '{} {}'.format(target, ignorelist)
                database.set(
                    db,
                    'channels',
                    'ignored',
                    ignorelist,
                    'chan',
                    chan)

                notice(u"[{}]: {} has been ignored.".format(chan, target))
    return
Пример #3
0
def onjoined(inp, input=None, conn=None, chan=None, raw=None, db=None):
    database.set(db, 'users', 'mask',
                 input.mask.lower().replace('~', ''), 'nick',
                 input.nick.lower())
    mask = user.format_hostmask(input.mask)
    disabled_commands = database.get(db, 'channels', 'disabled', 'chan', chan)
    if not disabled_commands: disabled_commands = ""

    if not 'banlist' in disabled_commands:
        #check if bans
        banlist = database.get(db, 'channels', 'bans', 'chan', chan)
        if banlist and mask in banlist:
            conn.send(u"MODE {} {} *{}".format(input.chan, '+b', mask))
            conn.send(u"KICK {} {} :{}".format(input.chan, input.nick,
                                               'I dont think so Tim.'))

    if not 'autoop' in disabled_commands:
        #check if ops
        autoop = database.get(db, 'channels', 'autoop', 'chan', chan)
        if autoop:
            autoops = database.get(db, 'channels', 'admins', 'chan', chan)
        else:
            autoops = database.get(db, 'channels', 'autoops', 'chan', chan)

        if autoops and mask in autoops:
            conn.send(u"MODE {} {} {}".format(input.chan, '+o', input.nick))

    if not 'greeting' in disabled_commands:
        # send greeting
        greeting = database.get(db, 'users', 'greeting', 'nick', input.nick)

        if greeting: return greeting
Пример #4
0
def time(inp, nick="", reply=None, db=None, notice=None):
    "time [location] [dontsave] | [@ nick] -- Gets time for <location>."

    save = True
    
    if '@' in inp:
        nick = inp.split('@')[1].strip()
        location = database.get(db,'users','location','nick',nick)
        if not location: return "No location stored for {}.".format(nick.encode('ascii', 'ignore'))
    else:
        location = database.get(db,'users','location','nick',nick)
        if not inp:
            if not location:
                notice(time.__doc__)
                return
        else:
            if not location: save = True
            if " save" in inp: save = True
            location = inp.split()[0]

    # now, to get the actual time
    try:
        url = "https://www.google.com/search?q=time+in+%s" % location.replace(' ','+').replace(' save','')
        html = http.get_html(url)
        prefix = html.xpath("//div[contains(@class,'vk_c vk_gy')]//span[@class='vk_gy vk_sh']/text()")[0].strip()
        curtime = html.xpath("//div[contains(@class,'vk_c vk_gy')]//div[@class='vk_bk vk_ans']/text()")[0].strip()
        day = html.xpath("//div[contains(@class,'vk_c vk_gy')]//div[@class='vk_gy vk_sh']/text()")[0].strip()
        date = html.xpath("//div[contains(@class,'vk_c vk_gy')]//div[@class='vk_gy vk_sh']/span/text()")[0].strip()
    except IndexError:
        return "Could not get time for that location."

    if location and save: database.set(db,'users','location',location,'nick',nick)

    return u'{} is \x02{}\x02 [{} {}]'.format(prefix, curtime, day, date)
Пример #5
0
def weather(inp, nick=None, reply=None, db=None, notice=None):
    "weather | <location> [save] | <@ user> -- Gets weather data for <location>."
    save = True
    
    if '@' in inp:
        save = False
        nick = inp.split('@')[1].strip()
        loc = database.get(db,'users','location','nick',nick)
        if not loc: return "No location stored for {}.".format(nick.encode('ascii', 'ignore'))
    else:
        loc = database.get(db,'users','location','nick',nick)
        if not inp:
            if not loc:
                notice(weather.__doc__)
                return
        else:
            # if not loc: save = True
            if " dontsave" in inp: 
                inp = inp.replace(' dontsave','')
                save = False
            loc = inp.replace(' ','_') #.split()[0]

    location = http.quote_plus(loc)
    # location = location.replace(',','').replace(' ','-')

    # now, to get the actual weather
    try:
        data = get_weather('%s' % location)
    except KeyError:
        return "Could not get weather for that location."

    if location and save: database.set(db,'users','location',location,'nick',nick)

    # put all the stuff we want to use in a dictionary for easy formatting of the output
    weather_data = {
        "place": data['location']['city'],
        "conditions": data['item']['condition']['text'],
        "temp_f": data['item']['condition']['temp'],
        "temp_c": data['item']['condition']['temp_c'],
        "humidity": data['atmosphere']['humidity'],
        "wind_kph": data['wind']['speed_kph'],
        "wind_mph": data['wind']['speed'],
        "wind_text": data['wind']['text'],
        "forecast": data['item']['forecast'][0]['text'],
        "high_f": data['item']['forecast'][0]['high'],
        "high_c": data['item']['forecast'][0]['high_c'],
        "low_f": data['item']['forecast'][0]['low'],
        "low_c": data['item']['forecast'][0]['low_c'],
        "_forecast": data['item']['forecast'][1]['text'],
        "_high_f": data['item']['forecast'][1]['high'],
        "_high_c": data['item']['forecast'][1]['high_c'],
        "_low_f": data['item']['forecast'][1]['low'],
        "_low_c": data['item']['forecast'][1]['low_c']
    }
 
    reply("\x02{place}\x02 - \x02Current:\x02 {conditions}, {temp_f}F/{temp_c}C, Humidity: {humidity}%, " \
            "Wind: {wind_kph}KPH/{wind_mph}MPH {wind_text}, \x02Today:\x02 {forecast}, " \
            "High: {high_f}F/{high_c}C, Low: {low_f}F/{low_c}C. " \
            "\x02Tomorrow:\x02 {_forecast}, High: {_high_f}F" \
            "/{_high_c}C, Low: {_low_f}F/{_low_c}C.".format(**weather_data))
Пример #6
0
def save(inp, nick=None, reply=None, db=None, notice=None):
    "weather | <location> [save] | <@ user> -- Gets weather data for <location>."
    save = True
    loc = database.get(db, 'users', 'location', 'nick', nick)
    if '@' in inp:
        save = False
        nick = inp.split('@')[1].strip()
        loc = database.get(db, 'users', 'location', 'nick', nick)
        if not loc:
            return "No location stored for {}.".format(
                nick.encode('ascii', 'ignore'))
    else:
        loc = database.get(db, 'users', 'location', 'nick', nick)
        if not inp:
            if not loc:
                notice(weather.__doc__)
                return
        else:
            # if not loc: save = True
            if " dontsave" in inp:
                inp = inp.replace(' dontsave', '')
                save = False
            loc = inp.replace(' ', '_')  #.split()[0]

    if location and save:
        database.set(db, 'users', 'location', location, 'nick', nick)
Пример #7
0
def horoscope(inp, db=None, notice=None, nick=None):
    """horoscope <sign> [save] -- Get your horoscope."""
    save = False
    database.init(db)

    if '@' in inp:
        nick = inp.split('@')[1].strip()
        sign = database.get(db,'users','horoscope','nick',nick)
        if not sign: return "No horoscope sign stored for {}.".format(nick)
    else:
        sign = database.get(db,'users','horoscope','nick',nick)
        if not inp:
            if not sign:
                notice(horoscope.__doc__)
                return
        else:
            if not sign: save = True
            if " save" in inp: save = True
            sign = inp.split()[0]

    url = "http://www.astrology.com/horoscope/daily/%s.html" % sign
    try:
        request = urllib2.Request(url, None, headers)
        page = urllib2.urlopen(request).read()
        result = BeautifulSoup(page, 'lxml')
        horoscopetxt = http.strip_html(str(result.find('div', attrs={'class':('page-horoscope-text')})))
    except: return "Check your spelling, acronyms and short forms are not accepted."


    if sign and save: database.set(db,'users','horoscope',sign,'nick',nick)
    horoscopetxt = horoscopetxt.rsplit('.', 2)[0]
    horoscopetxt += '.'
    return u"{}".format(horoscopetxt)
Пример #8
0
def battlestation(inp, nick=None, db=None, notice=None):
    "battlestation <url | @ person> -- Shows a users Battlestation."
    if inp:
        if 'http' in inp:
            database.set(db, 'users', 'battlestation', inp.strip(), 'nick',
                         nick)
            notice("Saved your battlestation.")
            return
        elif 'del' in inp:
            database.set(db, 'users', 'battlestation', '', 'nick', nick)
            notice("Deleted your battlestation.")
            return
        else:
            if '@' in inp:
                nick = inp.split('@')[1].strip()
            else:
                nick = inp.strip()

    result = database.get(db, 'users', 'battlestation', 'nick', nick)
    if result:
        return '{}: {}'.format(nick, result)
    else:
        if '@' not in inp:
            notice(battlestation.__doc__)
        return 'No battlestation saved for {}.'.format(nick)
Пример #9
0
def cmdflood(inp, conn=None, chan=None, notice=None, db=None):
    """cmdflood [channel] <number> <duration> | disable -- Enables commandflood protection for a channel.
    ex: .cmdflood 3 30 -- Allows 3 commands in 30 seconds, set disable to disable"""

    if len(inp) == 0:
        floods = database.get(db, 'channels', 'cmdflood', 'chan', chan)
        if floods:
            notice(u"[{}]: Command Flood: {} commands in {} seconds".format(
                chan,
                floods.split()[0],
                floods.split()[1]))
        else:
            notice(u"[{}]: CMD Flood is disabled.".format(chan))
            notice(cmdflood.__doc__)
    elif "disable" in inp:
        database.set(db, 'channels', 'cmdflood', None, 'chan', chan)
        notice(u"[{}]: Command Flood Protection Disabled.".format(chan))
    else:
        flood_num = inp.split()[0]
        flood_duration = inp.split()[1]
        floods = '{} {}'.format(flood_num, flood_duration)
        database.set(db, 'channels', 'cmdflood', floods, 'chan', chan)
        notice(
            u"[{}]: Command Flood Protection limited to {} commands in {} seconds."
            .format(chan, flood_num, flood_duration))
    return
Пример #10
0
def horoscope(inp, db=None, notice=None, nick=None):
    """horoscope <sign> [save] -- Get your horoscope."""
    save = False
    database.init(db)
    
    if '@' in inp:
        nick = inp.split('@')[1].strip()
        sign = database.get(db,'users','horoscope','nick',nick)
        if not sign: return "No horoscope sign stored for {}.".format(nick)
    else:
        sign = database.get(db,'users','horoscope','nick',nick)
        if not inp: 
            if not sign:
                notice(horoscope.__doc__)
                return
        else:
            if not sign: save = True
            if " save" in inp: save = True
            sign = inp.split()[0]

    url = "http://my.horoscope.com/astrology/free-daily-horoscope-%s.html" % sign
    try:
        result = http.get_soup(url)
        title = result.find_all('h1', {'class': 'h1b'})[1].text
        horoscopetxt = result.find('div', {'id': 'textline'}).text
    except: return "Could not get the horoscope for {}.".format(sign.encode('utf8'))

    if sign and save: database.set(db,'users','horoscope',sign,'nick',nick)
    
    return u"\x02{}\x02 {}".format(title, horoscopetxt)
Пример #11
0
def admin(inp, notice=None, bot=None, chan=None, db=None):
    """admin [channel] <add|del> <nick|host> -- Makes the user an admin."""
    inp,chan = get_chan(inp,chan)
    admins = database.get(db,'channels','admins','chan',chan)
    
    channel = chan.lower()
    command = inp.split()[0]
    nicks = inp.split()[1:]

    if 'add' in command:
        for nick in nicks:  
            nick = user.get_hostmask(nick,db)
            if admins and nick in admins:
                notice(u"[{}]: {} is already an admin.".format(chan,nick))
            else:
                admins = '{} {}'.format(nick,admins).replace('False','').strip()
                database.set(db,'channels','admins',admins,'chan',chan)
                notice(u"[{}]: {} is now an admin.".format(chan,nick))
    elif 'del' in command:
        for nick in nicks:  
            nick = user.get_hostmask(nick,db)
            if admins and nick in admins:
                admins = " ".join(admins.replace(nick,'').strip().split())
                database.set(db,'channels','admins',admins,'chan',chan)
                notice(u"[{}]: {} is no longer an admin.".format(chan,nick))
            else:
                notice(u"[{}]: {} is not an admin.".format(chan,nick))
    return
Пример #12
0
def enable(inp, notice=None, bot=None, chan=None, db=None):
    """enable [#channel] <commands|all> -- Enables commands for a channel.
    (you can enable multiple commands at once)"""

    disabledcommands = database.get(db, 'channels', 'disabled', 'chan', chan)
    targets = inp.split()
    if 'all' in targets or '*' in targets:
        database.set(db, 'channels', 'disabled', '', 'chan', chan)
        notice(u"[{}]: All commands are now enabled.".format(chan))
    else:
        for target in targets:
            if disabledcommands and target in disabledcommands:
                disabledcommands = disabledcommands.split(" ")
                for commands in disabledcommands:
                    if target == commands:
                        disabledcommands = " ".join(disabledcommands)
                        disabledcommands = " ".join(
                            disabledcommands.replace(target,
                                                     '').strip().split())
                        database.set(db, 'channels', 'disabled',
                                     disabledcommands, 'chan', chan)
                        notice(u"[{}]: {} is now enabled.".format(
                            chan, target))
                    else:
                        pass
            else:
                if target in " ".join(bot.config["disabled_commands"]):
                    notice(
                        u"[{}]: {} is globally disabled. Use .genable {} to enable."
                        .format(chan, target, target))
                else:
                    notice(u"[{}]: {} is not disabled.".format(chan, target))
    return
Пример #13
0
def onjoined(inp,input=None, conn=None, chan=None,raw=None, db=None):
    database.set(db,'users','mask',input.mask.lower().replace('~',''),'nick',input.nick.lower())
    mask = user.format_hostmask(input.mask)
    disabled_commands = database.get(db,'channels','disabled','chan',chan)
    if not disabled_commands: disabled_commands = ""

    if not 'banlist' in disabled_commands:
        #check if bans
        banlist = database.get(db,'channels','bans','chan',chan)
        if banlist and mask in banlist:
            conn.send("MODE {} {} *{}".format(input.chan, '+b', mask))
            conn.send("KICK {} {} :{}".format(input.chan, input.nick, 'I dont think so Tim.'))

    if not 'autoop' in disabled_commands:
        #check if ops
        autoop = database.get(db,'channels','autoop','chan',chan)
        if autoop: autoops = database.get(db,'channels','admins','chan',chan)
        else: autoops = database.get(db,'channels','autoops','chan',chan)

        if autoops and mask in autoops:
            conn.send("MODE {} {} {}".format(input.chan, '+o', input.nick))

    if not 'greeting' in disabled_commands:
        # send greeting
        greeting = database.get(db,'users','greeting','nick',input.nick)

        if greeting: return greeting
Пример #14
0
def horoscope(inp, db=None, notice=None, nick=None):
    """horoscope <sign> [save] -- Get your horoscope."""
    save = False
    database.init(db)

    if '@' in inp:
        nick = inp.split('@')[1].strip()
        sign = database.get(db, 'users', 'horoscope', 'nick', nick)
        if not sign: return "No horoscope sign stored for {}.".format(nick)
    else:
        sign = database.get(db, 'users', 'horoscope', 'nick', nick)
        if not inp:
            if not sign:
                notice(horoscope.__doc__)
                return
        else:
            if not sign: save = True
            if " save" in inp: save = True
            sign = inp.split()[0]

    url = "http://my.horoscope.com/astrology/free-daily-horoscope-%s.html" % sign
    try:
        result = http.get_soup(url)
        title = result.find_all('h1', {'class': 'h1b'})[1].text
        horoscopetxt = result.find('div', {'id': 'textline'}).text
    except:
        return "Could not get the horoscope for {}.".format(
            sign.encode('utf8'))

    if sign and save:
        database.set(db, 'users', 'horoscope', sign, 'nick', nick)

    return u"\x02{}\x02 {}".format(title, horoscopetxt)
Пример #15
0
def greeting(inp, nick=None, db=None, notice=None):
    "greet <message | @ person> -- Shows a users Greeting."
    if nick == 'kimi':
        return
    try:
        if not inp or '@' in inp:
            if '@' in inp:
                nick = inp.split('@')[1].strip()
            result = database.get(db, 'users', 'greeting', 'nick', nick)
            if result:
                return '{}: {}'.format(nick, result)
            else:
                if '@' not in inp:
                    notice(greeting.__doc__)
                return 'No greeting saved for {}.'.format(nick)
        elif 'del' in inp:
            database.set(db, 'users', 'greeting', '', 'nick', nick)
            notice("Deleted your greeting.")
        else:
            # TODO clean this digusting mess it does nothing
            inp = inp.strip().replace("'", "").replace("ACTION", "").replace("PRIVMSG", "").replace("PING", "").replace("NOTICE", "").replace("\x01", "")
            database.set(db, 'users', 'greeting', '{} '.format(inp.encode('utf8')), 'nick', nick)
            notice("Saved your greeting.")
        return
    except Exception:
        return "Uwaaahh~~?"
Пример #16
0
def stats(inp, nick=None, conn=None, chan=None, db=None, notice=None):
    "battlestation <url | @ person> -- Shows a users Battlestation."
    if inp:
        if "http" in inp:
            database.set(db, 'users', 'battlestation', inp.strip(), 'nick',
                         nick)
            notice("Saved your battlestation.")
            return
        elif 'del' in inp:
            database.set(db, 'users', 'battlestation', '', 'nick', nick)
            notice("Deleted your battlestation.")
            return
        else:
            if '@' in inp: nick = inp.split('@')[1].strip()
            else: nick = inp.strip()

    result = database.get(db, 'users', 'battlestation', 'nick', nick)
    if result:
        return '{}: {}'.format(nick, result)
    else:
        if not '@' in inp: notice(battlestation.__doc__)
        return 'No battlestation saved for {}.'.format(nick)


# 4 main compounds - bench, ohp, deadlift and squat. Body weight, height and bf?
Пример #17
0
def enable(inp, notice=None, bot=None, chan=None, db=None):
    """enable [#channel] <commands|all> -- Enables commands for a channel.
    (you can enable multiple commands at once)"""

    disabledcommands = database.get(db,'channels','disabled','chan',chan)
    targets = inp.split()
    if 'all' in targets or '*' in targets:
        database.set(db,'channels','disabled','','chan',chan)
        notice(u"[{}]: All commands are now enabled.".format(chan))
    else:
        for target in targets:
            if disabledcommands and target in disabledcommands:
                disabledcommands = disabledcommands.split(" ")
                for commands in disabledcommands:
                    if target == commands:
                        disabledcommands = " ".join(disabledcommands)
                        disabledcommands = " ".join(disabledcommands.replace(target,'').strip().split())
                        database.set(db,'channels','disabled',disabledcommands,'chan',chan)
                        notice(u"[{}]: {} is now enabled.".format(chan,target))
                    else:
                        pass
            else:
                if target in " ".join(bot.config["disabled_commands"]):
                    notice(u"[{}]: {} is globally disabled. Use .genable {} to enable.".format(chan,target,target))
                else:
                    notice(u"[{}]: {} is not disabled.".format(chan,target))
    return
Пример #18
0
def enablehash(inp, notice=None, bot=None, chan=None, db=None):
    '''
    enablehash [#channel] <hashtag|all>
    Enables hashtags for a channel.
    (you can enable multiple hashtags at once, don't put # before the hashtag)
    '''

    disabledhashes = database.get(
        db, 'channels', 'disabledhashes', 'chan', chan)
    targets = inp.split()
    if 'all' in targets or '*' in targets:
        database.set(db, 'channels', 'disabledhashes', '', 'chan', chan)
        notice(u"[{}]: All commands are now enabled.".format(chan))
    else:
        for target in targets:
            if disabledhashes and target in disabledhashes:
                disabledhashes = " ".join(
                    disabledhashes.replace(
                        target, '').strip().split())
                database.set(
                    db,
                    'channels',
                    'disabledhashes',
                    disabledhashes,
                    'chan',
                    chan)
                notice(u"[{}]: {} is now enabled.".format(chan, target))
            else:
                notice(u"[{}]: {} is not disabled.".format(chan, target))
    return
Пример #19
0
def ban(inp, conn=None, chan=None, notice=None, db=None, nick=None):
    """ban [channel] <user> [reason] [timer] -- Makes the bot ban <user> in [channel].
    If [channel] is blank the bot will ban <user> in
    the channel the command was used in."""
    mode = "+b"
    reason = "#rekt"
    inp,chan = get_chan(inp,chan)
    split = inp.split(" ")
    inp_nick = split[0]

    if conn.nick in inp_nick or 'infinity' in inp_nick: 
        target = nick
        reason = "Youre silly onii-chan."
        conn.send(u"KICK {} {} :{}".format(chan, target, reason))
        return

    if len(split) > 1: reason = " ".join(split[1:])
    target = user.get_hostmask(inp_nick,db)
    if '@' in target and not '!' in target: target = '*!*{}'.format(target)
    timer = scheduler.check_for_timers(inp)
    if timer > 0: reason = "{} Come back in {} seconds!!!".format(reason,timer)
    notice(u"Attempting to ban {} in {}...".format(nick, chan))
    conn.send(u"MODE {} {} {}".format(chan, mode, target))
    conn.send(u"KICK {} {} :{}".format(chan, inp_nick, reason))

    if timer > 0: 
        notice(u"{} will be unbanned in {} seconds".format(target, timer))
        scheduler.schedule(timer, 1, "MODE {} -b {}".format(chan, target), conn)
        #scheduler.schedule(timer, 2, "PRIVMSG ChanServ :unban {} {}".format(channel, nick), conn)
    else:
        banlist = database.get(db,'channels','bans','chan',chan)
        banlist = '{} {}'.format(target,banlist).replace('False','').strip()
        database.set(db,'channels','bans',banlist,'chan',chan)
    return
Пример #20
0
def timefunction2(inp, nick="", reply=None, db=None, notice=None):
    "time [location] [dontsave] | [@ nick] -- Gets time for <location>."

    save = True
    
    if '@' in inp:
        nick = inp.split('@')[1].strip()
        location = database.get(db,'users','location','nick',nick)
        if not location: return "No location stored for {}.".format(nick.encode('ascii', 'ignore'))
    else:
        location = database.get(db,'users','location','nick',nick)
        if not inp:
            if not location:
                notice(time.__doc__)
                return
        else:
            # if not location: save = True
            if " dontsave" in inp: save = False
            location = inp.split()[0]

    # now, to get the actual time
    try:
        url = "https://time.is/%s" % location.replace(' ','+').replace(' save','')
        html = http.get_html(url)
        prefix = html.xpath("//div[@id='msgdiv']/h1/a/text()")[0].strip()
        curtime = html.xpath("//div[contains(@id,'twd')]/text()")[0].strip()
        ampm = html.xpath("//div[contains(@id,'twd')]/span/text()")[0].strip()
        date = html.xpath("//h2[contains(@id,'dd')]/text()")[0].strip()
    except IndexError:
        return "Could not get time for that location."

    if location and save: database.set(db,'users','location',location,'nick',nick)

    return u'Time in {} is \x02{} {}\x02 [{}]'.format(prefix, curtime, ampm.upper(), date)
Пример #21
0
def cmdflood(inp, conn=None, chan=None, notice=None, db=None):
    '''
    cmdflood [channel] <number> <duration> | disable
    Enables commandflood protection for a channel.
    ex: .cmdflood 3 30 - Allows 3 commands in 30 seconds,
                         set disable to disable.
    '''

    if len(inp) == 0:
        floods = database.get(db, 'channels', 'cmdflood', 'chan', chan)
        if floods:
            notice(u"[{}]: Command Flood: {} commands in {} seconds".format(
                chan, floods.split()[0], floods.split()[1]))
        else:
            notice(u"[{}]: CMD Flood is disabled.".format(chan))
            notice(cmdflood.__doc__)
    elif "disable" in inp:
        database.set(db, 'channels', 'cmdflood', None, 'chan', chan)
        notice(u"[{}]: Command Flood Protection Disabled.".format(chan))
    else:
        flood_num = inp.split()[0]
        flood_duration = inp.split()[1]
        floods = '{} {}'.format(flood_num, flood_duration)
        database.set(db, 'channels', 'cmdflood', floods, 'chan', chan)
        s = u"[{}]: Command Flood Protection limited to {} commands " \
            "in {} seconds."
        notice(s.format(chan, flood_num, flood_duration))
    return
Пример #22
0
def lastfm(code, input):
    """ lfm <username> -- Pull last played song for the user """

    db = database.get(code.nick, 'lastfm')
    if not db:
        db = {}

    if input.group(2):
        user = input.group(2).split()[0].strip()
    else:
        if input.nick not in db:
            return code.say('{b}{red}No arguments supplied! Try: "%shelp lastfm"' % code.prefix)

        user = db[input.nick]

    data = web.json(api_uri.format(user=user, key=api_key))['recenttracks']
    if len(data['track']) == 0:
        return code.say('Username {} does not exist in the last.fm database.'.format(user))

    db[input.nick] = user
    database.set(code.nick, db, 'lastfm')

    track = data['track'][0]
    artist, song, url, name = track['artist']['#text'], track['name'], track['url'], data['@attr']['user']
    code.reply(code.format('{purple}{song} -- {artist}{c} - {pink}{user}{c} - {url}').format(
        artist=artist, song=song, url=url, user=name))
Пример #23
0
def onjoined(inp,input=None, conn=None, chan=None,raw=None, db=None):
    database.set(db,'users','mask',input.mask.lower().replace('~',''),'nick',input.nick.lower())
    mask = user.format_hostmask(input.mask)
    disabled_commands = database.get(db,'channels','disabled','chan',chan)
    if not disabled_commands: disabled_commands = ""
    
    if not 'banlist' in disabled_commands:
        #check if bans
        banlist = database.get(db,'channels','bans','chan',chan)
        if banlist and mask in banlist:
            conn.send(u"MODE {} {} *{}".format(input.chan, '+b', mask))
            conn.send(u"KICK {} {} :{}".format(input.chan, input.nick, 'I dont think so Tim.'))

    if not 'autoop' in disabled_commands:
        #check if ops
        autoop = database.get(db,'channels','autoop','chan',chan)
        if autoop: autoops = database.get(db,'channels','admins','chan',chan)
        else: autoops = database.get(db,'channels','autoops','chan',chan)
        
        if autoops and mask in autoops:
            conn.send(u"MODE {} {} {}".format(input.chan, '+o', input.nick))

    if not 'greeting' in disabled_commands:
        # send greeting
        greeting = database.get(db,'users','greeting','nick',input.nick)

        if greeting: conn.msg(chan, greeting.decode('UTF-8'))
    if input.nick == "kimi":
        conn.send('PRIVMSG {} :\x02[QUALITY OF CHANNEL SIGNIFICANTLY DECREASED]\x02'.format(input.chan))
Пример #24
0
def horoscope(inp, db=None, notice=None, nick=None):
    """horoscope <sign> [save] -- Get your horoscope."""
    save = False
    database.init(db)

    if '@' in inp:
        nick = inp.split('@')[1].strip()
        sign = database.get(db,'users','horoscope','nick',nick)
        if not sign: return "No horoscope sign stored for {}.".format(nick)
    else:
        sign = database.get(db,'users','horoscope','nick',nick)
        if not inp:
            if not sign:
                notice(horoscope.__doc__)
                return
        else:
            if not sign: save = True
            if " save" in inp: save = True
            sign = inp.split()[0]

    import urllib
    url = "http://my.horoscope.com/astrology/free-daily-horoscope-%s.html" % sign
    try:
        response = urllib.urlopen(url)
        result = response.read()
        horoscopetxt = result.find('div', {'class': 'block-horoscope-text f16 l20'}).text
    except: return "Could not get the horoscope for {}.".format(sign.encode('utf8'))

    if sign and save: database.set(db,'users','horoscope',sign,'nick',nick)

    return u"\x02{}\x02 {}".format(sign, horoscopetxt)
Пример #25
0
def disablehash(inp, notice=None, bot=None, chan=None, db=None):
    '''
    disablehash [#channel] <hashtah
    Disables hashtah for a channel.
    (you can disable multiple hastags at once, don't put # before the hashtag)
    '''

    disabledhashes = database.get(
        db, 'channels', 'disabledhashes', 'chan', chan)
    targets = inp.split()
    for target in targets:
        if disabledhashes and target in disabledhashes:
            notice(u"[{}]: {} is already disabled.".format(chan, target))
        else:
            if 'disable' in target or 'enable' in target:
                notice(u"[{}]: {} cannot be disabled.".format(chan, target))
            else:
                disabledhashes = '{} {}'.format(target, disabledhashes)
                database.set(
                    db,
                    'channels',
                    'disabledhashes',
                    disabledhashes,
                    'chan',
                    chan)
                notice(u"[{}]: {} has been disabled.".format(chan, target))
    return
Пример #26
0
def factoid_manage(data, code, input):
    # This is ugly looking, but I like it built into ` to make it easier to remember commands.
    #   - (Rather than if/fi, af/fa, fr/rf/fd/df)
    if len(data.split()) == 1:
        cmd, args = data, False
    else:
        cmd, args = data.split(' ', 1)
    if args:
        name = args.split()[0].lower()
    db = database.get(code.nick, 'factoids')
    if not db:
        db = {}
    if cmd.lower() in ['add', 'create', 'new']:
        if args:
            if name.lower() in db:
                return code.reply('{red}That factoid already exists!')
            elif len(args.strip().split()) > 1:
                db[name.lower()] = args.split(' ', 1)[1]
                database.set(code.nick, db, 'factoids')
                return code.reply(
                    '{green}Successfully created the factoid "{purple}%s{green}"!'
                    % name)
        return code.reply((
            '{red}Use "{purple}` add <name> <args>{red}" to create a new factoid. Use <py>, '
            '<act>, <url> in front of args for different responses.'))
    elif cmd.lower() in ['del', 'rem', 'delete', 'remove']:
        if args:
            if name.lower() not in db:
                return code.reply('{red}That factoid does not exist!')
            else:
                del db[name.lower()]
                database.set(code.nick, db, 'factoids')
                return code.reply(
                    '{green}Successfully deleted the factoid "{purple}%s{green}"!'
                    % name)
        return code.reply(
            '{red}Use "{purple}` del <name>{red}" to delete a factoid.')
    elif cmd.lower() in ['info', 'raw', 'show', 'view']:
        if args:
            if name.lower() in db:
                return code.msg(input.sender,
                                'Raw: ' + repr(db[name.lower()])[2:-1],
                                colors=False)
            else:
                return code.say('{red}That factoid does not exist!')
        return code.reply(
            '{red}Use "{purple}` info <name>{red}" to view the factoid in raw form.'
        )
    elif cmd.lower() in ['list', 'all']:
        factoids = db.keys()
        if len(factoids) < 1:
            return code.say('There are no factoids yet!')
        tmp = []
        for factoid in factoids:
            tmp.append('`%s' % factoid)
        return code.say('{b}List of factoids:{b} %s' % (', '.join(tmp)))
    else:
        return code.reply(
            '{red} Usage: "{purple}` <add|delete|info> [args]{red}"')
Пример #27
0
def citation(db, chan, nick, reason):
    fine = random.randint(1, 500)
    try:
        totalfines = int(database.get(db, 'users', 'fines', 'nick',
                                      nick)) + fine
    except:
        totalfines = 0 + fine
    database.set(db, 'users', 'fines', totalfines, 'nick', nick)
    return u"PRIVMSG {} :\x01ACTION fines {} \x02${}\x02 {}. You owe: \x0304${}\x02\x01".format(
        chan, nick, fine, reason, totalfines)
Пример #28
0
def weather(inp, nick=None, reply=None, db=None, notice=None):
    "weather | <location> [save] | <@ user> -- Gets weather data for <location>."
    save = False 
    
    if '@' in inp:
        save = False
        nick = inp.split('@')[1].strip()
        loc = database.get(db,'users','location','nick',nick)
        if not loc: return "No location stored for {}.".format(nick.encode('ascii', 'ignore'))
    else:
        loc = database.get(db,'users','location','nick',nick)
        if not inp:
            if not loc:
                notice(weather.__doc__)
                return
        else:
            # if not loc: save = True
            if " save" in inp: 
                inp = inp.replace(' save','')
                save = True 
            loc = inp.replace(' ','_') #.split()[0]

    location = http.quote_plus(loc)
    # location = location.replace(',','').replace(' ','-')

    # now, to get the actual weather
    try:

	    q ={
		'q': 'select title, units.temperature, item.forecast from weather.forecast where woeid in (select woeid from geo.places where text="'+ location+'") limit 1',
		 'format': 'json',
		 'env': 'store://datatables.org/alltableswithkeys'
		}

	    result = query(q)
	    data = json.loads(result)
	    weather = data["query"]["results"]["channel"]
	    average_F =  float((int(weather['item']['forecast']['high']) + int(weather['item']['forecast']['low']))/2)
	    average_C = round(float((average_F - 32) * (5.0/9.0)), 2)
    except KeyError:
        return "Could not get weather for that location."

    if location and save: database.set(db,'users','location',location,'nick',nick)

    # put all the stuff we want to use in a dictionary for easy formatting of the output
    weather_data = {
	'title': weather["title"].replace("Yahoo! Weather -", ""), 
	'current': weather['item']['forecast']['text'],
	'temp_f': average_F,
	'temp_c': average_C
    }
 
    reply("\x02{title}\x02 - \x02Current:\x02 {current}, {temp_f}F/{temp_c}C".format(**weather_data))
Пример #29
0
def bet(inp, nick=None, db=None, chan=None):
    "bet <ammount> -- bets <ammount>"
    inp = inp.replace(',', '').replace('$', '')
    try:
        money = float(database.get(db, 'users', 'fines', 'nick', nick))
    except:
        money = 0.0
    if inp == "":
        inp = "100"
    if inp != "0":
        inp = float('-' + inp)
        if math.isnan(inp):
            return
        strinp = "{:,}".format(inp)
        strmoney = "{:,}".format(money)
        if inp < money or money == 0:
            if '-' in strmoney[0]:
                return u"\x01ACTION You don't have enough money to bet \x02${}\x02. You have \x0309${}\x02\x01".format(
                    strinp[1:], strmoney[1:])
            else:
                return u"\x01ACTION You don't have enough money to bet \x02${}\x02. You owe \x0304${}\x02\x01".format(
                    strinp[1:], strmoney)
            if inp == 0:
                if '-' in strmoney[0]:
                    return u"\x01ACTION You have to bet more than \x02${}\x02. You have \x0309${}\x02\x01".format(
                        strinp[1:], strmoney[1:])
                else:
                    return u"\x01ACTION You have to bet more than \x02${}\x02. You owe \x0304${}\x02\x01".format(
                        strinp[1:], strmoney)
        else:
            print(inp)
            if random.randint(1, 100) <= 50:
                money = money - inp
                strinp = "{:,}".format(inp)
                strmoney = "{:,}".format(money)
                database.set(db, 'users', 'fines', money, 'nick', nick)
                if '-' in strmoney[0]:
                    return u"\x01ACTION You lose the bet and lost \x02${}\x02. You have \x0309${}\x02\x01".format(
                        strinp[1:], strmoney[1:])
                else:
                    return u"\x01ACTION You lose the bet and lost \x02${}\x02. You owe \x0304${}\x02\x01".format(
                        strinp[1:], strmoney)
            else:
                money = money + inp
                strinp = "{:,}".format(inp)
                strmoney = "{:,}".format(money)
                database.set(db, 'users', 'fines', money, 'nick', nick)
                if '-' in strmoney[0]:
                    return u"\x01ACTION You win the bet and win \x02${}\x02. You have \x0309${}\x02\x01".format(
                        strinp[1:], strmoney[1:])
                else:
                    return u"\x01ACTION You win the bet and win \x02${}\x02. You owe \x0304${}\x02\x01".format(
                        strinp[1:], strmoney)
Пример #30
0
def unignore(code, input):
    """ unignore <mask> - Removes <mask> from ignore list. """
    mask = matchmask(input.group(2))
    if not mask:
        return code.say('Invalid mask! For more info, see: https://github.com/Liamraystanley/Code/wiki/Masks')
    blocks = database.get(code.nick, 'ignore', [])
    if mask not in blocks:
        return code.say('%s doesn\'t exist in the ignore list!' % mask)
    del blocks[blocks.index(mask)]
    code.blocks = blocks
    code.blocks = [convertmask(x) for x in blocks]
    database.set(code.nick, blocks, 'ignore')
    return code.say('Successfully removed %s from the ignore list.' % mask)
Пример #31
0
def unignore(inp, notice=None, bot=None, chan=None, db=None):
    """unignore [channel] <nick|host> -- Makes the bot listen to <nick|host>."""
    ignorelist = database.get(db,'channels','ignored','chan',chan)
    targets = inp.split()
    for target in targets:
        target = user.get_hostmask(target,db)
        if ignorelist  and target in ignorelist:
            ignorelist = " ".join(ignorelist.replace(target,'').strip().split())
            database.set(db,'channels','ignored',ignorelist,'chan',chan)
            notice(u"[{}]: {} has been unignored.".format(chan,target))
        else:
            notice(u"[{}]: {} is not ignored.".format(chan,target))
    return
Пример #32
0
def unignore(inp, notice=None, bot=None, chan=None, db=None):
    """unignore [channel] <nick|host> -- Makes the bot listen to <nick|host>."""
    ignorelist = database.get(db,'channels','ignored','chan',chan)
    targets = inp.split()
    for target in targets:  
        target = user.get_hostmask(target,db)
        if ignorelist  and target in ignorelist:
            ignorelist = " ".join(ignorelist.replace(target,'').strip().split())
            database.set(db,'channels','ignored',ignorelist,'chan',chan)
            notice(u"[{}]: {} has been unignored.".format(chan,target))
        else:
            notice(u"[{}]: {} is not ignored.".format(chan,target))
    return
Пример #33
0
def timefunction(inp, nick="", reply=None, db=None, notice=None):
    "time [location] [dontsave] | [@ nick] -- Gets time for <location>."

    save = True

    if '@' in inp:
        nick = inp.split('@')[1].strip()
        location = database.get(db, 'users', 'location', 'nick', nick)
        if not location:
            return "No location stored for {}.".format(
                nick.encode('ascii', 'ignore'))
    else:
        location = database.get(db, 'users', 'location', 'nick', nick)
        if not inp:
            if not location:
                notice(time.__doc__)
                return
        else:
            # if not location: save = True
            if " dontsave" in inp: save = False
            location = inp.split()[0]

    # now, to get the actual time
    try:
        url = "https://www.google.com/search?q=time+in+{}".format(
            location.replace(' ', '+').replace(' save', ''))
        request = urllib2.Request(url, None, headers)
        page = urllib2.urlopen(request).read()
        soup = BeautifulSoup(page, 'lxml')
        soup = soup.find('div', attrs={'id': re.compile('ires')})

        time = filter(
            None,
            http.strip_html(
                soup.find('div', attrs={
                    'class': re.compile('vk_gy')
                }).renderContents().strip()).split(' '))
        prefix = ' '.join(time[6:])
        curtime = time[0]
        day = time[1]
        date = ' '.join(time[2:4])
    except IndexError:
        return "Could not get time for that location."

    if location and save:
        database.set(db, 'users', 'location', location, 'nick', nick)

    return formatting.output(
        'Time',
        [u'{} is \x02{}\x02 [{} {}]'.format(prefix, curtime, day, date)])
Пример #34
0
def ban(inp, conn=None, chan=None, notice=None, db=None, nick=None, bot=None):
    '''
    ban [channel] <user> [reason] [timer]
    Makes the bot ban <user> in [channel].
    If [channel] is blank the bot will ban <user> in
    the channel the command was used in.
    '''

    mode = "+b"
    reason = "#rekt"
    # inp,chan = get_chan(inp,chan)
    split = inp.split(" ")
    inp_nick = split[0]

    if conn.nick in inp_nick or bot.config['owner'] == inp_nick:
        target = nick
        reason = "Your attitude is not conducive to the desired environment"
        conn.send(u"KICK {} {} :{}".format(chan, target, reason))
        return

    if len(split) > 1:
        reason = " ".join(split[1:])

    if '@' not in inp_nick:
        target = user.get_hostmask(inp_nick, db)
    else:
        target = inp_nick

    if '@' in target and '!' not in target:
        target = '*!*{}'.format(target)
    timer = scheduler.check_for_timers(inp)
    if timer > 0:
        reason = "{} Come back in {} seconds!!!".format(reason, timer)
    notice(u"Attempting to ban {} in {}...".format(target, chan))
    conn.send(u"MODE {} {} {}".format(chan, mode, target))
    conn.send(u"KICK {} {} :{}".format(chan, inp_nick, reason))

    if timer > 0:
        notice(u"{} will be unbanned in {} seconds".format(target, timer))
        scheduler.schedule(
            timer, 1, "MODE {} -b {}".format(chan, target), conn)
        # scheduler.schedule(timer, 2,
        #                    "PRIVMSG ChanServ :unban {} {}".format(channel,
        #                                                           nick),
        #                     conn)
    else:
        banlist = database.get(db, 'channels', 'bans', 'chan', chan)
        banlist = '{} {}'.format(target, banlist).replace('False', '').strip()
        database.set(db, 'channels', 'bans', banlist, 'chan', chan)
    return
Пример #35
0
def mug(inp, db=None, nick=None, chan=None, conn=None, notice=None):
    """mug <user> -- Takes money from <user>.."""
    inp = inp.split()
    user = inp[0]
    money = float(random.randint(20, 1500))
    try:
        money = inp[-1].split('.')[0] + '.' + inp[-1].split('.')[1][0:2]
	money = float(money)
    except:
        pass
    try:
        robber = float(database.get(db,'users','fines','nick',nick))
    except:
        robber = 0.0
    try:
        victim = float(database.get(db,'users','fines','nick',user))
    except:
        victim = 0.0
    robbingfails = random.randint(1, 3)
    if robbingfails == 2:
        if victim != robber:
            database.set(db,'users','fines',robber + money,'nick', nick)
            database.set(db,'users','fines',victim - money,'nick',user)
        conn.send(u"PRIVMSG {} :\x01ACTION {} shoots you in the foot and takes \x02${}\x02.\x01".format(chan, user, money))
    else:
        if robber != victim:
            database.set(db,'users','fines',victim + money,'nick', user)
            database.set(db,'users','fines',robber - money,'nick', nick)
        conn.send(u"PRIVMSG {} :\x01ACTION {} shanks {} in a dark alley and takes \x02${}\x02\x01".format(chan, nick, user, money))
Пример #36
0
def autoop(inp, notice=None, bot=None, chan=None, db=None):
    """aop [channel] <enable|disable> OR <add|del> <nick|host> -- Add/Del Autoops."""
    autoops = database.get(db, "channels", "autoops", "chan", chan)

    channel = chan.lower()
    command = inp.split()[0]
    if "enable" in command:
        database.set(db, "channels", "autoop", True, "chan", chan)
        notice(u"[{}]: Autoops is now enabled.".format(chan))
    elif "disable" in command:
        database.set(db, "channels", "autoop", False, "chan", chan)
        notice(u"[{}]: Autoops is now disabled.".format(chan))
    elif "add" in command:
        nicks = inp.split()[1:]
        for nick in nicks:
            nick = user.get_hostmask(nick, db)
            if autoops and nick in autoops:
                notice(u"[{}]: {} is already an autoop.".format(chan, nick))
            else:
                autoops = "{} {}".format(nick, autoops).replace("False", "").strip()
                database.set(db, "channels", "autoops", autoops, "chan", chan)
                notice(u"[{}]: {} is now an auto op.".format(chan, nick))
    elif "del" in command:
        nicks = inp.split()[1:]
        for nick in nicks:
            nick = user.get_hostmask(nick, db)
            if autoops and nick in autoops:
                autoops = " ".join(autoops.replace(nick, "").strip().split())
                database.set(db, "channels", "autoops", autoops, "chan", chan)
                notice(u"[{}]: {} is no longer an auto op.".format(chan, nick))
            else:
                notice(u"[{}]: {} is not an auto op.".format(chan, nick))
    return
Пример #37
0
def ignore(code, input):
    """ ignore <mask> - Makes code ignore anyone matching <mask> """
    mask = matchmask(input.group(2))
    if not mask:
        return code.say('Invalid mask! For more info, see: https://github.com/Liamraystanley/Code/wiki/Masks')
    blocks = database.get(code.nick, 'ignore', [])
    if mask not in blocks:
        blocks.append(mask)
    else:
        return code.say('%s is already in the ignorelist!' % mask)
    code.blocks = blocks
    code.re_blocks = [convertmask(x) for x in blocks]
    database.set(code.nick, blocks, 'ignore')
    return code.say('Successfully added %s to the ignore list.' % mask)
Пример #38
0
def autoop(inp, notice=None, bot=None, chan=None, db=None):
    """aop [channel] <enable|disable> OR <add|del> <nick|host> -- Add/Del Autoops."""
    inp,chan = get_chan(inp,chan)
    autoops = database.get(db,'channels','autoops','chan',chan)
    
    channel = chan.lower()
    command = inp.split()[0]
    if 'enable' in command:
        database.set(db,'channels','autoop',True,'chan',chan)
        notice(u"[{}]: Autoops is now enabled.".format(chan))
    elif 'disable' in command:
        database.set(db,'channels','autoop',False,'chan',chan)
        notice(u"[{}]: Autoops is now disabled.".format(chan))
    elif 'add' in command:
        nicks = inp.split()[1:]
        for nick in nicks:  
            nick = user.get_hostmask(nick,db)
            if autoops and nick in autoops:
                notice(u"[{}]: {} is already an autoop.".format(chan,nick))
            else:
                autoops = '{} {}'.format(nick,autoops).replace('False','').strip()
                database.set(db,'channels','autoops',autoops,'chan',chan)
                notice(u"[{}]: {} is now an auto op.".format(chan,nick))
    elif 'del' in command:
        nicks = inp.split()[1:]
        for nick in nicks:  
            nick = user.get_hostmask(nick,db)
            if autoops and nick in autoops:
                autoops = " ".join(autoops.replace(nick,'').strip().split())
                database.set(db,'channels','autoops',autoops,'chan',chan)
                notice(u"[{}]: {} is no longer an auto op.".format(chan,nick))
            else:
                notice(u"[{}]: {} is not an auto op.".format(chan,nick))
    return
Пример #39
0
def autoop(inp, notice=None, bot=None, chan=None, db=None):
    """aop [channel] <enable|disable> OR <add|del> <nick|host> -- Add/Del Autoops."""
    autoops = database.get(db, 'channels', 'autoops', 'chan', chan)

    channel = chan.lower()
    command = inp.split()[0]
    if 'enable' in command:
        database.set(db, 'channels', 'autoop', True, 'chan', chan)
        notice(u"[{}]: Autoops is now enabled.".format(chan))
    elif 'disable' in command:
        database.set(db, 'channels', 'autoop', False, 'chan', chan)
        notice(u"[{}]: Autoops is now disabled.".format(chan))
    elif 'add' in command:
        nicks = inp.split()[1:]
        for nick in nicks:
            nick = user.get_hostmask(nick, db)
            if autoops and nick in autoops:
                notice(u"[{}]: {} is already an autoop.".format(chan, nick))
            else:
                autoops = '{} {}'.format(nick, autoops).replace('False',
                                                                '').strip()
                database.set(db, 'channels', 'autoops', autoops, 'chan', chan)
                notice(u"[{}]: {} is now an auto op.".format(chan, nick))
    elif 'del' in command:
        nicks = inp.split()[1:]
        for nick in nicks:
            nick = user.get_hostmask(nick, db)
            if autoops and nick in autoops:
                autoops = " ".join(autoops.replace(nick, '').strip().split())
                database.set(db, 'channels', 'autoops', autoops, 'chan', chan)
                notice(u"[{}]: {} is no longer an auto op.".format(chan, nick))
            else:
                notice(u"[{}]: {} is not an auto op.".format(chan, nick))
    return
Пример #40
0
def mug(inp, db=None, nick=None, chan=None, conn=None, notice=None):
    """mug <user> -- Takes money from <user>.."""
    inp = inp.split()
    user = inp[0]
    money = float(random.randint(20, 1500))
    try:
        money = inp[-1].split('.')[0] + '.' + inp[-1].split('.')[1][0:2]
        money = float(money)
    except:
        pass
    try:
        robber = float(database.get(db, 'users', 'fines', 'nick', nick))
    except:
        robber = 0.0
    try:
        victim = float(database.get(db, 'users', 'fines', 'nick', user))
    except:
        victim = 0.0
    robbingfails = random.randint(1, 3)
    if robbingfails == 2:
        if victim != robber:
            database.set(db, 'users', 'fines', robber + money, 'nick', nick)
            database.set(db, 'users', 'fines', victim - money, 'nick', user)
        conn.send(
            u"PRIVMSG {} :\x01ACTION {} shoots you in the foot and takes \x02${}\x02.\x01"
            .format(chan, user, money))
    else:
        if robber != victim:
            database.set(db, 'users', 'fines', victim + money, 'nick', user)
            database.set(db, 'users', 'fines', robber - money, 'nick', nick)
        conn.send(
            u"PRIVMSG {} :\x01ACTION {} shanks {} in a dark alley and takes \x02${}\x02\x01"
            .format(chan, nick, user, money))
Пример #41
0
def auto_honeypot(code, input):
    """Check joining users against the Project Honeypot Database"""
    if not code.config('honeypot_on_join'):
        return
    global db

    ip = get_ip(input.host)
    abuser = check(ip)
    if abuser:
        # First, we need to check if we've already checked for it, and got a match...
        if ip in db:
            return
        db.append(ip)
        database.set(code.nick, db, 'honeypot')
        code.say(abuser)
Пример #42
0
def auto_honeypot(code, input):
    """Check joining users against the Project Honeypot Database"""
    if not code.config('honeypot_on_join'):
        return
    global db

    ip = get_ip(input.host)
    abuser = check(ip)
    if abuser:
        # First, we need to check if we've already checked for it, and got a match...
        if ip in db:
            return
        db.append(ip)
        database.set(code.nick, db, 'honeypot')
        code.say(abuser)
Пример #43
0
def unignore(code, input):
    """ unignore <mask> - Removes <mask> from ignore list. """
    mask = matchmask(input.group(2))
    if not mask:
        return code.say(
            'Invalid mask! For more info, see: https://github.com/lrstanley/Code/wiki/Masks'
        )
    blocks = database.get(code.nick, 'ignore', [])
    if mask not in blocks:
        return code.say('%s doesn\'t exist in the ignore list!' % mask)
    del blocks[blocks.index(mask)]
    code.blocks = blocks
    code.blocks = [convertmask(x) for x in blocks]
    database.set(code.nick, blocks, 'ignore')
    return code.say('Successfully removed %s from the ignore list.' % mask)
Пример #44
0
def timefunction(inp, nick="", reply=None, db=None, notice=None):
    "time [location] [dontsave] | [@ nick] -- Gets time for <location>."

    save = True

    if '@' in inp:
        nick = inp.split('@')[1].strip()
        location = database.get(db, 'users', 'location', 'nick', nick)
        if not location:
            return "No location stored for {}.".format(
                nick.encode('ascii', 'ignore'))
    else:
        location = database.get(db, 'users', 'location', 'nick', nick)
        if not inp:
            if not location:
                notice(time.__doc__)
                return
        else:
            # if not location: save = True
            if " dontsave" in inp: save = False
            location = inp.split()[0]

    # now, to get the actual time
    try:
        url = "https://www.google.com/search?q=time+in+%s" % location.replace(
            ' ', '+').replace(' save', '')
        html = http.get_html(url)
        prefix = html.xpath(
            "//div[contains(@class,'vk_c vk_gy')]//span[@class='vk_gy vk_sh']/text()"
        )[0].strip()
        curtime = html.xpath(
            "//div[contains(@class,'vk_c vk_gy')]//div[@class='vk_bk vk_ans']/text()"
        )[0].strip()
        day = html.xpath(
            "//div[contains(@class,'vk_c vk_gy')]//div[@class='vk_gy vk_sh']/text()"
        )[0].strip()
        date = html.xpath(
            "//div[contains(@class,'vk_c vk_gy')]//div[@class='vk_gy vk_sh']/span/text()"
        )[0].strip()
    except IndexError:
        return "Could not get time for that location."

    if location and save:
        database.set(db, 'users', 'location', location, 'nick', nick)

    return formatting.output(
        'Time',
        [u'{} is \x02{}\x02 [{} {}]'.format(prefix, curtime, day, date)])
Пример #45
0
def factoid_manage(data, code, input):
    # This is ugly looking, but I like it built into ` to make it easier to remember commands.
    #   - (Rather than if/fi, af/fa, fr/rf/fd/df)
    if len(data.split()) == 1:
        cmd, args = data, False
    else:
        cmd, args = data.split(' ', 1)
    if args:
        name = args.split()[0].lower()
    db = database.get(code.nick, 'factoids')
    if not db:
        db = {}
    if cmd.lower() in ['add', 'create', 'new']:
        if args:
            if name in db:
                return code.reply('{red}That factoid already exists!')
            elif len(args.strip().split()) > 1:
                db[name] = args.split(' ', 1)[1]
                database.set(code.nick, db, 'factoids')
                return code.reply('{green}Successfully created the factoid "{purple}%s{green}"!' % name)
        return code.reply(('{red}Use "{purple}` add <name> <args>{red}" to create a new factoid. Use <py>, '
                           '<act>, <url> in front of args for different responses.'))
    elif cmd.lower() in ['del', 'rem', 'delete', 'remove']:
        if args:
            if name not in db:
                return code.reply('{red}That factoid does not exist!')
            else:
                del db[name]
                database.set(code.nick, db, 'factoids')
                return code.reply('{green}Successfully deleted the factoid "{purple}%s{green}"!' % name)
        return code.reply('{red}Use "{purple}` del <name>{red}" to delete a factoid.')
    elif cmd.lower() in ['info', 'raw', 'show', 'view']:
        if args:
            if name in db:
                return code.say('Raw: ' + db[name])
            else:
                return code.say('{red}That factoid does not exist!')
        return code.reply('{red}Use "{purple}` info <name>{red}" to view the factoid in raw form.')
    elif cmd.lower() in ['list', 'all']:
        factoids = db.keys()
        if len(factoids) < 1:
            return code.say('There are no factoids yet!')
        tmp = []
        for factoid in factoids:
            tmp.append('`%s' % factoid)
        return code.say('{b}List of factoids:{b} %s' % (', '.join(tmp)))
    else:
        return code.reply('{red} Usage: "{purple}` <add|delete|info> [args]{red}"')
Пример #46
0
def setup(code):
    # Read the databases here, make global variables. If we can't read the db
    #   then we need to disable the module..
    global enabled
    global db
    # Try to read the db...
    db = database.get(code.nick, "twss")
    if not db:
        try:
            db = web.json("http://misc.liamstanley.io/twss.json")["lines"]
            database.set(code.nick, db, "twss")
            output.info('Downloaded "That\'s What She Said" library and saved')
        except:
            output.error(('Failed to download "That\'s What She Said" library. ' "Disabling twss.py."))
    if db:
        enabled = True
Пример #47
0
def unban(inp, conn=None, chan=None, notice=None, db=None):
    """unban [channel] <user> -- Makes the bot unban <user> in [channel].
    If [channel] is blank the bot will unban <user> in
    the channel the command was used in."""
    #mode_cmd("-b", "unban", inp, chan, conn, notice)
    inp,chan = get_chan(inp,chan)
    split = inp.split(" ")
    nick = split[0]
    target = user.get_hostmask(nick,db)
    if '@' in target and not '!' in target: target = '*!*{}'.format(target)
    notice(u"Attempting to unban {} in {}...".format(nick, chan))
    conn.send(u"MODE {} -b {}".format(chan, target))
    banlist = database.get(db,'channels','bans','chan',chan)
    banlist = " ".join(banlist.replace(target,'').strip().split())
    database.set(db,'channels','bans',banlist,'chan',chan)
    return
Пример #48
0
def ignore(code, input):
    """ ignore <mask> - Makes code ignore anyone matching <mask> """
    mask = matchmask(input.group(2))
    if not mask:
        return code.say(
            'Invalid mask! For more info, see: https://github.com/lrstanley/Code/wiki/Masks'
        )
    blocks = database.get(code.nick, 'ignore', [])
    if mask not in blocks:
        blocks.append(mask)
    else:
        return code.say('%s is already in the ignorelist!' % mask)
    code.blocks = blocks
    code.re_blocks = [convertmask(x) for x in blocks]
    database.set(code.nick, blocks, 'ignore')
    return code.say('Successfully added %s to the ignore list.' % mask)
Пример #49
0
def disable(inp, notice=None, bot=None, chan=None, db=None):
    """disable [#channel] <commands> -- Disables commands for a channel.
    (you can disable multiple commands at once)"""

    disabledcommands = database.get(db, "channels", "disabled", "chan", chan)
    targets = inp.split()
    for target in targets:
        if disabledcommands and target in disabledcommands:
            notice(u"[{}]: {} is already disabled.".format(chan, target))
        else:
            if "disable" in target or "enable" in target:
                notice(u"[{}]: {} cannot be disabled.".format(chan, target))
            else:
                disabledcommands = "{} {}".format(target, disabledcommands)
                database.set(db, "channels", "disabled", disabledcommands, "chan", chan)
                notice(u"[{}]: {} has been disabled.".format(chan, target))
    return
Пример #50
0
def unban(inp, conn=None, chan=None, notice=None, db=None):
    """unban [channel] <user> -- Makes the bot unban <user> in [channel].
    If [channel] is blank the bot will unban <user> in
    the channel the command was used in."""
    #mode_cmd("-b", "unban", inp, chan, conn, notice)
    # inp,chan = get_chan(inp,chan)
    split = inp.split(" ")
    nick = split[0]
    if not '@' in nick: target = user.get_hostmask(nick, db)
    else: target = nick
    if '@' in target and not '!' in target: target = '*!*{}'.format(target)
    notice(u"Attempting to unban {} in {}...".format(target, chan))
    conn.send(u"MODE {} -b {}".format(chan, target))
    banlist = database.get(db, 'channels', 'bans', 'chan', chan)
    banlist = " ".join(banlist.replace(target, '').strip().split())
    database.set(db, 'channels', 'bans', banlist, 'chan', chan)
    return
Пример #51
0
def horoscope(inp, db=None, notice=None, nick=None):
    """horoscope <sign> [save] -- Get your horoscope."""
    save = False
    database.init(db)

    if '@' in inp:
        nick = inp.split('@')[1].strip()
        sign = database.get(db, 'users', 'horoscope', 'nick', nick)
        if not sign:
            return "No horoscope sign stored for {}.".format(nick)
    else:
        sign = database.get(db, 'users', 'horoscope', 'nick', nick)
        if not inp:
            if not sign:
                notice(horoscope.__doc__)
                return
        else:
            if not sign:
                save = True
            if " save" in inp:
                save = True
            sign = inp.split()[0]

    url = "https://my.horoscope.com/astrology/free-daily-horoscope-{}.html".format(
        sign)
    try:
        result = http.get_soup(url)
        container = result.find('div', attrs={'class': 'main-horoscope'})
        if not container:
            return 'Could not parse the horoscope for {}.'.format(sign)

        paragraph = container.find('p')

        if paragraph:
            return nick + ': ' + paragraph.text
        else:
            return 'Could not read the horoscope for {}.'.format(sign)

    except Exception:
        raise
        return "Could not get the horoscope for {}.".format(sign)

    if sign and save:
        database.set(db, 'users', 'horoscope', sign, 'nick', nick)

    return u"\x02{}\x02 {}".format(title, horoscopetxt)
Пример #52
0
def disablehash(inp, notice=None, bot=None, chan=None, db=None):
    """disablehash [#channel] <hashtah> -- Disables hashtah for a channel.
    (you can disable multiple hastags at once, don't put # before the hashtag)"""

    disabledhashes = database.get(db,'channels','disabledhashes','chan',chan)
    targets = inp.split()
    for target in targets:
        if disabledhashes and target in disabledhashes:
            notice(u"[{}]: {} is already disabled.".format(chan,target))
        else:
            if 'disable' in target or 'enable' in target:
                 notice(u"[{}]: {} cannot be disabled.".format(chan,target))
            else:
                disabledhashes = '{} {}'.format(target,disabledhashes)
                database.set(db,'channels','disabledhashes',disabledhashes,'chan',chan)
                notice(u"[{}]: {} has been disabled.".format(chan,target))
    return
Пример #53
0
def gen_db(botname):
    global uc_names, cp_names, uc
    # http://www.unicode.org/reports/tr44/#UnicodeData.txt
    output.info('Downloading Unicode data')
    data = get('http://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt').read()
    data = data.split('\n')
    del data[-1]
    # http://www.unicode.org/reports/tr44/#UnicodeData.txt
    for line in data:
        tmp = line.split(';')
        name = tmp[1]
        if tmp[10]:
            name = name + ' ' + str(tmp[10])
        uc[name] = tmp
        uc_names.append(name)
        cp_names[tmp[0]] = name
    database.set(botname, {'uc': uc, 'uc_names': uc_names, 'cp_names': cp_names, 'time': int(time.time())}, 'unicodedata')
Пример #54
0
def disable(inp, notice=None, bot=None, chan=None, db=None):
    """disable [#channel] <commands> -- Disables commands for a channel.
    (you can disable multiple commands at once)"""

    disabledcommands = database.get(db,'channels','disabled','chan',chan)
    targets = inp.split()
    for target in targets:
        if disabledcommands and target in disabledcommands:
            notice(u"[{}]: {} is already disabled.".format(chan,target))
        else:
            if 'disable' in target or 'enable' in target or 'core_admin' in target:
                 notice(u"[{}]: {} cannot be disabled.".format(chan,target))
            else:
                disabledcommands = '{} {}'.format(target,disabledcommands)
                database.set(db,'channels','disabled',disabledcommands,'chan',chan)
                notice(u"[{}]: {} has been disabled.".format(chan,target))
    return
Пример #55
0
def disable(inp, notice=None, bot=None, chan=None, db=None):
    """disable [#channel] <commands> -- Disables commands for a channel.
    (you can disable multiple commands at once)"""
    inp,chan = get_chan(inp,chan)
    disabledcommands = database.get(db,'channels','disabled','chan',chan)
    targets = inp.split()
    for target in targets:  
        if disabledcommands and target in disabledcommands:
            notice(u"[{}]: {} is already disabled.".format(chan,target))
        else:
            if 'disable' in target or 'enable' in target:
                 notice(u"[{}]: {} cannot be disabled.".format(chan,target))
            else:
                disabledcommands = '{} {}'.format(target,disabledcommands)
                database.set(db,'channels','disabled',disabledcommands,'chan',chan)
                notice(u"[{}]: {} has been disabled.".format(chan,target))
    return
Пример #56
0
def ignore(inp, notice=None, bot=None, chan=None, db=None):
    """ignore [channel] <nick|host> -- Makes the bot ignore <nick|host>."""
    ignorelist = database.get(db,'channels','ignored','chan',chan)
    targets = inp.split()
    for target in targets:
        target = user.get_hostmask(target,db)
        if (user.is_admin(target,chan,db,bot)):
            notice(u"[{}]: {} is an admin and cannot be ignored.".format(chan,inp))
        else:
            if ignorelist and target in ignorelist:
                notice(u"[{}]: {} is already ignored.".format(chan, target))
            else:
                ignorelist = '{} {}'.format(target,ignorelist)
                database.set(db,'channels','ignored',ignorelist,'chan',chan)

                notice(u"[{}]: {} has been ignored.".format(chan,target))
    return
Пример #57
0
def enablehash(inp, notice=None, bot=None, chan=None, db=None):
    """enablehash [#channel] <hashtag|all> -- Enables hashtags for a channel.
    (you can enable multiple hashtags at once, don't put # before the hashtag)"""

    disabledhashes = database.get(db,'channels','disabledhashes','chan',chan)
    targets = inp.split()
    if 'all' in targets or '*' in targets:
        database.set(db,'channels','disabledhashes','','chan',chan)
        notice(u"[{}]: All commands are now enabled.".format(chan))
    else:
        for target in targets:
            if disabledhashes and target in disabledhashes:
                disabledhashes = " ".join(disabledhashes.replace(target,'').strip().split())
                database.set(db,'channels','disabledhashes',disabledhashes,'chan',chan)
                notice(u"[{}]: {} is now enabled.".format(chan,target))
            else:
                notice(u"[{}]: {} is not disabled.".format(chan,target))
    return
Пример #58
0
def waifu(inp, nick=None, conn=None, chan=None,db=None, notice=None):
    "waifu <waifu | @ person> -- Shows a users Waifu or Husbando."

    if not inp or '@' in inp:
        if '@' in inp: nick = inp.split('@')[1].strip()
        result = database.get(db,'users','waifu','nick',nick)
        if result:
            return '{}: {}'.format(nick,result)
        else:
            if not '@' in inp: notice(waifu.__doc__)
            return 'No waifu saved for {}.'.format(nick)
    elif 'del' in inp:
        database.set(db,'users','waifu','','nick',nick)
        notice("Deleted your waifu.")
    else:
        database.set(db,'users','waifu','{} '.format(inp.strip().encode('utf8')),'nick',nick)
        notice("Saved your waifu.")
    return