Browse Source

resolve linter hints

mostly incorrect indentation on continuation lines and too-long lines
Helge Jung 9 years ago
parent
commit
368a773138
6 changed files with 131 additions and 50 deletions
  1. 85 44
      modules/ffpb.py
  2. 12 0
      modules/ffpb_fun.py
  3. 5 1
      modules/ffpb_hamburg.py
  4. 6 2
      modules/ffpb_monitoring.py
  5. 12 2
      modules/ffpb_netstatus.py
  6. 11 1
      modules/ffpb_nodeinfo.py

+ 85 - 44
modules/ffpb.py

@@ -28,9 +28,10 @@ nodeaccess = None
 
 alfred_method = None
 
-ffpb_resolver = dns.resolver.Resolver ()
+ffpb_resolver = dns.resolver.Resolver()
 ffpb_resolver.nameservers = ['10.132.254.53']
 
+
 class MsgHandler(SocketServer.BaseRequestHandler):
     """Reads line from TCP stream and forwards it to configured IRC channels."""
 
@@ -70,10 +71,12 @@ class MsgHandler(SocketServer.BaseRequestHandler):
         except dns.resolver.NXDOMAIN:
             return ipaddr
 
+
 class ThreadingTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
     """Defines a threaded TCP socket server."""
     bot = None
 
+
 def setup(bot):
     """Called by willie upon loading this plugin."""
 
@@ -97,7 +100,7 @@ def setup(bot):
     # open the git repository containing the peers files
     if not bot.config.ffpb.peers_directory is None:
         peers_repo = git.Repo(bot.config.ffpb.peers_directory)
-        assert peers_repo.bare == False
+        assert peers_repo.bare is False
 
     # if configured, start the messaging server
     if int(bot.config.ffpb.msg_enable) == 1:
@@ -128,6 +131,7 @@ def setup(bot):
     # signal end of setup routine
     bot.memory['ffpb_in_setup'] = False
 
+
 def shutdown(bot):
     global msgserver, nodeaccess
 
@@ -149,6 +153,7 @@ def shutdown(bot):
         print("Closed messaging server.")
         msgserver = None
 
+
 @willie.module.commands("help")
 @willie.module.commands("hilfe")
 @willie.module.commands("man")
@@ -180,9 +185,12 @@ def ffpb_help(bot, trigger):
 
     bot.say("Allgemeine Hilfe gibt's mit !help - ohne Parameter.")
 
+
 def playitsafe(bot, trigger,
-    botadmin=False, admin_channel=False, via_channel=False, via_privmsg=False, need_op=False, node=None,
-    reply_directly=True, debug_user=None, debug_ignorebotadmin=False):
+               botadmin=False, admin_channel=False,
+               via_channel=False, via_privmsg=False, need_op=False,
+               node=None, reply_directly=True,
+               debug_user=None, debug_ignorebotadmin=False):
     """
     helper: checks that the triggering user has the necessary rights
 
@@ -191,8 +199,8 @@ def playitsafe(bot, trigger,
     """
 
     if via_channel and via_privmsg:
-        raise Exception('Der Entwickler ist ein dummer, dummer Junge ' +
-            '(playitsafe hat via_channel + via_privmsg gleichzeitig gesetzt).')
+        raise Exception('Der Entwickler ist ein dummer, dummer Junge. ' +
+                        '(playitsafe: via_channel && via_privmsg).')
 
     user = trigger.nick if debug_user is None else debug_user
     user = user.lower()
@@ -212,11 +220,13 @@ def playitsafe(bot, trigger,
     # via_privmsg: the request must be a private conversation
     if via_privmsg and not trigger.is_privmsg:
         if reply_directly:
-            bot.say('Solche Informationen gibt es nur per PM, da bin ich ja schon ein klein wenig sensibel ...')
+            bot.say('Solche Informationen gibt es nur per PM, ' +
+                    'da bin ich ja schon ein klein wenig sensibel ...')
         return False
 
     # need_op: if the message is in a channel, check that the user has OP there
-    if need_op and (not trigger.is_privmsg) and (not user in bot.ops[trigger.sender]):
+    if need_op and (not trigger.is_privmsg) and \
+       (not user in bot.ops[trigger.sender]):
         if reply_directly:
             bot.say('Keine Zimtschnecke, keine Kekse.')
         return False
@@ -244,6 +254,7 @@ def playitsafe(bot, trigger,
 
     return True
 
+
 @willie.module.commands('nodeacl')
 def ffpb_nodeacl(bot, trigger):
     """Configure ACL for nodes."""
@@ -296,19 +307,19 @@ def ffpb_nodeacl(bot, trigger):
                 nodeaccess[uid] = []
             if not value in nodeaccess[uid]:
                 nodeaccess[uid].append(value)
-                bot.say('201 nodeACL \'{0}\' +\'{1}\''.format(uid, value))
+                bot.say("201 nodeACL '{0}' +'{1}'".format(uid, value))
             else:
-                bot.say('304 nodeACL \'{0}\' contains \'{1}\''.format(uid, value))
+                bot.say("304 nodeACL '{0}' contains '{1}'".format(uid, value))
 
         elif cmd == 'del':
             if len(uid) == 0:
-                bot.say('404 nodeACL \'{0}\''.format(uid))
+                bot.say("404 nodeACL '{0}'".format(uid))
                 return
             if value in nodeaccess[uid]:
                 nodeaccess[uid].remove(value)
-                bot.say('200 nodeACL \'{0}\' -\'{1}\''.format(uid, value))
+                bot.say("200 nodeACL '{0}' -'{1}'".format(uid, value))
             else:
-                bot.say('404 nodeACL \'{0}\' does not contain \'{1}\''.format(uid, value))
+                bot.say("404 nodeACL '{0}' has no '{1}'".format(uid, value))
 
         elif cmd == 'check':
             if len(uid) == 0:
@@ -320,17 +331,22 @@ def ffpb_nodeacl(bot, trigger):
                 bot.say('Nope, kein Plan was für ein Knoten das ist.')
                 return
 
-            result = playitsafe(bot, trigger, debug_user=uid[0], debug_ignorebotadmin=True, node=node, reply_directly=False)
-            if result == True:
+            result = playitsafe(bot, trigger,
+                                debug_user=uid[0], debug_ignorebotadmin=True,
+                                node=node, reply_directly=False)
+            if result is True:
                 bot.say('Jupp.')
-            elif result == False:
+            elif result is False:
                 bot.say('Nope.')
             else:
                 bot.say('Huh? result=' + str(result))
 
         return
 
-    bot.say('Unbekanntes Kommando. Probier "list [user]", "add user value" oder "del user value". Value kann node_id oder hostname-Maske sein.')
+    bot.say('Unbekanntes Kommando. Probier ' +
+            '"list [user]", "add user value" oder "del user value". ' +
+            'Value kann node_id oder hostname-Maske sein.')
+
 
 def ffpb_ensurenodeid(nodedata):
     """Makes sure that the given dict has a 'node_id' field."""
@@ -339,7 +355,9 @@ def ffpb_ensurenodeid(nodedata):
         return nodedata
 
     # derive node's id
-    nodeid = nodedata['network']['mac'].replace(':', '') if 'network' in nodedata and 'mac' in nodedata['network'] else None
+    nodeid = None
+    if 'network' in nodedata and 'mac' in nodedata['network']:
+        nodeid = nodedata['network']['mac'].replace(':', '')
 
     # assemble extended data
     result = {'node_id': nodeid}
@@ -348,6 +366,7 @@ def ffpb_ensurenodeid(nodedata):
 
     return result
 
+
 def ffpb_findnode(name, alfred_data=None, allow_fuzzymatching=True):
     """helper: try to identify the node the user meant by the given name"""
 
@@ -359,7 +378,7 @@ def ffpb_findnode(name, alfred_data=None, allow_fuzzymatching=True):
 
     # disable fuzzy matching if name is enclosed in quotes
     if name.startswith('\'') and name.endswith('\'') or \
-        name.startswith('"') and name.endswith('"'):
+       name.startswith('"') and name.endswith('"'):
         name = name[1:-1]
         allow_fuzzymatching = False
 
@@ -377,7 +396,7 @@ def ffpb_findnode(name, alfred_data=None, allow_fuzzymatching=True):
             for nodeid in alfred_data:
                 node = alfred_data[nodeid]
                 if "network" in node:
-                    if "mac" in node["network"] and node["network"]["mac"].lower() == mac:
+                    if node["network"].get("mac", "").lower() == mac:
                         return ffpb_ensurenodeid(node)
                     if "mesh_interfaces" in node["network"]:
                         for mim in node["network"]["mesh_interfaces"]:
@@ -431,7 +450,7 @@ def ffpb_findnode(name, alfred_data=None, allow_fuzzymatching=True):
                 'node_id': peer_mac.replace(':', ''),
                 'hostname': peer_name,
                 'network': {
-                    'addresses': [mac2ipv6(peer_mac, 'fdca:ffee:ff12:132:'),],
+                    'addresses': [mac2ipv6(peer_mac, 'fdca:ffee:ff12:132:'), ],
                     'mac': peer_mac,
                 },
                 'hardware': {
@@ -454,8 +473,9 @@ def ffpb_findnode(name, alfred_data=None, allow_fuzzymatching=True):
     # none of the above was able to identify the requested node
     return None
 
+
 def ffpb_findnode_from_botparam(bot, name, ensure_recent_alfreddata=True):
-    """helper: call ffpb_findnode() and give common answers via bot if nothing has been found"""
+    """helper: call ffpb_findnode() and give common answers via bot on error"""
 
     if name is None or len(name) == 0:
         if not bot is None:
@@ -466,7 +486,7 @@ def ffpb_findnode_from_botparam(bot, name, ensure_recent_alfreddata=True):
     if ensure_recent_alfreddata and alfred_data is None:
         if not bot is None:
             bot.say('Informationen sind ausverkauft bzw. veraltet, ' +
-                 'daher sage ich mal lieber nichts zu \'' + name + '\'.')
+                    'daher sage ich mal lieber nichts zu \'' + name + '\'.')
         return None
 
     node = ffpb_findnode(name, alfred_data)
@@ -476,6 +496,7 @@ def ffpb_findnode_from_botparam(bot, name, ensure_recent_alfreddata=True):
 
     return node
 
+
 def mac2ipv6(mac, prefix=None):
     """Calculate IPv6 address from given MAC,
     optionally replacing the fe80:: prefix with a given one."""
@@ -485,6 +506,7 @@ def mac2ipv6(mac, prefix=None):
         result = prefix + result[6:]
     return result
 
+
 @willie.module.interval(30)
 def ffpb_updatealfred(bot):
     """Aktualisiere ALFRED-Daten"""
@@ -522,7 +544,7 @@ def ffpb_updatealfred(bot):
     bot.memory['alfred_data'] = alfred_data
     bot.memory['alfred_update'] = updated
 
-    seen_nodes = bot.memory['seen_nodes'] if 'seen_nodes' in bot.memory else None
+    seen_nodes = bot.memory.get('seen_nodes', None)
     if not seen_nodes is None:
         new = []
         for nodeid in alfred_data:
@@ -569,14 +591,15 @@ def ffpb_updatealfred(bot):
                 action_target = bot.config.ffpb.msg_target_public
             bot.msg(action_target, '\x01ACTION %s\x01' % action_msg)
 
+
 def get_alfred_data(bot, ensure_not_outdated=True):
     """
     Retrieves the stored alfred_data and optionally checks
     that it has been updated no more than 5 minutes ago.
     """
 
-    alfred_data = bot.memory['alfred_data'] if 'alfred_data' in bot.memory else None
-    alfred_update = bot.memory['alfred_update'] if 'alfred_update' in bot.memory else 0
+    alfred_data = bot.memory.get('alfred_data', None)
+    alfred_update = bot.memory.get('alfred_update', 0)
 
     if alfred_data is None:
         return None
@@ -589,15 +612,17 @@ def get_alfred_data(bot, ensure_not_outdated=True):
 
     return alfred_data
 
+
 def ffpb_get_batcave_nodefield(nodeid, field):
     """Query the given field for the given nodeid from the BATCAVE."""
 
     raw_data = None
     try:
-            # query BATCAVE for node's field
+        # query BATCAVE for node's field
         raw_data = urllib2.urlopen('http://[fdca:ffee:ff12:a255::253]:8888/node/{0}/{1}'.format(nodeid, field))
     except urllib2.URLError as err:
-        print('Failed to contact BATCAVE for \'{0}\'->\'{1}\': {2}'.format(nodeid, field, err))
+        print('Failed to contact BATCAVE for \'{0}\'->\'{1}\': {2}'.format(
+              nodeid, field, err))
         return None
 
     try:
@@ -607,6 +632,7 @@ def ffpb_get_batcave_nodefield(nodeid, field):
         print('Could not parse BATCAVE\'s response as JSON for \'{0}\'->\'{1}\':'.format(nodeid, field, err))
         return None
 
+
 @willie.module.commands('debug-alfred')
 def ffpb_debug_alfred(bot, trigger):
     """Show statistics of available ALFRED data."""
@@ -615,7 +641,9 @@ def ffpb_debug_alfred(bot, trigger):
     if alfred_data is None:
         bot.say("Keine ALFRED-Daten vorhanden.")
     else:
-        bot.say("ALFRED Daten: count={0} lastupdate={1}".format(len(alfred_data), bot.memory['alfred_update']))
+        bot.say("ALFRED Daten: count={0} lastupdate={1}".format(
+                len(alfred_data), bot.memory['alfred_update']))
+
 
 @willie.module.interval(60)
 def ffpb_updatepeers(bot):
@@ -649,7 +677,8 @@ def ffpb_updatepeers(bot):
             else:
                 changed.append(f.a_blob.name)
 
-        response = "Knoten-Update (VPN +{0} %{1} -{2}): ".format(len(added), len(renamed)+len(changed), len(deleted))
+        response = "Knoten-Update (VPN +{0} %{1} -{2}): ".format(
+                   len(added), len(renamed)+len(changed), len(deleted))
         for f in added:
             response += " +'{}'".format(f)
         for f in changed:
@@ -661,6 +690,7 @@ def ffpb_updatepeers(bot):
 
         bot.msg(bot.config.ffpb.msg_target, response)
 
+
 def ffpb_fetch_stats(bot, url, memoryid):
     """Fetch a ffmap-style nodes.json from the given URL and
     store it in the bot's memory."""
@@ -697,6 +727,7 @@ def ffpb_fetch_stats(bot, url, memoryid):
 
     return (nodes_active, nodes_total, clients_count)
 
+
 def pretty_date(timestamp=False):
     """
     Get a datetime object or a int() Epoch timestamp and return a
@@ -739,6 +770,7 @@ def pretty_date(timestamp=False):
         return "vor " + str(day_diff) + " Tagen"
     return "am " + compare.strftime('%d.%m.%Y um %H:%M Uhr')
 
+
 @willie.module.commands('ping')
 def ffpb_ping(bot, trigger=None, target_name=None, reply_directly=True):
     """Ping the given node"""
@@ -747,12 +779,13 @@ def ffpb_ping(bot, trigger=None, target_name=None, reply_directly=True):
     if target_name is None:
         target_name = trigger.group(2)
     node = ffpb_findnode_from_botparam(bot, target_name,
-        ensure_recent_alfreddata=False)
+                                       ensure_recent_alfreddata=False)
     if node is None:
         return None
 
     # get the first non-linklocal address from the node
-    target = [x for x in node["network"]["addresses"] if not x.lower().startswith("fe80:")][0]
+    target = [x for x in node["network"]["addresses"]
+              if not x.lower().startswith("fe80:")][0]
     target_alias = node["hostname"]
 
     # execute the actual ping and reply the result
@@ -777,6 +810,7 @@ def ffpb_ping(bot, trigger=None, target_name=None, reply_directly=True):
             bot.say('Uh oh, irgendwas ist kaputt. Chef, ping result = ' + str(result) + ' - darf ich das essen?')
         return None
 
+
 @willie.module.commands('mesh')
 def ffpb_nodemesh(bot, trigger):
     """Display mesh partners of the given node."""
@@ -784,22 +818,24 @@ def ffpb_nodemesh(bot, trigger):
     # identify node or bail out
     target_name = trigger.group(2)
     node = ffpb_findnode_from_botparam(bot, target_name,
-        ensure_recent_alfreddata=False)
+                                       ensure_recent_alfreddata=False)
     if node is None:
         return None
 
     # derive node's id
     nodeid = node['node_id'] if 'node_id' in node else None
     if nodeid is None:
-        msg = 'Mist, ich habe gerade den Zettel verlegt auf dem die Node-ID von \'{0}\' steht, bitte frag später noch einmal.'
-        bot.say(msg.format(node['hostname'] if 'hostname' in node else target_name))
+        msg = 'Mist, ich habe gerade den Zettel verlegt auf dem die Node-ID' + \
+              ' von \'{0}\' steht, bitte frag später noch einmal.'
+        bot.say(msg.format(node.get('hostname', target_name)))
         return
 
     # query BATCAVE for node's neighbours (result is a list of MAC addresses)
     cave_result = ffpb_get_batcave_nodefield(nodeid, 'neighbours')
     if cave_result is None:
-        msg = 'Hm, scheinbar liegen zu \'{0}\' keine Daten vor. Klingt komisch, ist aber so.'
-        bot.say(msg.format(node['hostname'] if 'hostname' in node else target_name))
+        msg = 'Hm, scheinbar liegen zu \'{0}\' keine Daten vor. ' + \
+              'Klingt komisch, ist aber so.'
+        bot.say(msg.format(node.get('hostname', target_name)))
         return
 
     # query BATCAVE for neighbour's names
@@ -811,10 +847,10 @@ def ffpb_nodemesh(bot, trigger):
     gateways = set()
     for line in req:
         ident, name = line.strip().split('=')
-	if ident == name and ident.startswith('c0:ff:ee:ba:be:'):
-            gateways.add('Gateway ' + ident[len('c0:ff:ee:ba:be:'):])
-        else:
-            neighbours.add(name)
+    if ident == name and ident.startswith('c0:ff:ee:ba:be:'):
+        gateways.add('Gateway ' + ident[len('c0:ff:ee:ba:be:'):])
+    else:
+        neighbours.add(name)
     neighbours = [x for x in neighbours]
     gateways = sorted([x for x in gateways])
 
@@ -825,7 +861,9 @@ def ffpb_nodemesh(bot, trigger):
     elif len(neighbours) == 1:
         reply += u' mesht mit \'{0}\''.format(neighbours[0])
     else:
-        reply += ' mesht mit \'{0}\' und \'{1}\''.format('\', \''.join(neighbours[:-1]), neighbours[-1])
+        all_except_last = '\', \''.join(neighbours[:-1])
+        last = neighbours[-1]
+        reply += ' mesht mit \'{0}\' und \'{1}\''.format(all_except_last, last)
 
     if len(gateways) > 0:
         if len(neighbours) == 0:
@@ -836,10 +874,13 @@ def ffpb_nodemesh(bot, trigger):
         if len(gateways) == 1:
             reply += gateways[0]
         else:
-            reply += '{0} und {1}'.format('\', \''.join(gateways[:-1]), gateways[-1])
+            all_except_last = '\', \''.join(gateways[:-1])
+            last = gateways[-1]
+            reply += '{0} und {1}'.format(all_except_last, last)
 
     bot.say(reply)
 
+
 @willie.module.commands('exec-on-peer')
 def ffpb_remoteexec(bot, trigger):
     """Remote execution on the given node"""
@@ -855,7 +896,7 @@ def ffpb_remoteexec(bot, trigger):
 
     # identify requested node or bail out
     node = ffpb_findnode_from_botparam(bot, target_name,
-        ensure_recent_alfreddata=False)
+                                       ensure_recent_alfreddata=False)
     if node is None:
         return
 

+ 12 - 0
modules/ffpb_fun.py

@@ -6,16 +6,19 @@ import random
 
 COFFEE_RULE = '(make[_-]me[_-](a[_-])?)?coffee'
 
+
 def setup(bot):
     """Called by willie upon loading this plugin."""
 
     pass
 
+
 def shutdown(bot):
     """Called by willie upon unloading this plugin."""
 
     pass
 
+
 @willie.module.rule(r'(?i)(hi|hallo|moin|morgen|guten morgen|re)[ \t]*$')
 def ffpb_greeting(bot, trigger):
     stats = bot.memory['ffpb_stats'] if 'ffpb_stats' in bot.memory else None
@@ -30,6 +33,7 @@ def ffpb_greeting(bot, trigger):
         '{1} Knoten online, {2} Clients im Netz und {0} gibt uns die Ehre - Herzlich Willkommen :)'))
     bot.say(greeting.format(trigger.nick, stats["nodes_active"], stats["clients"]))
 
+
 @willie.module.rule(r'(?i)(alles )?fake[?!]?')
 def ffpb_nofake(bot, trigger):
     msg = random.choice((
@@ -38,34 +42,42 @@ def ffpb_nofake(bot, trigger):
     ))
     bot.action(msg.format(trigger.nick))
 
+
 @willie.module.commands('fake')
 def ffpb_fakecmd(bot, trigger):
     bot.say('Public Service Announcement: {0} ist ein Fake.'.format(trigger.nick))
 
+
 @willie.module.rule(r'(?i)!(sudo )?rm -rf (--no-preserve-root )?/')
 def ffpb_rmrf(bot, trigger):
     bot.action("liest dann mal sehr schnell " + trigger.nick + "s Mails o.O")
 
+
 @willie.module.rule(r'(?i)!' + COFFEE_RULE)
 def ffpb_kaffee(bot, trigger):
     bot.say("Kein sudo, kein Kaffee.")
 
+
 @willie.module.rule(r'(?i)!sudo ' + COFFEE_RULE)
 def ffpb_sudokaffee(bot, trigger):
     bot.action("reicht " + trigger.nick + " eine dampfende, aromatisch duftende Tasse Kaffee.")
 
+
 @willie.module.rule(r'(?i).*(teurer|besser|neuer|cooler|geiler|mehr|weniger) wie')
 def ffpb_grammarnazi_als(bot, trigger):
     bot.say("*als")
 
+
 @willie.module.rule(r'(?i).*(genauso|genau so) als')
 def ffpb_grammarnazi_wie(bot, trigger):
     bot.say("*wie")
 
+
 @willie.module.rule(r'(?i).*als wie')
 def ffpb_grammarnazi_alswie(bot, trigger):
     bot.action("denkt spontan an seine Deutschlehrerin")
 
+
 @willie.module.rule(r'(?i)gi(ve |m)me the key to your heart')
 def ffpb_botkey(bot, trigger):
     bot.reply('ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDJfsG/myO4y9WzJSP+ixluHFmkIMJJRsvRT8t5h4y/5A7QzovOw1GpCmWJWnZ6GKXilTxb8ycqVfDcFPB2NRkdJUjYL+v4IMriPeBigAjc6FoUZXOS3TOZVhaTlNT4XxXKOYF/Rpgscv5f0iu1SG0Tp4mb2TX04pZjbnLNBABbjn592abEuMG5bH/g9odi50S0MoU/qCH9AZvkoc8vGu+flOBrKfFi+7g2GxF/w66mMvCJfK27QFSPOiFV3CT6ZfSZM138OCdC1SOi89X9+oCEQ3LB9A+bJgyYnxqp8eVpRPui6K9sPkax71tMimRJA5Xgdvqt9HpcgtNYxKJ4gYMR ffpb-statusbot')

+ 5 - 1
modules/ffpb_hamburg.py

@@ -4,6 +4,7 @@ import willie
 
 from ffpb import ffpb_fetch_stats
 
+
 def setup(bot):
     """Called by willie upon loading this plugin."""
 
@@ -12,11 +13,13 @@ def setup(bot):
     except:
         pass
 
+
 def shutdown(bot):
     """Called by willie upon unloading this plugin."""
 
     pass
 
+
 @willie.module.interval(60)
 def ffpb_hamburg_fetch(bot):
     ffpb_fetch_stats(bot, 'https://hamburg.freifunk.net/nodes_ffhh/nodes.json', 'ffhh_stats')
@@ -37,9 +40,10 @@ def ffpb_hamburg_fetch(bot):
                 action_target = bot.config.ffpb.msg_target_public
             bot.msg(action_target, '\x01ACTION %s\x01' % action_msg)
 
+
 @willie.module.commands('hamburg')
 def ffpb_hamburg(bot, trigger):
-    hamburg_data = bot.memory['ffhh_stats'] if 'ffhh_stats' in bot.memory else None
+    hamburg_data = bot.memory.get('ffhh_stats', None)
     if hamburg_data is None:
         bot.say('Hamburg, was ist schon Hamburg ... zumindest habe ich gerade keine Daten.')
         return

+ 6 - 2
modules/ffpb_monitoring.py

@@ -9,6 +9,7 @@ from ffpb import ffpb_ping, playitsafe, pretty_date
 
 monitored_nodes = None
 
+
 def setup(bot):
     """Called by willie upon loading this plugin."""
 
@@ -17,6 +18,7 @@ def setup(bot):
     # load list of monitored nodes and their last status from disk
     monitored_nodes = shelve.open('nodes.monitored', writeback=True)
 
+
 def shutdown(bot):
     """Called by willie upon unloading this plugin."""
 
@@ -28,6 +30,7 @@ def shutdown(bot):
         monitored_nodes.close()
         monitored_nodes = None
 
+
 @willie.module.interval(3*60)
 def ffpb_monitor_ping(bot):
     """Ping each node currently under surveillance."""
@@ -52,7 +55,7 @@ def ffpb_monitor_ping(bot):
         mon['status'] = current_status
         mon['last_check'] = time.time()
 
-        if current_status == True:
+        if current_status is True:
             mon['last_success'] = time.time()
 
         print("Monitoring ({0}) {1} (last: {2} at {3})".format(
@@ -66,7 +69,7 @@ def ffpb_monitor_ping(bot):
                 # erster Check, keine Ausgabe
                 continue
 
-            if current_status == True:
+            if current_status is True:
                 msg = 'Monitoring: Knoten \'{0}\' pingt wieder (zuletzt {1})'
             else:
                 msg = 'Monitoring: Knoten \'{0}\' DOWN'
@@ -75,6 +78,7 @@ def ffpb_monitor_ping(bot):
                 pretty_date(last_success) if not last_success is None else '[nie]',
             ))
 
+
 @willie.module.commands('monitor')
 def ffpb_monitor(bot, trigger):
     """

+ 12 - 2
modules/ffpb_netstatus.py

@@ -11,6 +11,7 @@ from ffpb import ffpb_fetch_stats, get_alfred_data, pretty_date
 
 highscores = None
 
+
 def setup(bot):
     """Called by willie upon loading this plugin."""
 
@@ -25,6 +26,7 @@ def setup(bot):
         highscores['clients'] = 0
         highscores['clients_ts'] = time.time()
 
+
 def shutdown(bot):
     """Called by willie upon loading this plugin."""
 
@@ -36,6 +38,7 @@ def shutdown(bot):
         highscores.close()
         highscores = None
 
+
 @willie.module.interval(15)
 def ffpb_get_stats(bot):
     """Fetch current statistics, if the highscore changes signal this."""
@@ -73,6 +76,7 @@ def ffpb_get_stats(bot):
                 highscores['clients'], pretty_date(int(highscores['clients_ts'])),
             ))
 
+
 @willie.module.commands('status')
 def ffpb_status(bot, trigger):
     """State of the network: count of nodes + clients"""
@@ -82,7 +86,9 @@ def ffpb_status(bot, trigger):
         bot.say('Uff, kein Plan wo der Zettel ist. Fragst du später nochmal?')
         return
 
-    bot.say('Es sind {0} Knoten und ca. {1} Clients online.'.format(stats["nodes_active"], stats["clients"]))
+    bot.say('Es sind {0} Knoten und ca. {1} Clients online.'.format(
+            stats["nodes_active"], stats["clients"]))
+
 
 @willie.module.commands('batcave-status')
 def ffpb_batcave_status(bot, trigger):
@@ -91,6 +97,7 @@ def ffpb_batcave_status(bot, trigger):
     status = json.loads(urllib2.urlopen('http://[fdca:ffee:ff12:a255::253]:8888/status').read())
     bot.say('Status: ' + str(json.dumps(status))[1:-1])
 
+
 @willie.module.commands('highscore')
 def ffpb_highscore(bot, trigger):
     """Print current highscores (nodes + clients)."""
@@ -99,6 +106,7 @@ def ffpb_highscore(bot, trigger):
         highscores['nodes'], pretty_date(int(highscores['nodes_ts'])),
         highscores['clients'], pretty_date(int(highscores['clients_ts']))))
 
+
 @willie.module.commands('rollout-status')
 def ffpb_rolloutstatus(bot, trigger):
     """Display statistic on how many nodes have installed the given firmware version."""
@@ -167,6 +175,7 @@ def ffpb_rolloutstatus(bot, trigger):
     if skipped > 0:
         bot.say('plus {0} Knoten deren Status gerade nicht abfragbar war'.format(skipped))
 
+
 @willie.module.commands('providers')
 def ffpb_providers(bot, trigger):
     """Fetch the top 5 providers from BATCAVE."""
@@ -174,5 +183,6 @@ def ffpb_providers(bot, trigger):
     providers = json.load(urllib2.urlopen('http://[fdca:ffee:ff12:a255::253]:8888/providers?format=json'))
     providers.sort(key=lambda x: x['count'], reverse=True)
 
-    top5 = ['{0} ({1:.0f}%)'.format(x['name'], x['percentage']) for x in providers[:5]]
+    top5 = providers[:5]
+    top5 = ['{0} ({1:.0f}%)'.format(x['name'], x['percentage']) for x in top5]
     bot.say('Unsere Top 5 Provider: ' + ', '.join(top5))

+ 11 - 1
modules/ffpb_nodeinfo.py

@@ -3,18 +3,24 @@ from __future__ import print_function
 import time
 import willie
 
-from ffpb import ffpb_findnode_from_botparam, ffpb_get_batcave_nodefield, mac2ipv6, playitsafe, pretty_date
+from ffpb import \
+    ffpb_findnode_from_botparam, \
+    ffpb_get_batcave_nodefield, \
+    mac2ipv6, playitsafe, pretty_date
+
 
 def setup(bot):
     """Called by willie upon loading this plugin."""
 
     pass
 
+
 def shutdown(bot):
     """Called by willie upon unloading this plugin."""
 
     pass
 
+
 @willie.module.commands('alfred-data')
 def ffpb_peerdata(bot, trigger):
     """Show ALFRED data of the given node."""
@@ -38,6 +44,7 @@ def ffpb_peerdata(bot, trigger):
 
         bot.say("{0}.{1} = {2}".format(node['hostname'], key, node[key]))
 
+
 @willie.module.commands('info')
 def ffpb_peerinfo(bot, trigger):
     """Show information of the given node."""
@@ -98,6 +105,7 @@ def ffpb_peerinfo(bot, trigger):
 
     bot.say('[{1}]{2}{3}{4}{5}{6}'.format(info_mac, info_name, info_hw, info_fw, info_update, info_uptime, info_clients))
 
+
 @willie.module.commands('last-seen')
 @willie.module.commands('last_seen')
 @willie.module.commands('lastseen')
@@ -135,6 +143,7 @@ def ffpb_lastseen(bot, trigger):
             pretty_date(b_value) if not b_value is None else "nie"
         ))
 
+
 @willie.module.commands('uptime')
 def ffpb_peeruptime(bot, trigger):
     """Display the uptime of the given node."""
@@ -172,6 +181,7 @@ def ffpb_peeruptime(bot, trigger):
     # reply to user
     bot.say('uptime(\'{0}\') = {1}'.format(info_name, info_uptime))
 
+
 @willie.module.commands('link')
 def ffpb_peerlink(bot, trigger):
     """Display MAC and link to statuspage for the given node."""