def daemon(code, tc): while True: time.sleep(auto_check) if code.debug: output.info('Running check for new tweets', 'TWITTER') # Here we do the work... for channel in tc: for tweet_item in tc[channel]: if tweet_item.startswith('#'): # ID data = get_tweets(uri_hash % web.quote(tweet_item)) else: data = get_tweets(uri_user % web.quote(tweet_item), tweet_item) if not data: continue data = data[0] hash_str = hash(data['text']) db = database.get(code.default, 'twitter') if not db: # New data on new database, don't output anywhere.. database.set(code.default, [hash_str], 'twitter') continue if hash_str in db: continue # Same db.append(hash_str) database.set(code.default, db, 'twitter') msg = format(data) code.msg(channel, msg.decode('ascii', 'ignore'), shorten_urls=False) db = database.get(code.default, 'twitter') if db: if len(db) > 200: db = db[-200:] database.set(code.default, db, 'twitter')
def host(inp, nick=None, conn=None, db=None): if not inp: return 'Your host is ' + user.get_hostmask(nick, db) db_host = database.get(db, 'users', 'mask', 'nick', inp) if inp is db_host: db_host = database.get(db, 'seen', 'host', 'name', inp) return "{}: {}".format(inp, db_host)
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
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)
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))
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 # now, to get the actual time url = "https://time.is/%s" % location.replace(' ','_').replace(' save','') try: request = urllib2.Request(url, None, headers) page = urllib2.urlopen(request).read() soup = BeautifulSoup(page, 'lxml') soup = soup.find('div', attrs={'id': re.compile('time_section')}) time = filter(None, http.strip_html(soup.find('div', attrs={'id': re.compile('twd')}).renderContents().strip())) details = filter(None, http.strip_html(soup.find('div', attrs={'id': re.compile('dd')}).renderContents().strip())) prefix = filter(None, http.strip_html(soup.find('div', attrs={'id': re.compile('msgdiv')}).renderContents().strip())) except IndexError: return "Could not get time for that location." return formatting.output('Time', [u'{} {}, {}'.format(prefix.decode('ascii', 'ignore'), time, details)])
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))
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)
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)
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)
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)
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)
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)
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))
def host(inp, nick=None, conn=None, db=None): # return user.get_hostmask(inp,db) if not inp: inp = nick db_host = database.get(db, 'users', 'mask', 'nick', inp) if inp is db_host: db_host = database.get(db, 'seen', 'host', 'name', inp) return "{}: {}".format(inp, db_host)
def badwords(inp, notice=None, bot=None, chan=None, db=None): """disabled [#channel] -- Lists disabled commands/.""" if len(inp) == 0 or 'list' in inp: badwordlist = database.get(db, 'channels', 'badwords', 'chan', chan) if badwordlist: notice(u"[{}]: Bad words: {}".format(chan, badwordlist)) else: notice(u"[{}]: No bad words in list.".format(chan)) notice(badwords.__doc__) elif 'add' or 'del' in inp: command = inp.split(' ')[0].strip() inp = inp.replace(command, '').strip() badwordlist = database.get(db, 'channels', 'badwords', 'chan', chan) targets = inp.split() if 'add' in command: for target in targets: if badwordlist and target in badwordlist: notice( u"[{}]: {} is already a bad word.".format( chan, target)) else: if len(target) < 3: s = u"[{}]: badwords must be longer than 3 " \ "characters. ({})" notice(s.format(chan, target)) else: badwordlist = '{} {}'.format(target, badwordlist) database.set( db, 'channels', 'badwords', badwordlist, 'chan', chan) s = u"[{}]: {} has been added to the bad word list." notice(s.format(chan, target)) elif 'del' in command: if 'all' in targets or '*' in targets: database.set(db, 'channels', 'badwords', '', 'chan', chan) notice(u"[{}]: All bad words have been removed.".format(chan)) else: for target in targets: if badwordlist and target in badwordlist: badwordlist = " ".join( badwordlist.replace( target, '').strip().split()) database.set( db, 'channels', 'badwords', badwordlist, 'chan', chan) notice( u"[{}]: {} is no longer a bad word.".format( chan, target)) else: notice( u"[{}]: {} is not a bad word.".format( chan, target)) else: notice(badwords.__doc__) return
def get_hostmask(inp, db): "userhost -- Returns a nicks userhost" if '@' in inp or '.' in inp: return inp nick = inp.strip().replace('~', '').lower() db_host = database.get(db, 'users', 'mask', 'nick', nick) if db_host is False: db_host = database.get(db, 'seen', 'host', 'name', nick) if db_host is False: db_host = nick return format_hostmask(db_host)
def process_vote(target,action,chan,mask,db,notice,conn): if ' ' in target: notice('Invalid nick') return try: votes2kick = database.get(db,'channels','votekick','chan',chan) except: votes2kick = 10 try: votes2ban = database.get(db,'channels','voteban','chan',chan) except: votes2ban = 10 if len(target) is 0: if action is 'kick': notice('Votes required to kick: {}'.format(votes2kick)) elif action is 'ban': notice('Votes required to ban: {}'.format(votes2ban)) return votefinished = False global db_ready if not db_ready: db_init(db) chan = chan.lower() target = target.lower() voter = user.format_hostmask(mask) oters = db.execute("SELECT voters FROM votes where chan='{}' and action='{}' and target like '{}'".format(chan,action,target)).fetchone() if conn.nick.lower() in target: return "I dont think so Tim." if voters: voters = voters[0] if voter in voters: notice("You have already voted.") return else: voters = '{} {}'.format(voters,voter).strip() notice("Thank you for your vote!") else: voters = voter votecount = len(voters.split(' ')) if 'kick' in action: votemax = int(votes2kick) if votecount >= votemax: votefinished = True conn.send("KICK {} {} :{}".format(chan, target, "You have been voted off the island.")) if 'ban' in action: votemax = int(votes2ban) if votecount >= votemax: votefinished = True conn.send("MODE {} +b {}".format(chan, user.get_hostmask(target,db))) conn.send("KICK {} {} :".format(chan, target, "You have been voted off the island.")) if votefinished: db.execute("DELETE FROM votes where chan='{}' and action='{}' and target like '{}'".format(chan,action,target)) else: db.execute("insert or replace into votes(chan, action, target, voters, time) values(?,?,?,?,?)", (chan, action, target, voters, time.time())) db.commit() return ("Votes to {} {}: {}/{}".format(action, target, votecount,votemax))
def showfloods(inp, chan=None, notice=None, db=None): """showfloods [channel]-- Shows flood settings.""" flood = database.get(db,'channels','flood','chan',chan) if flood: notice(u"[{}]: Flood: {} messages in {} seconds".format(chan,flood.split()[0],flood.split()[1])) else: notice(u"[{}]: Flood protection is disabled.".format(chan)) cmdflood = database.get(db,'channels','cmdflood','chan',chan) if cmdflood: notice(u"[{}]: Command Flood: {} commands in {} seconds".format(chan,cmdflood.split()[0],cmdflood.split()[1])) else: notice(u"[{}]: Command Flood protection is disabled.".format(chan)) return
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))
def get_hostmask(inp, db): "userhost -- Returns a nicks userhost" if "@" in inp or "." in inp: return inp nick = inp.strip().replace("~", "").lower() db_host = database.get(db, "users", "mask", "nick", nick) if db_host is False: db_host = database.get(db, "seen", "host", "name", nick) if db_host is False: db_host = nick return format_hostmask(db_host)
def badwords(inp, notice=None, bot=None, chan=None, db=None): """disabled [#channel] -- Lists disabled commands/.""" if len(inp) == 0 or 'list' in inp: badwordlist = database.get(db, 'channels', 'badwords', 'chan', chan) if badwordlist: notice(u"[{}]: Bad words: {}".format(chan, badwordlist)) else: notice(u"[{}]: No bad words in list.".format(chan)) notice(badwords.__doc__) elif 'add' or 'del' in inp: command = inp.split(' ')[0].strip() inp = inp.replace(command, '').strip() badwordlist = database.get(db, 'channels', 'badwords', 'chan', chan) targets = inp.split() if 'add' in command: for target in targets: if badwordlist and target in badwordlist: notice(u"[{}]: {} is already a bad word.".format( chan, target)) else: if len(target) < 3: notice( u"[{}]: badwords must be longer than 3 characters. ({})" .format(chan, target)) else: badwordlist = '{} {}'.format(target, badwordlist) database.set(db, 'channels', 'badwords', badwordlist, 'chan', chan) notice( u"[{}]: {} has been added to the bad word list.". format(chan, target)) elif 'del' in command: if 'all' in targets or '*' in targets: database.set(db, 'channels', 'badwords', '', 'chan', chan) notice(u"[{}]: All bad words have been removed.".format(chan)) else: for target in targets: if badwordlist and target in badwordlist: badwordlist = " ".join( badwordlist.replace(target, '').strip().split()) database.set(db, 'channels', 'badwords', badwordlist, 'chan', chan) notice(u"[{}]: {} is no longer a bad word.".format( chan, target)) else: notice(u"[{}]: {} is not a bad word.".format( chan, target)) else: notice(badwords.__doc__) return
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)])
def donate(inp, db=None, nick=None, chan=None, conn=None, notice=None): """donate <user> <money> -- Gives <money> to <user>.""" inp = inp.replace('$', '').replace('-', '').split(' ') inp = ' '.join(inp[0:2]).split('.')[0].split() user = str(' '.join(inp[0:-1]).split('.')[0]) donation = float(inp[-1]) if math.isnan(donation) or math.isinf(donation): return # try: # donation = inp[-1].split('.')[0] + '.' + inp[-1].split('.')[1][0:2] # print donation # donation = float(donation) # except Exception as e: # print e # return #if donation > 10000.00: # donation = 10000.00 if user.lower() == nick.lower(): user = '******' try: giver = float(database.get(db, 'users', 'fines', 'nick', nick)) except: giver = 0.0 try: taker = float(database.get(db, 'users', 'fines', 'nick', user)) except: taker = 0.0 if donation > giver or donation < 0: return if str(giver)[0] == '-': giver = giver + donation else: giver = giver - donation database.set(db, 'users', 'fines', giver, 'nick', nick) wednesdaywins = random.randint(1, 80) if wednesdaywins == 80: wednesday = float( database.get(db, 'users', 'fines', 'nick', 'wednesday')) database.set(db, 'users', 'fines', wednesday - donation, 'nick', 'wednesday') conn.send( u"PRIVMSG {} :\x01ACTION gives \x02${}\x02 to wednesday.\x01". format(chan, donation)) else: if giver != taker: database.set(db, 'users', 'fines', taker - donation, 'nick', user) database.set(db, 'users', 'fines', giver, 'nick', nick) conn.send( u"PRIVMSG {} :\x01ACTION gives \x02${}\x02 to {}.\x01".format( chan, donation, user))
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)])
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
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
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?
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
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)
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
def disabled(inp, notice=None, bot=None, chan=None, db=None): """disabled [#channel] -- Lists disabled commands/.""" disabledcommands = database.get(db,'channels','disabled','chan',chan) disabledglobalcommands = " ".join(bot.config["disabled_commands"]) if disabledcommands: notice(u"[{}]: Disabled commands: {} {}".format(chan,disabledcommands,disabledglobalcommands)) else: notice(u"[{}]: No commands are currently disabled.".format(chan)) return
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~~?"
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))
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
def ignoresieve(bot, input, func, type, args): """ blocks input from ignored channels/nicks/hosts """ globalignorelist = bot.config["ignored"] db = bot.get_db_connection(input.conn) mask = input.mask.lower() chan = input.chan.lower() ignorelist = database.get(db,'channels','ignored','chan',chan) # don't block input to event hooks # if type == "event": return input if user.is_admin(mask,chan,db,bot): return input if ignorelist and user.format_hostmask(mask) in ignorelist: return None if globalignorelist and user.format_hostmask(mask) in globalignorelist: return None #print "[{}]: {} is ignored.".format(input.chan,mask) # if input.chan.lower() in ignorelist \ # or input.nick.lower().replace('~','') in ignorelist \ # or input.mask.lower().replace('~','').lower() in ignorelist: # if input.command == "PRIVMSG" and input.lastparam[1:] == "unignore": # return input # else: # return None return input
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
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
def admin(inp, notice=None, bot=None, chan=None, db=None): """admin [channel] <add|del> <nick|host> -- Makes the user an admin.""" 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: if '*' in nicks: database.set(db, 'channels', 'admins', '', 'chan', chan) notice(u"[{}]: All admins have been removed.".format(chan)) else: 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
def bans(inp, notice=None, bot=None, chan=None, db=None): """bans -- Lists bans on channel.""" inp,chan = get_chan(inp,chan) bans = database.get(db,'channels','bans','chan',chan) if bans: notice(u"[{}]: Bans are: {}".format(chan,bans)) else: notice(u"[{}]: No nicks/hosts are in the banlist.".format(chan)) return
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
def disabled(inp, notice=None, bot=None, chan=None, db=None): """disabled [#channel] -- Lists disabled commands/.""" inp,chan = get_chan(inp,chan) disabledcommands = database.get(db,'channels','disabled','chan',chan) if disabledcommands: notice(u"[{}]: Disabled commands: {}".format(chan,disabledcommands)) else: notice(u"[{}]: No commands are currently disabled.".format(chan)) return
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
def admins(inp, notice=None, bot=None, chan=None, db=None): """admins [channel] -- Lists admins on channel.""" inp,chan = get_chan(inp,chan) admins = database.get(db,'channels','admins','chan',chan) if admins: notice(u"[{}]: Admins are: {}".format(chan,admins)) else: notice(u"[{}]: No nicks/hosts are currently admins.".format(chan)) return
def ignored(inp, notice=None, bot=None, chan=None, db=None): """ignored [channel]-- Lists ignored channels/nicks/hosts.""" inp,chan = get_chan(inp,chan) ignorelist = database.get(db,'channels','ignored','chan',chan) if ignorelist: notice(u"[{}]: Ignored nicks/hosts are: {}".format(chan,ignorelist)) else: notice(u"[{}]: No nicks/hosts are currently ignored.".format(chan)) return
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
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
def unmatched_url(match, chan, db): disabled_commands = database.get(db, 'channels', 'disabled', 'chan', chan) try: r = requests.get(match, headers=headers, allow_redirects=True, stream=True) except Exception as e: return formatting.output('URL', ['Error: {}'.format(e)]) domain = urlparse(match).netloc if r.status_code != 404: content_type = r.headers['Content-Type'] try: encoding = r.headers['content-encoding'] except: encoding = '' if content_type.find("html") != -1: # and content_type is not 'gzip': data = '' for chunk in r.iter_content(chunk_size=1024): data += chunk if len(data) > 48336: break body = html.fromstring(data) try: title = body.xpath('//title/text()')[0] except: return formatting.output('URL', ['No Title ({})'.format(domain)]) try: title_formatted = text.fix_bad_unicode( body.xpath('//title/text()')[0]) except: title_formatted = body.xpath('//title/text()')[0] return formatting.output( 'URL', ['{} ({})'.format(title_formatted, domain)]) else: if disabled_commands: if 'filesize' in disabled_commands: return try: if r.headers['Content-Length']: length = int(r.headers['Content-Length']) if length < 0: length = 'Unknown size' else: length = formatting.filesize(length) else: length = "Unknown size" except: length = "Unknown size" if "503 B" in length: length = "" if length is None: length = "" return formatting.output( 'URL', ['{} Size: {} ({})'.format(content_type, length, domain)]) return
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}"')
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)
def ignored(inp, notice=None, bot=None, chan=None, db=None): """ignored [channel]-- Lists ignored channels/nicks/hosts.""" ignorelist = database.get(db, 'channels', 'ignored', 'chan', chan) if ignorelist: notice(u"[{}]: Ignored nicks/hosts are: {}".format(chan, ignorelist)) else: notice(u"[{}]: No nicks/hosts are currently ignored.".format(chan)) return
def owed(inp, nick=None, conn=None, chan=None, db=None): """owe -- shows your total fines""" if '@' in inp: nick = inp.split('@')[1].strip() fines = database.get(db, 'users', 'fines', 'nick', nick) if not fines: fines = 0 if fines <= 0: return u'\x02{} owes: \x0309${}\x02'.format(nick, fines) else: return u'\x02{} owes: \x0304${}\x02'.format(nick, fines)
def disabledhashes(inp, notice=None, bot=None, chan=None, db=None): """disabledhashes [#channel] -- Lists disabled hashtags.""" disabledhashes = database.get(db, 'channels', 'disabledhashes', 'chan', chan) if disabledhashes: notice(u"[{}]: Disabled hashtags: {}".format(chan, disabledhashes)) else: notice(u"[{}]: No hashtags are currently disabled.".format(chan)) return
def unmatched_url(match, chan, db): disabled_commands = database.get(db, 'channels', 'disabled', 'chan', chan) r = requests.get(match, headers=headers, allow_redirects=True, stream=True) # print r.headers # print r.status_code # print r.request.headers if r.status_code != 404: # image_hash = md5.new(r.content).hexdigest() # print image_hash content_type = r.headers['Content-Type'] try: encoding = r.headers['content-encoding'] except: encoding = '' # try: # r.raise_for_status() if content_type.find("html") != -1: # and content_type is not 'gzip': body = html.fromstring(r.text) try: title_formatted = text.fix_bad_unicode( body.xpath('//title/text()')[0]) except: title_formatted = body.xpath('//title/text()')[0] return title_formatted # return body.xpath('//title/text()')[0] # return re.match(r'^\W+(\w.*)', body.xpath('//title/text()')[0]).group(1) else: if disabled_commands: if 'filesize' in disabled_commands: return try: if r.headers['Content-Length']: length = int(r.headers['Content-Length']) if length > 1048576: length = str("{0:.2f}".format( round((float(length) / 1048576), 2))) + ' MiB' elif length > 1024: length = str("{0:.2f}".format( round((float(length) / 1024), 2))) + ' KiB' elif length < 0: length = 'Unknown size' else: length = str(length) + ' B' else: length = "Unknown size" except: length = "Unknown size" if "503 B" in length: length = "" if length is None: length = "" return u"[{}] {}".format(content_type, length) else: return return
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)
def getlocation(db, location): print location try: location = location.decode("utf-8") except: pass latlong = database.get(db, 'location', 'latlong', 'location', location) address = database.get(db, 'location', 'address', 'location', location) if not latlong: location = location.encode('utf-8') locator = Nominatim(user_agent="Taiga").geocode(location) latlong = (locator.latitude, locator.longitude) database.set(db, 'location', 'latlong', '{},{}'.format(latlong[0], latlong[1]), 'location', location) address = locator.address.replace('United States of America', 'USA').replace( 'United Kingdom', 'UK').encode('utf-8') database.set(db, 'location', 'address', address, 'location', location) else: latlong = latlong.split(',') return latlong, address