Skip to content

Commit

Permalink
This change makes ".xkcd" module more robust:
Browse files Browse the repository at this point in the history
- don't allow negative numbers which accesses a comic number lower than 0
- don't allow the 0th comic when randomly checked
- allow also a "+" as a sign
- remove a possible #
- don't show an error when accessing sopel-irc#404
- don't show an error when no search.google_search() returned None
  • Loading branch information
xZise committed Aug 8, 2014
1 parent 9604bfc commit 33eec04
Showing 1 changed file with 28 additions and 17 deletions.
45 changes: 28 additions & 17 deletions willie/modules/xkcd.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ def get_info(number=None):

def google(query):
url = google_search(query + sites_query)
if not url:
return None
match = re.match('(?:https?://)?xkcd.com/(\d+)/?', url)
if match:
return match.group(1)
Expand All @@ -66,27 +68,17 @@ def xkcd(bot, trigger):
# if no input is given (pre - lior's edits code)
if not trigger.group(2): # get rand comic
random.seed()
requested = get_info(random.randint(0, max_int + 1))
requested = get_info(random.randint(1, max_int + 1))
else:
query = trigger.group(2).strip()

# Positive or 0; get given number or latest
if query.isdigit():
if query[0] == "#":
query = query[1:]

try:
query = int(query)
if query > max_int:
bot.say(("Sorry, comic #{} hasn't been posted yet. "
"The last comic was #{}").format(query, max_int))
return
elif query == 0:
requested = latest
else:
requested = get_info(query)
# Negative: go back that many from current
elif query[0] == '-' and query[1:].isdigit():
query = int(query[1:])
requested = get_info(max_int - query)
# Non-number: google.
else:
except ValueError:
# Non-number: google.
if (query.lower() == "latest" or query.lower() == "newest"):
requested = latest
else:
Expand All @@ -95,6 +87,25 @@ def xkcd(bot, trigger):
bot.say('Could not find any comics for that query.')
return
requested = get_info(number)
else:
if query > max_int:
bot.say(("Sorry, comic #{} hasn't been posted yet. "
"The last comic was #{}").format(query, max_int))
return
elif query <= -max_int:
bot.say(("Sorry, but there were only {} comics "
"released yet").format(max_int))
return
elif abs(query) == 0:
requested = latest
elif query == 404 or max_int + query == 404:
bot.say("404 - Not Found") # don't error on that one
return
elif query > 0:
requested = get_info(query)
else:
# Negative: go back that many from current
requested = get_info(max_int + query)

message = '{} [{}]'.format(requested['url'], requested['title'])
bot.say(message)

0 comments on commit 33eec04

Please sign in to comment.