Skip to content

Commit

Permalink
[dice, ip, movie, reload, spellcheck, tell, unicode_info, seen] s/wil…
Browse files Browse the repository at this point in the history
…lie/bot

Issue #276. Also PEP8ed per issue #125
  • Loading branch information
embolalia committed Jun 22, 2013
1 parent 55d0830 commit dae91fc
Show file tree
Hide file tree
Showing 8 changed files with 86 additions and 93 deletions.
27 changes: 11 additions & 16 deletions willie/modules/dice.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@
@willie.module.command("dice")
@willie.module.command("d")
@willie.module.priority("medium")
def dice(willie, trigger):
def dice(bot, trigger):
"""
.dice <formula> - Rolls dice using the XdY format, also does basic math and
drop lowest (XdYvZ).
"""
no_dice = True
if not trigger.group(2):
return willie.reply('You have to specify the dice you wanna roll.')
arr = trigger.group(2).lower().replace(' ','')
return bot.reply('You have to specify the dice you wanna roll.')
arr = trigger.group(2).lower().replace(' ', '')
arr = arr.replace('-', ' - ').replace('+', ' + ').replace('/', ' / ')
arr = arr.replace('*', ' * ').replace('(', ' ( ').replace(')', ' ) ')
arr = arr.replace('^', ' ^ ').replace('()', '').split(' ')
Expand All @@ -41,7 +41,7 @@ def dice(willie, trigger):
#check for invalid droplowest
dropLowest = int(result.group(3)[1:])
if(dropLowest >= int(result.group(2).split('d')[0] or 1)):
willie.reply('You\'re trying to drop too many dice.')
bot.reply('You\'re trying to drop too many dice.')
return
else:
dropLowest = 0
Expand Down Expand Up @@ -72,20 +72,20 @@ def dice(willie, trigger):
result = calculate(''.join(
full_string.replace('[', '#').replace(']', '#').split('#')[::2]))
if result == 'Sorry, no result.':
willie.reply('Calculation failed, did you try something weird?')
bot.reply('Calculation failed, did you try something weird?')
elif(no_dice):
willie.reply('For pure math, you can use .c '
bot.reply('For pure math, you can use .c '
+ trigger.group(2) + ' = ' + result)
else:
willie.reply('You roll ' + trigger.group(2) + ': ' + full_string + ' = '
bot.reply('You roll ' + trigger.group(2) + ': ' + full_string + ' = '
+ result)


def rollDice(diceroll):
rolls = int(diceroll.split('d')[0] or 1)
size = int(diceroll.split('d')[1])
result = [] # dice results.

for i in range(1, rolls + 1):
#roll 10 dice, pick a random dice to use, add string to result.
result.append((randint(1, size), randint(1, size), randint(1, size),
Expand All @@ -99,17 +99,12 @@ def rollDice(diceroll):
@willie.module.command("ch")
@willie.module.command("choose")
@willie.module.priority("medium")
def choose(willie, trigger):
def choose(bot, trigger):
"""
.choice option1|option2|option3 - Makes a difficult choice easy.
"""
if not trigger.group(2):
return willie.reply('I\'d choose an option, but you didn\'t give me any.')
return bot.reply('I\'d choose an option, but you didn\'t give me any.')
choices = re.split('[\|\\\\\/]', trigger.group(2))
pick = choice(choices)
return willie.reply('Your options: %s. My choice: %s' % (', '.join(choices), pick))


if __name__ == '__main__':
print __doc__.strip()

return bot.reply('Your options: %s. My choice: %s' % (', '.join(choices), pick))
10 changes: 4 additions & 6 deletions willie/modules/ip.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@
import socket
from willie.module import commands, example


@commands('iplookup', 'ip')
@example('.ip 8.8.8.8')
def ip(willie, trigger):
def ip(bot, trigger):
"""IP Lookup tool"""
if not trigger.group(2):
return willie.reply("No search term.")
return bot.reply("No search term.")
query = trigger.group(2)
# FIXME: This shouldn't be hardcoded
gi_city = pygeoip.GeoIP('/usr/share/GeoIP/GeoLiteCity.dat')
Expand All @@ -33,7 +34,4 @@ def ip(willie, trigger):
if isp is not None:
isp = re.sub('^AS\d+ ', '', isp)
response += " | ISP: %s" % isp
willie.say(response)

if __name__ == '__main__':
print __doc__.strip()
bot.say(response)
28 changes: 13 additions & 15 deletions willie/modules/movie.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,34 +10,32 @@
import willie.web as web
import willie.module


@willie.module.commands('movie', 'imdb')
@willie.module.example('.movie Movie Title')
def movie(willie, trigger):
def movie(bot, trigger):
"""
Returns some information about a movie, like Title, Year, Rating, Genre and IMDB Link.
"""
if not trigger.group(2):
return
word=trigger.group(2).rstrip()
word=word.replace(" ", "+")
uri="http://www.imdbapi.com/?t="+word
word = trigger.group(2).rstrip()
word = word.replace(" ", "+")
uri = "http://www.imdbapi.com/?t=" + word
u = web.get_urllib_object(uri, 30)
data = json.load(u) #data is a Dict containing all the information we need
data = json.load(u) # data is a Dict containing all the information we need
u.close()
if data['Response'] == 'False':
if 'Error' in data:
message = '[MOVIE] %s' % data['Error']
else:
willie.debug('movie', 'Got an error from the imdb api, search phrase was %s' % word, 'warning')
willie.debug('movie', str(data), 'warning')
bot.debug('movie', 'Got an error from the imdb api, search phrase was %s' % word, 'warning')
bot.debug('movie', str(data), 'warning')
message = '[MOVIE] Got an error from imdbapi'
else:
message = '[MOVIE] Title: ' +data['Title']+ \
' | Year: ' +data['Year']+ \
' | Rating: ' +data['imdbRating']+ \
' | Genre: ' +data['Genre']+ \
message = '[MOVIE] Title: ' + data['Title'] + \
' | Year: ' + data['Year'] + \
' | Rating: ' + data['imdbRating'] + \
' | Genre: ' + data['Genre'] + \
' | IMDB Link: http://imdb.com/title/' + data['imdbID']
willie.say(message)

if __name__ == '__main__':
print __doc__.strip()
bot.say(message)
60 changes: 30 additions & 30 deletions willie/modules/reload.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,32 +17,32 @@
@willie.module.nickname_command("reload")
@willie.module.priority("low")
@willie.module.thread(False)
def f_reload(willie, trigger):
def f_reload(bot, trigger):
"""Reloads a module, for use by admins only."""
if not trigger.admin:
return

name = trigger.group(2)
if name == willie.config.owner:
return willie.reply('What?')
if name == bot.config.owner:
return bot.reply('What?')

if (not name) or (name == '*') or (name.upper() == 'ALL THE THINGS'):
willie.callables = None
willie.commands = None
willie.setup()
return willie.reply('done')
bot.callables = None
bot.commands = None
bot.setup()
return bot.reply('done')

if not name in sys.modules:
return willie.reply('%s: no such module!' % name)
return bot.reply('%s: no such module!' % name)

old_module = sys.modules[name]

old_callables = {}
for obj_name, obj in vars(old_module).iteritems():
if willie.is_callable(obj):
if bot.is_callable(obj):
old_callables[obj_name] = obj

willie.unregister(old_callables)
bot.unregister(old_callables)
# Also remove all references to willie callables from top level of the
# module, so that they will not get loaded again if reloading the
# module does not override them.
Expand All @@ -54,72 +54,72 @@ def f_reload(willie, trigger):
if path.endswith('.pyc') or path.endswith('.pyo'):
path = path[:-1]
if not os.path.isfile(path):
return willie.reply('Found %s, but not the source file' % name)
return bot.reply('Found %s, but not the source file' % name)

module = imp.load_source(name, path)
sys.modules[name] = module
if hasattr(module, 'setup'):
module.setup(willie)
module.setup(bot)

mtime = os.path.getmtime(module.__file__)
modified = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(mtime))

willie.register(vars(module))
willie.bind_commands()
bot.register(vars(module))
bot.bind_commands()

willie.reply('%r (version: %s)' % (module, modified))
bot.reply('%r (version: %s)' % (module, modified))


if sys.version_info >= (2, 7):
def update(willie, trigger):
def update(bot, trigger):
if not trigger.admin:
return

"""Pulls the latest versions of all modules from Git"""
proc = subprocess.Popen('/usr/bin/git pull',
stdout=subprocess.PIPE,
stderr=subprocess.PIPE, shell=True)
willie.reply(proc.communicate()[0])
bot.reply(proc.communicate()[0])

f_reload(willie, trigger)
f_reload(bot, trigger)
else:
def update(willie, trigger):
willie.say('You need to run me on Python 2.7 to do that.')
def update(bot, trigger):
bot.say('You need to run me on Python 2.7 to do that.')
update.rule = ('$nick', ['update'], r'(.+)')


@willie.module.nickname_command("load")
@willie.module.priority("low")
@willie.module.thread(False)
def f_load(willie, trigger):
def f_load(bot, trigger):
"""Loads a module, for use by admins only."""
if not trigger.admin:
return

module_name = trigger.group(2)
path = ''
if module_name == willie.config.owner:
return willie.reply('What?')
if module_name == bot.config.owner:
return bot.reply('What?')

if module_name in sys.modules:
return willie.reply('Module already loaded, use reload')
return bot.reply('Module already loaded, use reload')

mods = willie.config.enumerate_modules()
mods = bot.config.enumerate_modules()
for name in mods:
if name == trigger.group(2):
path = mods[name]
if not os.path.isfile(path):
return willie.reply('Module %s not found' % module_name)
return bot.reply('Module %s not found' % module_name)

module = imp.load_source(module_name, path)
mtime = os.path.getmtime(module.__file__)
modified = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(mtime))
if hasattr(module, 'setup'):
module.setup(willie)
willie.register(vars(module))
willie.bind_commands()
module.setup(bot)
bot.register(vars(module))
bot.bind_commands()

willie.reply('%r (version: %s)' % (module, modified))
bot.reply('%r (version: %s)' % (module, modified))


if __name__ == '__main__':
Expand Down
20 changes: 10 additions & 10 deletions willie/modules/seen.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,42 +17,42 @@
seen_dict = Ddict(dict)


def get_user_time(willie, nick):
def get_user_time(bot, nick):
tz = 'UTC'
tformat = None
if willie.db and nick in willie.db.preferences:
tz = willie.db.preferences.get(nick, 'tz') or 'UTC'
tformat = willie.db.preferences.get(nick, 'time_format')
if bot.db and nick in bot.db.preferences:
tz = bot.db.preferences.get(nick, 'tz') or 'UTC'
tformat = bot.db.preferences.get(nick, 'time_format')
if tz not in pytz.all_timezones_set:
tz = 'UTC'
return (pytz.timezone(tz.strip()), tformat or '%Y-%m-%d %H:%M:%S %Z')


@command('seen')
def seen(willie, trigger):
def seen(bot, trigger):
"""Reports when and where the user was last seen."""
if not trigger.group(2):
willie.say(".seen <nick> - Reports when <nick> was last seen.")
bot.say(".seen <nick> - Reports when <nick> was last seen.")
return
nick = Nick(trigger.group(2).strip())
if nick in seen_dict:
timestamp = seen_dict[nick]['timestamp']
channel = seen_dict[nick]['channel']
message = seen_dict[nick]['message']

tz, tformat = get_user_time(willie, trigger.nick)
tz, tformat = get_user_time(bot, trigger.nick)
saw = datetime.datetime.fromtimestamp(timestamp, tz)
timestamp = saw.strftime(tformat)

msg = "I last saw %s at %s on %s, saying %s" % (nick, timestamp, channel, message)
willie.say(str(trigger.nick) + ': ' + msg)
bot.say(str(trigger.nick) + ': ' + msg)
else:
willie.say("Sorry, I haven't seen %s around." % nick)
bot.say("Sorry, I haven't seen %s around." % nick)


@rule('(.*)')
@priority('low')
def note(willie, trigger):
def note(bot, trigger):
if trigger.sender.startswith('#'):
nick = Nick(trigger.nick)
seen_dict[nick]['timestamp'] = time.time()
Expand Down
24 changes: 13 additions & 11 deletions willie/modules/spellcheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,32 +15,34 @@

@commands('spellcheck', 'spell')
@example('.spellcheck stuff')
def spellcheck(willie, trigger):
def spellcheck(bot, trigger):
"""
Says whether the given word is spelled correctly, and gives suggestions if
it's not.
"""
if not trigger.group(2):
return
word=trigger.group(2).rstrip()
word = trigger.group(2).rstrip()
if " " in word:
willie.say("One word at a time, please")
return;
bot.say("One word at a time, please")
return
dictionary = enchant.Dict("en_US")
dictionary_uk = enchant.Dict("en_GB")
# I don't want to make anyone angry, so I check both American and British English.
if dictionary_uk.check(word):
if dictionary.check(word): willie.say(word+" is spelled correctly")
else: willie.say(word+" is spelled correctly (British)")
if dictionary.check(word):
bot.say(word + " is spelled correctly")
else:
bot.say(word + " is spelled correctly (British)")
elif dictionary.check(word):
willie.say(word+" is spelled correctly (American)")
bot.say(word + " is spelled correctly (American)")
else:
msg = word+" is not spelled correctly. Maybe you want one of these spellings:"
msg = word + " is not spelled correctly. Maybe you want one of these spellings:"
sugWords = []
for suggested_word in dictionary.suggest(word):
sugWords.append(suggested_word)
for suggested_word in dictionary_uk.suggest(word):
sugWords.append(suggested_word)
for suggested_word in sorted(set(sugWords)): # removes duplicates
msg = msg + " '"+suggested_word+"',"
willie.say(msg)
for suggested_word in sorted(set(sugWords)): # removes duplicates
msg = msg + " '" + suggested_word + "',"
bot.say(msg)
2 changes: 1 addition & 1 deletion willie/modules/tell.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def get_user_time(bot, nick):
@nickname_command('tell')
@nickname_command('ask')
@example('Willie, tell Embolalia he broke something again.')
def f_remind(willie, trigger):
def f_remind(bot, trigger):
"""Give someone a message the next time they're seen"""
teller = trigger.nick

Expand Down
Loading

0 comments on commit dae91fc

Please sign in to comment.