Skip to content

Commit

Permalink
Pep8 passes, adds to tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
skoczen committed Apr 23, 2015
1 parent 6146e94 commit b941006
Show file tree
Hide file tree
Showing 10 changed files with 95 additions and 37 deletions.
1 change: 1 addition & 0 deletions circle.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ test:
override:
- /home/ubuntu/will/will/scripts/test_run.sh
- coverage run -m nose
- flake8
1 change: 1 addition & 0 deletions docs/improve.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ If you're looking for plugin inspiration, here are some wills that are open-sour
* `self.save()` now accepts an `expire` value, thanks to [netjunki](https://github.com/netjunki).
* Awesome new `remind ___ to ___ at ___`, thanks to [woohgit](https://github.com/woohgit).
* Will now keeps an eye on hipchat's uptime as well, thanks to [netjunki](https://github.com/netjunki).
* PEP8 support, with flake8 added to automated tests.

#### 0.7.3 - March 3, 2015

Expand Down
2 changes: 1 addition & 1 deletion tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
ignore = F401,N812,F403,E721,E713
max-line-length = 120
# exclude = tests/*
max-complexity = 12
# max-complexity = 12
20 changes: 15 additions & 5 deletions will/listener.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ def _handle_message_listeners(self, msg):
or (msg['type'] in ('chat', 'normal') and self.real_sender_jid(msg) != self.me.jid)
# we're in group chat and I didn't send it
or (msg["type"] == "groupchat" and msg['mucnick'] != self.nick)
):
):
body = msg["body"]

sent_directly_to_me = False
Expand All @@ -150,23 +150,28 @@ def _handle_message_listeners(self, msg):

for l in self.message_listeners:
search_matches = l["regex"].search(body)
if (search_matches # The search regex matches and
if (
search_matches # The search regex matches and
# It's not from me, or this search includes me, and
and (msg['mucnick'] != self.nick or l["include_me"])
# I'm mentioned, or this is an overheard, or we're in a 1-1
and (msg['type'] in ('chat', 'normal') or not l["direct_mentions_only"] or
self.handle_regex.search(body) or sent_directly_to_me)
# It's from admins only and sender is an admin, or it's not from admins only
and ((l['admin_only'] and self.message_is_from_admin(msg)) or (not l['admin_only']))
):
):
try:
thread_args = [msg, ] + l["args"]

def fn(listener, args, kwargs):
try:
listener["fn"](*args, **kwargs)
except:
content = "I ran into trouble running %s.%s:\n\n%s" % (listener["class_name"], listener["function_name"], traceback.format_exc(),)
content = "I ran into trouble running %s.%s:\n\n%s" % (
listener["class_name"],
listener["function_name"],
traceback.format_exc(),
)

if msg is None or msg["type"] == "groupchat":
if msg.sender and "nick" in msg.sender:
Expand All @@ -178,4 +183,9 @@ def fn(listener, args, kwargs):
thread = threading.Thread(target=fn, args=(l, thread_args, search_matches.groupdict()))
thread.start()
except:
logging.critical("Error running %s. \n\n%s\nContinuing...\n" % (l["function_name"], traceback.format_exc() ))
logging.critical(
"Error running %s. \n\n%s\nContinuing...\n" % (
l["function_name"],
traceback.format_exc()
)
)
79 changes: 59 additions & 20 deletions will/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,9 @@
import os
import operator
import re
import requests
import sys
import time
import threading
from clint.textui import colored
from clint.textui import puts, indent, columns
from clint.textui import colored, puts, indent
from os.path import abspath, dirname
from multiprocessing import Process, Queue

Expand All @@ -22,7 +19,7 @@
RoomMixin, PluginModulesLibraryMixin, EmailMixin
from scheduler import Scheduler
import settings
from utils import show_valid, error, warn, note, print_head
from utils import show_valid, error, warn, print_head


# Force UTF8
Expand Down Expand Up @@ -177,7 +174,9 @@ def verify_environment(self):
},
{
"name": "WILL_PASSWORD",
"obtain_at": "1. Go to hipchat, and create a new user for will. Note that password - this is the value you want. It's used for signing in via XMPP.",
"obtain_at": "1. Go to hipchat, and create a new user for will. "
"Note that password - this is the value you want. "
"It's used for signing in via XMPP.",
},
{
"name": "WILL_V2_TOKEN",
Expand All @@ -201,19 +200,22 @@ def verify_environment(self):
missing_settings = True

if missing_settings:
error("Will was unable to start because some required environment variables are missing. Please fix them and try again!")
error(
"Will was unable to start because some required environment "
"variables are missing. Please fix them and try again!"
)
sys.exit(1)
else:
puts("")

puts("Verifying credentials...")
# Parse 11111_222222@chat.hipchat.com into id, where 222222 is the id. Yup.
user_id = settings.USERNAME[0:settings.USERNAME.find("@")][settings.USERNAME.find("_")+1:]
user_id = settings.USERNAME[0:settings.USERNAME.find("@")][settings.USERNAME.find("_") + 1:]

# Splitting into a thread. Necessary because *BSDs (including OSX) don't have threadsafe DNS.
# http://stackoverflow.com/questions/1212716/python-interpreter-blocks-multithreaded-dns-requests
q = Queue()
p = Process(target=self.get_hipchat_user, args=(user_id,), kwargs={"q":q,})
p = Process(target=self.get_hipchat_user, args=(user_id,), kwargs={"q": q, })
p.start()
user_data = q.get()
p.join()
Expand All @@ -238,18 +240,23 @@ def load_config(self):
puts("Verifying rooms...")
# If we're missing ROOMS, join all of them.
with indent(2):
if settings.ROOMS == None:
if settings.ROOMS is None:
# Yup. Thanks, BSDs.
q = Queue()
p = Process(target=self.update_available_rooms, args=(), kwargs={"q":q,})
p = Process(target=self.update_available_rooms, args=(), kwargs={"q": q, })
p.start()
rooms_list = q.get()
show_valid("Joining all %s known rooms." % len(rooms_list))
os.environ["WILL_ROOMS"] = ";".join(rooms_list)
p.join()
settings.import_settings()
else:
show_valid("Joining the %s room%s specified." % (len(settings.ROOMS), "s" if len(settings.ROOMS)>1 else ""))
show_valid(
"Joining the %s room%s specified." % (
len(settings.ROOMS),
"s" if len(settings.ROOMS) > 1 else ""
)
)
puts("")

def verify_plugin_settings(self):
Expand All @@ -260,7 +267,8 @@ def verify_plugin_settings(self):
with indent(2):
for name, meta in self.required_settings_from_plugins.items():
if not hasattr(settings, name):
error_message = "%(setting_name)s is missing. It's required by the %(plugin_name)s plugin's '%(function_name)s' method." % meta
error_message = "%(setting_name)s is missing. "
"It's required by the %(plugin_name)s plugin's '%(function_name)s' method." % meta
puts(colored.red("✗ %(setting_name)s" % meta))
missing_setting_error_messages.append(error_message)
missing_settings = True
Expand All @@ -269,7 +277,11 @@ def verify_plugin_settings(self):

if missing_settings:
puts("")
warn("Will is missing settings required by some plugins. He's starting up anyway, but you will run into errors if you try to use those plugins!")
warn(
"Will is missing settings required by some plugins. "
"He's starting up anyway, but you will run into errors"
" if you try to use those plugins!"
)
self.add_startup_error("\n".join(missing_setting_error_messages))
else:
puts("")
Expand All @@ -294,10 +306,25 @@ def bootstrap_scheduler(self):

for plugin_info, fn, function_name in self.periodic_tasks:
meta = fn.will_fn_metadata
self.add_periodic_task(plugin_info["full_module_name"], plugin_info["name"], function_name, meta["sched_args"], meta["sched_kwargs"], meta["function_name"],)
self.add_periodic_task(
plugin_info["full_module_name"],
plugin_info["name"],
function_name,
meta["sched_args"],
meta["sched_kwargs"],
meta["function_name"],
)
for plugin_info, fn, function_name in self.random_tasks:
meta = fn.will_fn_metadata
self.add_random_tasks(plugin_info["full_module_name"], plugin_info["name"], function_name, meta["start_hour"], meta["end_hour"], meta["day_of_week"], meta["num_times_per_day"])
self.add_random_tasks(
plugin_info["full_module_name"],
plugin_info["name"],
function_name,
meta["start_hour"],
meta["end_hour"],
meta["day_of_week"],
meta["num_times_per_day"]
)
bootstrapped = True
except Exception, e:
self.startup_error("Error bootstrapping scheduler", e)
Expand Down Expand Up @@ -328,7 +355,7 @@ def bootstrap_xmpp(self):
try:
self.start_xmpp_client()
sorted_help = {}
for k,v in self.help_modules.items():
for k, v in self.help_modules.items():
sorted_help[k] = sorted(v)

self.save("help_modules", sorted_help)
Expand Down Expand Up @@ -459,7 +486,10 @@ def bootstrap_plugins(self):
puts("✗ %s (blacklisted)" % plugin_name)
else:
plugin_instances = {}
for function_name, fn in inspect.getmembers(plugin_info["class"], predicate=inspect.ismethod):
for function_name, fn in inspect.getmembers(
plugin_info["class"],
predicate=inspect.ismethod
):
try:
# Check for required_settings
with indent(2):
Expand All @@ -472,7 +502,11 @@ def bootstrap_plugins(self):
"function_name": function_name,
"setting_name": s,
}
if "listens_to_messages" in meta and meta["listens_to_messages"] and "listener_regex" in meta:
if (
"listens_to_messages" in meta and
meta["listens_to_messages"] and
"listener_regex" in meta
):
# puts("- %s" % function_name)
regex = meta["listener_regex"]
if not meta["case_sensitive"]:
Expand Down Expand Up @@ -525,7 +559,12 @@ def bootstrap_plugins(self):
self.bottle_routes.append((plugin_info["class"], function_name))
except Exception, e:
error(plugin_name)
self.startup_error("Error bootstrapping %s.%s" % (plugin_info["class"], function_name,), e)
self.startup_error(
"Error bootstrapping %s.%s" % (
plugin_info["class"],
function_name,
), e
)
show_valid(plugin_name)
except Exception, e:
self.startup_error("Error bootstrapping %s" % (plugin_info["class"],), e)
Expand Down
12 changes: 9 additions & 3 deletions will/mixins/room.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,22 @@ def history(self):
def participants(self):
payload = {"auth_token": settings.V2_TOKEN}
room_id = int(self['id'])
response = requests.get("https://{1}/v2/room/{0}/participant".format(str(room_id),
settings.HIPCHAT_SERVER),
params=payload, **settings.REQUESTS_OPTIONS).json()
response = requests.get(
"https://{1}/v2/room/{0}/participant".format(
str(room_id),
settings.HIPCHAT_SERVER
),
params=payload,
**settings.REQUESTS_OPTIONS
).json()
data = response['items']
while 'next' in response['links']:
response = requests.get(response['links']['next'],
params=payload, **settings.REQUESTS_OPTIONS).json()
data.extend(response['items'])
return data


class RoomMixin(object):
def update_available_rooms(self, q=None):
self._available_rooms = {}
Expand Down
2 changes: 1 addition & 1 deletion will/plugins/productivity/bitly.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,4 @@ def say_bitly_short_url(self, message, long_url=None):
c = bitly_api.Connection(access_token=settings.BITLY_ACCESS_TOKEN)
response = c.shorten(uri=long_url)
short_url = response['url']
self.say("Shorten URL: %s" % short_url, message=message)
self.say("Shorten URL: %s" % short_url, message=message)
11 changes: 6 additions & 5 deletions will/plugins/productivity/remind.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,12 @@ def remind_somebody_at(self, message, reminder_recipient=None, reminder_text=Non
parsed_time = self.parse_natural_time(remind_time)
natural_datetime = self.to_natural_day_and_time(parsed_time)

formatted_reminder_text = "@%(reminder_recipient)s, %(from_handle)s asked me to remind you %(reminder_text)s" % {
"reminder_recipient": reminder_recipient,
"from_handle": message.sender.nick,
"reminder_text": reminder_text,
}
formatted_reminder_text = \
"@%(reminder_recipient)s, %(from_handle)s asked me to remind you %(reminder_text)s" % {
"reminder_recipient": reminder_recipient,
"from_handle": message.sender.nick,
"reminder_text": reminder_text,
}

self.schedule_say(formatted_reminder_text, parsed_time, message=message)
self.say("%(reminder_text)s %(natural_datetime)s. Got it." % locals(), message=message)
2 changes: 1 addition & 1 deletion will/plugins/version/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
MODULE_DESCRIPTION = "Version"
MODULE_DESCRIPTION = "Version"
2 changes: 1 addition & 1 deletion will/plugins/version/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ class VersionPlugin(WillPlugin):
@respond_to("^version$")
def say_version(self, message):
version = pkg_resources.get_distribution("will").version
self.say("I'm running version %s" % version, message=message)
self.say("I'm running version %s" % version, message=message)

0 comments on commit b941006

Please sign in to comment.