def test_weather_update_temp(): """ checks that the weather_update function gives a temperature in Hannestad between -55 and 55 """ pattern = r'temp:([-\d.]+)' match = re.search(pattern, weather_update('Hannestad')) if match: temp = int(match.group(1)) assert -55 < temp < 55
def test44(capfd): weather.weather_update(u'Hannestad',15,0) out, err = capfd.readouterr() assert "Retrieving data for cache" in out #Making dummy file weather.weather_update(u'Hannestad',15,0) cache=pickle.load(open('cached_data.p','r+b')) data = cache[u'Hannestad0'] tmp = data[0:10] #splitting the data expired_timestamp=int(tmp)-21600 #Making the timestamp expire(Subtracting 1 day) tmp = str(expired_timestamp) + data[10:12] #concatenating the data again cache[u'Hannestad0']=tmp pickle.dump(cache,open('cached_data.p','wb')) #writing it to the dummy file weather.weather_update(u'Hannestad',15,0) #Do the weather call again. This also makes a new dummy file, a correct one. cache=pickle.load(open('cached_data.p','r+b')) #reading it again. data = cache[u'Hannestad0'] tmp = data[0:10] #splitting the data assert expired_timestamp != tmp #check expired one is replaced weather.weather_update(u'Hannestad',15,0) #Do the weather call again cache=pickle.load(open('cached_data.p','r')) data = cache[u'Hannestad0'] new_tmp = data[0:10] #splitting the data assert new_tmp == tmp #check expired one is replaced
Simple script to find extremes from weather data given by yr.no using our previously written weather functions. The script attempts to find the hottest and the coldest temperatures in a small subset of Norwegian places (we limit it to 100 forecast requests to not spam yr.no too much) at the next 13:00. As a note it would probably be easier to just use the weather data given by fetch_forecast(), however this also works. """ import weather import re if __name__ == "__main__": # Get forecast string for as many places as we can (100). forecast = weather.weather_update("*", 13, 00) # Regexp string and get location names and temperatures. # Iterate over matches and determine the hottest and the coldest location. matches = re.finditer(r"^(.*?)\:.*?temp\:(\S*)", forecast, re.M | re.U) if matches: match = matches.next() hottest = (match.group(1), int(match.group(2))) coldest = (match.group(1), int(match.group(2))) for match in matches: name = match.group(1) temp = int(match.group(2)) if temp > hottest[1]: hottest = (name, temp) elif temp < coldest[1]:
def output_return(tag, address): if tag == "weather_value": address = address[3:] return weather_update(address) else: return " "
def commands(usernick, msg, chan, ircsock): global watch_enabled # First of all, check if it is a command if chan[0] == "#": # If message starts in trigger if msg[:len(cfg.cmdsym())] == cfg.cmdsym(): # Strip trigger msg = msg[len(cfg.cmdsym()):] # else it is not a command else: return cmd = msg.split(' ') # Stats if cmd[0].lower() in commandsavail or cmd[0].lower() in lastfm.commandsavail_short or cmd[0].lower() in \ watch.commandsavail_short or cmd[0].lower() in cfg.lst_command_option() or cmd[0].lower() in \ cfg.lst_rawcommand_option(): print "stats: matched regular command" stats.update_cmd(cmd[0], 1) stats.update_user(usernick, cmd[0], 1) elif len(cmd) > 1: if cmd[0].lower() == "stats": print "stats: matched stats module command" if cmd[1] in lastfm.commandsavail: stats.update_cmd(('stats ' + cmd[1]), 1) stats.update_user(usernick, ('stats ' + cmd[1]), 1) elif cmd[0].lower() == "lastfm": print "stats: matched lastfm module command" if cmd[1] in lastfm.commandsavail: stats.update_cmd(('lastfm ' + cmd[1]), 1) stats.update_user(usernick, ('lastfm ' + cmd[1]), 1) elif cmd[0].lower() == "watch": print "stats: matched watch module command" if cmd[1] in watch.commandsavail: stats.update_cmd(('watch ' + cmd[1]), 1) stats.update_user(usernick, ('watch ' + cmd[1]), 1) elif cmd[0].lower() == "samba": print "stats: matched samba module command" if cmd[1] in samba.commandsavail: stats.update_cmd(('samba ' + cmd[1]), 1) stats.update_user(usernick, ('samba ' + cmd[1]), 1) # General commands if cmd[0].lower() == "awesome": sendmsg("Everything is awesome!", chan, ircsock) elif cmd[0].lower() == "version": sendmsg("%s" % version(), chan, ircsock) elif cmd[0].lower() == "nyaa": sendmsg("Nyaa~", chan, ircsock) elif cmd[0].lower() == "date": sendmsg(date(), chan, ircsock) elif cmd[0].lower() == "ddate": sendmsg(ddate(), chan, ircsock) elif cmd[0].lower() == "dump": try: if cmd[1] == "cmd": if len(cmd) > 1: if cmd[2] == "ignorednicks": sendmsg("Ignored nicks: %s" % cfg.commands_ignorednicks(), chan, ircsock) elif cmd[1] == "trg": if len(cmd) > 1: if cmd[2] == "ignorednicks": try: sendmsg("Ignored nicks: %s" % cfg.triggers_ignorednicks(), chan, ircsock) except TypeError: sendmsg("An error occurred, sue me", chan, ircsock) elif cmd[1] == "lastfm": if len(cmd) > 1: if cmd[2] == "alias": # try: da_list = lastfm.cfg.list_alias() # for i in range(len(da_list[0])): # for item in da_list: # print item[i] # print da_list sendmsg(da_list, chan, ircsock) # except: # sendmsg("An error occurred, sue me", chan, ircsock) else: sendmsg("Available parameters for this debug function:" " {cmd ignorednicks, trg ignorednicks, lastfm alias}", chan, ircsock) except IndexError: sendmsg("INFODUMP: Invalid argument(s)", chan, ircsock) elif cmd[0].lower() == "kick": # Make sure that it is an actual user if ignored_nick("commands", usernick) is True: sendmsg("%s: Abuse by proxy? Nice try... ಠ_ಠ" % usernick, chan, ircsock) return # Check if user is authorised to do so for u in cfg.su().lower().split(","): if usernick.lower() == u: try: try: # KICK <user> <reason> sendraw("KICK %s %s %s\n" % (chan, cmd[1], cmd[2]), ircsock) return except IndexError: # KICK <user> <static reason> (fallback if no reason given) sendraw("KICK %s %s *shove*\n" % (chan, cmd[1]), ircsock) return except IndexError: print("IndexError in authorisation check") return # If all else fails, user was probably not authorised and must be punished for abuse sendraw("KICK %s %s Backfired, oh the irony! ~\n" % (chan, usernick), ircsock) elif cmd[0].lower() == "replay": # TODO not 100% sure here, debug the backlog list a little and find out if this is safe if len(cmd) > 2 and ian(cmd[1]) and int(cmd[1]) <= maxbacklog: try: if cmd[2] == "duplex": replay(int(cmd[1]), chan, 0, ircsock) elif cmd[2] == "recv": replay(int(cmd[1]), chan, 1, ircsock) elif cmd[2] == "send": replay(int(cmd[1]), chan, 2, ircsock) except IndexError: sendmsg("WHOA! IndexError in cmd[2] o_0", chan, ircsock) replay(int(cmd[1]), chan, 0, ircsock) else: replay(maxbacklog, chan, 0, ircsock) elif cmd[0].lower() == "say": if len(cmd) > 1: # Secure outgoing message if (re.match(r"^\x01[^\s]*", cmd[1]) is None) and (re.match(r"^![^\s]+", cmd[1]) is None): sendmsg(" ".join(cmd[1:]), chan, ircsock) else: sendmsg("Syntax: %ssay <string>" % cfg.cmdsym(), chan, ircsock) elif cmd[0].lower() == "act": sendmsg("\x01ACTION %s\x01" % " ".join(cmd[1:]), chan, ircsock) elif cmd[0].lower() == "join": # Ability to join multiple channels newchans = cmd[1:] for newchan in newchans: if newchan[0] == '#': ircsock.send("JOIN %s\r\n" % newchan) else: ircsock.send("JOIN #%s\r\n" % newchan) elif cmd[0].lower() == "quit" and usernick in cfg.su(): # and cmd[1] == cfg.quitpro(): ircquit(ircsock) elif cmd[0].lower() == "host": if len(cmd) > 1: try: retval = check_output("host %s" % cmd[1], shell=True) # for line in retval: # sendmsg(line, chan) sendmsg(retval, chan, ircsock) except CalledProcessError: sendmsg("Invalid argument.... (and you *know* it)", chan, ircsock) # Help calls if cmd[0].lower() == "help": try: if cmd[1] == "triggers": sendmsg("%s: Syntax: <trigger> %s" % (usernick, cfg.nick()), chan, ircsock) sendmsg("Available triggers: %s " % cfg.triggers_words(), chan, ircsock) elif cmd[1] == "replay": sendmsg("%s: Syntax: %sreplay <lines> <direction>" % (usernick, cfg.cmdsym()), chan, ircsock) sendmsg("Available commands: recv, send, duplex", chan, ircsock) elif cmd[1] == "kick": sendmsg("%s: Syntax: %skick <user>" % (usernick, cfg.cmdsym()), chan, ircsock) elif cmd[1] == "samba": if len(cmd) > 2: if cmd[2] == "logins": sendmsg("%s: Syntax: %ssamba logins <user>" % (usernick, cfg.cmdsym()), chan, ircsock) else: for item in xrange(len(samba.helpcmd(cfg.cmdsym()))): sendmsg(str(samba.helpcmd(cfg.cmdsym())[item]), chan, ircsock) elif cmd[1] == "lastfm": if len(cmd) > 2: if cmd[2] == "recent": sendmsg("%s: Syntax: %slastfm recent <user> <num>" % (usernick, cfg.cmdsym()), chan, ircsock) else: for item in xrange(len(lastfm.helpcmd(cfg.cmdsym()))): sendmsg(str(lastfm.helpcmd(cfg.cmdsym())[item]), chan, ircsock) except IndexError: helpcmd(usernick, chan, ircsock) # module lastfm elif cmd[0].lower() == "lastfm": if len(cmd) > 1: if cmd[1] == "bio": if len(cmd) > 2: feedback = lastfm.artist_bio(cmd[2]) if isinstance(feedback, str): sendmsg(str(feedback), chan, ircsock) # elif isinstance(feedback, list): else: for i in feedback: sendmsg(str(i), chan, ircsock) elif cmd[1] == "status": auth = lastfm.test_connection() print auth print type(auth) if type(auth) is Exception: sendmsg(str(auth.message), chan, ircsock) sendmsg(str(auth.details), chan, ircsock) else: auth = unicodedata.normalize('NFKD', auth).encode('ascii', 'ignore') print auth print type(auth) net = lastfm.network.name print net print type(net) # if type(auth) is str and type(net) is str: if type(auth) is str and type(net) is str: sendmsg("I am currently authenticated as " + auth + " on " + net, chan, ircsock) elif type(auth) is str: sendmsg( "I am currently authenticated as " + auth + " on *NO NETWORK*, how does that even work? =/", chan, ircsock) elif net is str: sendmsg("I am somehow connected to " + net + ", but not authenticated... Okay then!", chan, ircsock) else: sendmsg("I am unable to query the network, is LastFM throwing a fit?", chan, ircsock) elif cmd[1] == "set": if len(cmd) > 2: if cmd[2] == "alias": if len(cmd) > 3: tmp = lastfm.add_alias(usernick, cmd[3]) sendmsg(tmp, chan, ircsock) elif cmd[1] == "recent": default_num = 3 # !lastfm recent nick num if len(cmd) > 3: num = cmd[3] nick = cmd[2] # !lastfm recent nick num try: if 0 > num <= 10: test = lastfm.recently_played(nick, num) # !lastfm recent nick 3 (num was out of bounds) else: test = lastfm.recently_played(nick, default_num) except TypeError: test = lastfm.recently_played(nick, default_num) # !lastfm recent num elif len(cmd) > 2: num = cmd[2] nick = usernick test = lastfm.recently_played(nick, num) # !lastfm recent else: nick = usernick test = lastfm.recently_played(nick, default_num) # Test returned data integrity # If the returned data is a string it is most likely an exception and should be handled as one if type(test) is str: sendmsg(test, chan, ircsock) elif test is None: sendmsg("%s has not played anything in the given period" % nick, chan, ircsock) elif test == "None": sendmsg("%s: No user named '%s' was found =/" % (nick, test), chan, ircsock) else: sendmsg("%s has recently played:" % nick, chan, ircsock) for item in xrange(len(test)): sendmsg(str(test[item]), chan, ircsock) # Print help else: for item in xrange(len(lastfm.helpcmd(cfg.cmdsym()))): sendmsg(str(lastfm.helpcmd(cfg.cmdsym())[item]), chan, ircsock) elif cmd[0].lower() == "ragequit": raise Exception("spam", "eggs") # Module: lastfm - shortcuts elif cmd[0].lower() == "np": try: test = lastfm.now_playing(cmd[1]) if test is None: sendmsg("%s is not currently playing anything" % cmd[1], chan, ircsock) elif test == "None": sendmsg("No user named '%s' was found =/" % cmd[1], chan, ircsock) elif test == "timeout": sendmsg("Request timed out =/", chan, ircsock) else: sendmsg("%s is currently playing: %s" % (cmd[1], test), chan, ircsock) except IndexError: test = lastfm.now_playing(usernick) if test is None: sendmsg("%s is not currently playing anything" % usernick, chan, ircsock) elif test == "None": sendmsg("%s: No user named '%s' was found =/ " "You can set an alias with !lastfm set alias <lastfmuser>" % (usernick, test), chan, ircsock) elif test == "timeout": sendmsg("Request timed out =/", chan, ircsock) else: sendmsg("%s is currently playing: %s" % (usernick, test), chan, ircsock) elif cmd[0].lower() == "npt": try: sendmsg("%s is currently playing; %s" % (usernick, lastfm.test_playing(cmd[1])), chan, ircsock) except IndexError: sendmsg("Index derp", chan, ircsock) # Module: samba elif cmd[0].lower() == "samba": if len(cmd) > 1: if cmd[1] == "logins": sendmsg(samba.get_logins(cmd[2:]), chan, ircsock) elif cmd[1] == "np": if usernick.lower() == "bluabk": sendmsg(samba.get_playing(), chan, ircsock) else: sendmsg("%s: Get your own damn service, leech!" % usernick, chan, ircsock) elif cmd[1] == "np2": if usernick.lower() == "bluabk": sendmsg(samba.get_playing2(), chan, ircsock) else: sendmsg("%s: Get your own damn service, leech!" % usernick, chan, ircsock) else: for item in xrange(len(samba.helpcmd(cfg.cmdsym()))): sendmsg(str(samba.helpcmd(cfg.cmdsym())[item]), chan, ircsock) # Debug commands elif cmd[0].lower() == "debug": if len(cmd) >= 2 and cmd[1] == "logins": dbg = samba.get_logins(cmd[2:]) debug("Passed variable of length:" + str(len(dbg)), ircsock) for itr in range(len(dbg)): debug("Iteration: %s/%s" % (str(itr), str(len(dbg))), ircsock) debug(dbg[itr], ircsock) # Custom commands elif cmd[0].lower() == "addcommand": if ignored_nick("commands", usernick) is True: sendmsg("%s:ಠ_ಠ" % usernick, chan, ircsock) return if len(cmd) > 1: arg = list() for item in xrange(len(cmd)): if item > 1: if item != "\n": arg.append(cmd[item]) print "arg = %s" % arg fstr = " ".join(str(x) for x in arg) ret = add_custom_cmd(str(cmd[1]), fstr, usernick) sendmsg(ret, chan, ircsock) elif cmd[0].lower() == "removecommand": if ignored_nick("commands", usernick) is True: sendmsg("%s:ಠ_ಠ" % usernick, chan, ircsock) return if len(cmd) > 1: ret = del_custom_cmd(str(cmd[1]), usernick) sendmsg(ret, chan, ircsock) elif cmd[0].lower() == "addrawcommand" and usernick.lower() == "bluabk": if len(cmd) > 1: arg = list() for item in xrange(len(cmd)): if item > 1: if item != "\n": arg.append(cmd[item]) print "arg = %s" % arg fstr = " ".join(str(x) for x in arg) ret = add_custom_rawcmd(str(cmd[1]), fstr, usernick) sendmsg(ret, chan, ircsock) elif cmd[0].lower() == "removerawcommand" and usernick.lower() == "bluabk": if len(cmd) > 1: ret = del_custom_rawcmd(str(cmd[1]), usernick) sendmsg(ret, chan, ircsock) elif cmd[0].lower() == "listcustom": string_list = "" for item in cfg.lst_command(): string_list += (item[0] + " ") for item in cfg.lst_rawcommand(): string_list += (item[0] + "* ") sendmsg(string_list, chan, ircsock) # Module: Watch elif cmd[0].lower() == "watch": if len(cmd) > 1: if cmd[1] == "enable": watch_enabled = True sendmsg("Watch notifications enabled.", chan, ircsock) elif cmd[1] == "disable": watch_enabled = False sendmsg("Watch notifications disabled.", chan, ircsock) elif cmd[1] == "limit": print "watch: Setting watchlimit to %s" % cmd[2] watch.set_notify_limit(cmd[2]) sendmsg("Watch notifications limit set to %s" % cmd[2], chan, ircsock) else: for item in xrange(len(watch.helpcmd(cfg.cmdsym()))): sendmsg(str(watch.helpcmd(cfg.cmdsym())[item]), chan, ircsock) # Module: Stats elif cmd[0].lower() == "stats": if len(cmd) > 1: if cmd[1] == "cmd" or cmd[1] == "command": if len(cmd) > 2: sendmsg(stats.get_cmd(cmd[2]), chan, ircsock) else: for item in stats.get_cmd_all(): sendmsg("%s = %s" % (item[0], item[1]), chan, ircsock) elif cmd[1] == "user": # TODO: Code user stats get command sendmsg("Dummy function", chan, ircsock) else: for item in xrange(len(stats.helpcmd(cfg.cmdsym()))): sendmsg(str(stats.helpcmd(cfg.cmdsym())[item]), chan, ircsock) elif cmd[0].lower() in cfg.lst_command_option(): print "Executing custom command" custom_command(cmd[0].lower(), chan, ircsock) elif cmd[0].lower() in cfg.lst_rawcommand_option() and usernick in cfg.su(): print "Executing custom rawcommand" custom_rawcommand(cmd, usernick, chan, ircsock) # Module: YouTube elif cmd[0].lower() == "ytt" and module_exists("modules.youtube"): global youtube_url, ytt_trigger if len(cmd) > 1: if cmd[1].lower() == "trigger": if ytt_trigger is False: ytt_trigger = True sendmsg("YouTube Title: Changing to [trigger mode]", chan, ircsock) return else: ytt_trigger = False sendmsg("YouTube Title: Changing to [command mode]", chan, ircsock) return if youtube_url != "" and ytt_trigger is False: ytt_print(chan, ircsock) return # Private Module: yr elif cmd[0].lower() == "yr" and module_exists("weather"): kittens = True if len(cmd) > 1: if cmd[1] == "extreme": if len(cmd) > 2: extreme = yr.find_extreme_places(info=True, limit=int(cmd[2])) else: extreme = yr.find_extreme_places(info=True, limit=10) sendmsg("%s: %02d C & %s: %02d C" % ( extreme[0][0], extreme[0][1], extreme[1][0], extreme[1][1]), chan, ircsock) return try: forecast = yr.weather_update(" ".join(map(str, cmd[1:])), hour=time.localtime().tm_hour, minute=time.localtime().tm_min, debug=kittens) for item in cmd: if '@' in item: loc = " ".join(map(str, cmd[1:])) t = re.sub(r'\s+', "", loc[loc.find('@') + 1:len(loc)])[0:5].split(':') forecast = yr.weather_update(loc[0:loc.find('@')].strip(' '), hour=int(t[0]), minute=int(t[1]), debug=kittens) break prev = forecast print forecast if forecast is not None: sendmsg(forecast, chan, ircsock) elif prev is not None: sendmsg(forecast, chan, ircsock) else: sendmsg("No such weather station", chan, ircsock) except: sendmsg("https://www.konata.us/nope.gif", chan, ircsock)