convert most modules to use ! commands.

okay, it's time. we got around for a while with all sorts of silly
config options and exceptions and common strings triggering bot
commands. but now it's time to man up and expect modules to be
more strict and less loosey-goosey.

convert the popular modules (i.e. the ones that still work) to
trigger on !pi rather than pi, etc. usually, this is achieved via
regex searches, although there are some weird bugs (ones i'm hoping
are caused by other recursion/alias bugs and not this commit).

more code around this will be gutted soon, but this, at least,
means you can't say 'tweet that shit, yo' and accidentally trigger
the bot.
This commit is contained in:
Brian S. Stephan 2011-01-07 20:37:24 -06:00
parent 6b2af47552
commit 0bd681c324
15 changed files with 254 additions and 209 deletions

View File

@ -18,6 +18,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
from ConfigParser import NoOptionError, NoSectionError from ConfigParser import NoOptionError, NoSectionError
from datetime import datetime from datetime import datetime
import re
from dateutil.parser import * from dateutil.parser import *
from dateutil.relativedelta import * from dateutil.relativedelta import *
@ -33,69 +34,77 @@ class Countdown(Module):
def do(self, connection, event, nick, userhost, replypath, what, admin_unlocked): def do(self, connection, event, nick, userhost, replypath, what, admin_unlocked):
"""Add/retrieve countdown items.""" """Add/retrieve countdown items."""
whats = what.split(' ') match = re.search('^!countdown\s+add\s+(\S+)\s+(.*)$', what)
if whats[0] == 'countdown' and len(whats) >= 2: if match:
if whats[1] == 'add' and len(whats) >= 4: item = match.group(1)
item = whats[2] target = parse(match.group(2), default=datetime.now().replace(tzinfo=tzlocal()))
target = parse(' '.join(whats[3:]), default=datetime.now().replace(tzinfo=tzlocal()))
if not self.config.has_section(self.__class__.__name__):
self.config.add_section(self.__class__.__name__)
self.config.set(self.__class__.__name__, item, target.astimezone(tzutc()).isoformat()) if not self.config.has_section(self.__class__.__name__):
replystr = 'added countdown item ' + whats[2] self.config.add_section(self.__class__.__name__)
return self.reply(connection, replypath, replystr)
elif whats[1] == 'remove': self.config.set(self.__class__.__name__, item, target.astimezone(tzutc()).isoformat())
try: replystr = 'added countdown item ' + item
if self.config.remove_option(self.__class__.__name__, whats[2]): return self.reply(connection, replypath, replystr)
replystr = 'removed countdown item ' + whats[2]
return self.reply(connection, replypath, replystr) match = re.search('^!countdown\s+remove\s+(\S+)$', what)
except NoSectionError: pass if match:
elif whats[1] == 'list': try:
try: item = match.group(1)
cdlist = self.config.options(self.__class__.__name__) if self.config.remove_option(self.__class__.__name__, item):
self.remove_metaoptions(cdlist) replystr = 'removed countdown item ' + item
cdlist.sort() return self.reply(connection, replypath, replystr)
liststr = ', '.join(cdlist) except NoSectionError: pass
return self.reply(connection, replypath, liststr)
except NoSectionError: pass match = re.search('^!countdown\s+list$', what)
else: if match:
try: try:
timestr = self.config.get(self.__class__.__name__, whats[1]) cdlist = self.config.options(self.__class__.__name__)
time = parse(timestr) self.remove_metaoptions(cdlist)
rdelta = relativedelta(time, datetime.now().replace(tzinfo=tzlocal())) cdlist.sort()
relstr = whats[1] + ' will occur in ' liststr = ', '.join(cdlist)
if rdelta.years != 0: return self.reply(connection, replypath, liststr)
relstr += str(rdelta.years) + ' years ' except NoSectionError: pass
if rdelta.years > 1:
relstr += 's' match = re.search('^!countdown\s+(\S+)$', what)
relstr += ', ' if match:
if rdelta.months != 0: try:
relstr += str(rdelta.months) + ' month' item = match.group(1)
if rdelta.months > 1: timestr = self.config.get(self.__class__.__name__, item)
relstr += 's' time = parse(timestr)
relstr += ', ' rdelta = relativedelta(time, datetime.now().replace(tzinfo=tzlocal()))
if rdelta.days != 0: relstr = item + ' will occur in '
relstr += str(rdelta.days) + ' day' if rdelta.years != 0:
if rdelta.days > 1: relstr += str(rdelta.years) + ' years '
relstr += 's' if rdelta.years > 1:
relstr += ', ' relstr += 's'
if rdelta.hours != 0: relstr += ', '
relstr += str(rdelta.hours) + ' hour' if rdelta.months != 0:
if rdelta.hours > 1: relstr += str(rdelta.months) + ' month'
relstr += 's' if rdelta.months > 1:
relstr += ', ' relstr += 's'
if rdelta.minutes != 0: relstr += ', '
relstr += str(rdelta.minutes) + ' minute' if rdelta.days != 0:
if rdelta.minutes > 1: relstr += str(rdelta.days) + ' day'
relstr += 's' if rdelta.days > 1:
relstr += ', ' relstr += 's'
if rdelta.seconds != 0: relstr += ', '
relstr += str(rdelta.seconds) + ' second' if rdelta.hours != 0:
if rdelta.seconds > 1: relstr += str(rdelta.hours) + ' hour'
relstr += 's' if rdelta.hours > 1:
relstr += ', ' relstr += 's'
return self.reply(connection, replypath, relstr[0:-2]) relstr += ', '
except NoOptionError: pass if rdelta.minutes != 0:
relstr += str(rdelta.minutes) + ' minute'
if rdelta.minutes > 1:
relstr += 's'
relstr += ', '
if rdelta.seconds != 0:
relstr += str(rdelta.seconds) + ' second'
if rdelta.seconds > 1:
relstr += 's'
relstr += ', '
return self.reply(connection, replypath, relstr[0:-2])
except NoOptionError: pass
# vi:tabstop=4:expandtab:autoindent # vi:tabstop=4:expandtab:autoindent
# kate: indent-mode python;indent-width 4;replace-tabs on; # kate: indent-mode python;indent-width 4;replace-tabs on;

View File

@ -261,17 +261,18 @@ class Dice(Module):
return output return output
def do(self, connection, event, nick, userhost, replypath, what, admin_unlocked): def do(self, connection, event, nick, userhost, replypath, what, admin_unlocked):
whats = what.split(' ') match = re.search('^!roll\s+(.*)$', what)
if match:
if whats[0] == 'roll': dicestr = match.group(1)
dicestr = ' '.join(whats[1:])
self.build() self.build()
yacc.parse(dicestr) yacc.parse(dicestr)
reply = self.get_result() reply = self.get_result()
if reply is not "": if reply is not "":
return self.reply(connection, replypath, nick + ': ' + reply) return self.reply(connection, replypath, nick + ': ' + reply)
if whats[0] == 'ctech':
rollitrs = re.split(';\s*', ' '.join(whats[1:])) match = re.search('^!ctech\s+(.*)$', what)
if match:
rollitrs = re.split(';\s*', match.group(1))
reply = "" reply = ""
for count, roll in enumerate(rollitrs): for count, roll in enumerate(rollitrs):
pattern = '^(\d+)d(?:(\+|\-)(\d+))?(?:\s+(.*))?' pattern = '^(\d+)d(?:(\+|\-)(\d+))?(?:\s+(.*))?'

View File

@ -16,6 +16,8 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
""" """
import re
from extlib import irclib from extlib import irclib
from Module import Module from Module import Module
@ -27,9 +29,9 @@ class Echo(Module):
def do(self, connection, event, nick, userhost, replypath, what, admin_unlocked): def do(self, connection, event, nick, userhost, replypath, what, admin_unlocked):
"""Repeat provided text.""" """Repeat provided text."""
whats = what.split(' ') match = re.search('^!echo\s+(.*)$', what)
if whats[0] == 'echo' and len(whats) >= 2: if match:
return self.reply(connection, replypath, ' '.join(whats[1:])) return self.reply(connection, replypath, match.group(1))
# vi:tabstop=4:expandtab:autoindent # vi:tabstop=4:expandtab:autoindent
# kate: indent-mode python;indent-width 4;replace-tabs on; # kate: indent-mode python;indent-width 4;replace-tabs on;

View File

@ -17,6 +17,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
""" """
import random import random
import re
from extlib import irclib from extlib import irclib
@ -59,8 +60,8 @@ class EightBall(Module):
def do(self, connection, event, nick, userhost, replypath, what, admin_unlocked): def do(self, connection, event, nick, userhost, replypath, what, admin_unlocked):
"""Determine the response to the question. Spoiler alert: it's random.""" """Determine the response to the question. Spoiler alert: it's random."""
whats = what.split(' ') match = re.search('^!8ball', what)
if whats[0] == '8ball': if match:
response = self.responses[random.randint(1,len(self.responses))-1] response = self.responses[random.randint(1,len(self.responses))-1]
return self.reply(connection, replypath, response) return self.reply(connection, replypath, response)

View File

@ -59,33 +59,40 @@ class Facts(Module):
def do(self, connection, event, nick, userhost, replypath, what, admin_unlocked): def do(self, connection, event, nick, userhost, replypath, what, admin_unlocked):
"""Add or retrieve a fact from the database.""" """Add or retrieve a fact from the database."""
whats = what.split(' ') try:
if whats[0] == 'facts' and len(whats) >= 2:
db = self.get_db() db = self.get_db()
try: cur = db.cursor()
cur = db.cursor()
if len(whats) == 2:
category_facts = cur.execute('SELECT * FROM facts_facts WHERE category=?', (whats[1],))
else:
# before doing a query, see if this is actually an add attempt
if whats[1] == 'add' and len(whats) >= 4:
cur.execute('''INSERT INTO facts_facts (category, fact, who, userhost)
VALUES (?, ?, ?, ?)''', (whats[2], ' '.join(whats[3:]), nick, userhost))
db.commit()
return self.reply(connection, replypath, "fact added")
else:
category_facts = cur.execute('SELECT * FROM facts_facts WHERE category=? AND fact REGEXP ?', (whats[1], ' '.join(whats[2:])))
facts = category_facts.fetchall()
match = re.search('^!facts\s+add\s+(\S+)\s+(.*)$', what)
if match:
category = match.group(1)
fact = match.group(2)
cur.execute('''INSERT INTO facts_facts (category, fact, who, userhost)
VALUES (?, ?, ?, ?)''', (category, fact, nick, userhost))
db.commit()
return self.reply(connection, replypath, category + ' added.')
match = re.search('^!facts\s+(\S+)\s+(.*)$', what)
if match:
category = match.group(1)
regex = match.group(2)
category_facts = cur.execute('SELECT * FROM facts_facts WHERE category=? AND fact REGEXP ?', (category, regex))
facts = category_facts.fetchall()
if len(facts) > 0: if len(facts) > 0:
fact = facts[random.randint(1,len(facts))-1] fact = facts[random.randint(1,len(facts))-1]
# success
return self.reply(connection, replypath, fact['fact'].rstrip().encode('utf-8', 'ignore')) return self.reply(connection, replypath, fact['fact'].rstrip().encode('utf-8', 'ignore'))
except sqlite3.Error as e: match = re.search('^!facts\s+(\S+)$', what)
return self.reply(connection, replypath, "sqlite error: " + str(e)) if match:
category = match.group(1)
category_facts = cur.execute('SELECT * FROM facts_facts WHERE category=?', (category,))
facts = category_facts.fetchall()
if len(facts) > 0:
fact = facts[random.randint(1,len(facts))-1]
return self.reply(connection, replypath, fact['fact'].rstrip().encode('utf-8', 'ignore'))
except sqlite3.Error as e:
return self.reply(connection, replypath, "sqlite error: " + str(e))
# vi:tabstop=4:expandtab:autoindent # vi:tabstop=4:expandtab:autoindent
# kate: indent-mode python;indent-width 4;replace-tabs on; # kate: indent-mode python;indent-width 4;replace-tabs on;

View File

@ -16,6 +16,7 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
""" """
import re
from urllib2 import urlopen from urllib2 import urlopen
from urllib import urlencode from urllib import urlencode
@ -36,11 +37,11 @@ class GoogleTranslate(Module):
Leaves the input alone to let google make the best guess. Leaves the input alone to let google make the best guess.
""" """
whats = what.split(' ') match = re.search('^!translate\s+(\S+)\s+(\S+)\s+(.*)$', what)
if whats[0] == 'translate' and len(whats) >= 4: if match:
fromlang = whats[1] fromlang = match.group(1)
tolang = whats[2] tolang = match.group(2)
text = ' '.join(whats[3:]) text = match.group(3)
langpair = '%s|%s' % (fromlang, tolang) langpair = '%s|%s' % (fromlang, tolang)
gt_url = 'http://ajax.googleapis.com/ajax/services/language/translate' gt_url = 'http://ajax.googleapis.com/ajax/services/language/translate'

View File

@ -63,23 +63,23 @@ class IrcAdmin(Module):
whats = what.split(' ') whats = what.split(' ')
if whats[0] == 'join' and admin_unlocked and len(whats) >= 2: if whats[0] == '!join' and admin_unlocked and len(whats) >= 2:
return self.sub_join_channel(connection, event, nick, userhost, replypath, what, admin_unlocked) return self.sub_join_channel(connection, event, nick, userhost, replypath, what, admin_unlocked)
elif whats[0] == 'part' and admin_unlocked and len(whats) >= 2: elif whats[0] == '!part' and admin_unlocked and len(whats) >= 2:
return self.sub_part_channel(connection, event, nick, userhost, replypath, what, admin_unlocked) return self.sub_part_channel(connection, event, nick, userhost, replypath, what, admin_unlocked)
elif whats[0] == 'quit' and admin_unlocked: elif whats[0] == '!quit' and admin_unlocked:
return self.sub_quit_irc(connection, event, nick, userhost, replypath, what, admin_unlocked) return self.sub_quit_irc(connection, event, nick, userhost, replypath, what, admin_unlocked)
elif whats[0] == 'autojoin' and admin_unlocked and len(whats) >= 3: elif whats[0] == '!autojoin' and admin_unlocked and len(whats) >= 3:
return self.sub_autojoin_manipulate(connection, event, nick, userhost, replypath, what, admin_unlocked) return self.sub_autojoin_manipulate(connection, event, nick, userhost, replypath, what, admin_unlocked)
elif whats[0] == 'config' and whats[1] == 'save' and admin_unlocked: elif whats[0] == '!config' and whats[1] == 'save' and admin_unlocked:
return self.reply(connection, replypath, self.irc.save_config()) return self.reply(connection, replypath, self.irc.save_config())
elif whats[0] == 'nick' and admin_unlocked and len(whats) >= 2: elif whats[0] == '!nick' and admin_unlocked and len(whats) >= 2:
return self.sub_change_nick(connection, event, nick, userhost, replypath, what, admin_unlocked) return self.sub_change_nick(connection, event, nick, userhost, replypath, what, admin_unlocked)
elif whats[0] == 'load' and admin_unlocked and len(whats) >= 2: elif whats[0] == '!load' and admin_unlocked and len(whats) >= 2:
return self.sub_load_module(connection, event, nick, userhost, replypath, what, admin_unlocked) return self.sub_load_module(connection, event, nick, userhost, replypath, what, admin_unlocked)
elif whats[0] == 'reload' and admin_unlocked and len(whats) >= 2: elif whats[0] == '!reload' and admin_unlocked and len(whats) >= 2:
return self.sub_reload_module(connection, event, nick, userhost, replypath, what, admin_unlocked) return self.sub_reload_module(connection, event, nick, userhost, replypath, what, admin_unlocked)
elif whats[0] == 'unload' and admin_unlocked and len(whats) >= 2: elif whats[0] == '!unload' and admin_unlocked and len(whats) >= 2:
return self.sub_unload_module(connection, event, nick, userhost, replypath, what, admin_unlocked) return self.sub_unload_module(connection, event, nick, userhost, replypath, what, admin_unlocked)
def sub_join_channel(self, connection, event, nick, userhost, replypath, what, admin_unlocked): def sub_join_channel(self, connection, event, nick, userhost, replypath, what, admin_unlocked):

View File

@ -35,9 +35,9 @@ class Karma(Module):
pattern = "(?:(\S+)|\((.+)\))" pattern = "(?:(\S+)|\((.+)\))"
karmapattern = pattern + '(\+\+|--|\+-|-\+)' + '(\s+|$)' karmapattern = pattern + '(\+\+|--|\+-|-\+)' + '(\s+|$)'
querypattern = '^rank\s+(.*)' querypattern = '^!rank\s+(.*)'
reportpattern = '^karma\s+report\s+(highest|lowest|positive|negative)' reportpattern = '^!karma\s+report\s+(highest|lowest|positive|negative)'
statpattern = '^karma\s+stat\s+(.*)' statpattern = '^!karma\s+stat\s+(.*)'
self.karmare = re.compile(karmapattern) self.karmare = re.compile(karmapattern)
self.queryre = re.compile(querypattern) self.queryre = re.compile(querypattern)

View File

@ -64,7 +64,7 @@ class MegaHAL(Module):
append_nick = True append_nick = True
reply = mh_python.doreply(line) reply = mh_python.doreply(line)
elif re.search('^megahal$', line, re.IGNORECASE) is not None: elif re.search('^!megahal$', line, re.IGNORECASE) is not None:
reply = mh_python.doreply('') reply = mh_python.doreply('')
elif replypath is not None: elif replypath is not None:
# only learn if the command is not an internal one # only learn if the command is not an internal one

View File

@ -18,6 +18,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import math import math
import random import random
import re
import sqlite3 import sqlite3
from extlib import irclib from extlib import irclib
@ -67,7 +68,8 @@ class Pi(Module):
raise raise
def do(self, connection, event, nick, userhost, replypath, what, admin_unlocked): def do(self, connection, event, nick, userhost, replypath, what, admin_unlocked):
if what == "pi": match = re.search('^!pi$', what)
if match:
db = self.get_db() db = self.get_db()
try: try:
cur = db.cursor() cur = db.cursor()

View File

@ -1,18 +1,20 @@
# Seen - track when a person speaks, and allow data to be queried """
# Copyright (C) 2010 Brian S. Stephan Seen - track when a person speaks, and allow data to be queried
# Copyright (C) 2010 Brian S. Stephan
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by This program is free software: you can redistribute it and/or modify
# the Free Software Foundation, either version 3 of the License, or it under the terms of the GNU General Public License as published by
# (at your option) any later version. the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the but WITHOUT ANY WARRANTY; without even the implied warranty of
# GNU General Public License for more details. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from ConfigParser import NoOptionError from ConfigParser import NoOptionError
import re import re
@ -23,10 +25,10 @@ from extlib import irclib
from Module import Module from Module import Module
# Keeps track of when people say things in public channels, and reports on when
# they last said something.
class Seen(Module): class Seen(Module):
"""Track when people say things in public channels, and report on it."""
def do(self, connection, event, nick, userhost, replypath, what, admin_unlocked): def do(self, connection, event, nick, userhost, replypath, what, admin_unlocked):
# whatever it is, store it # whatever it is, store it
if not self.config.has_section(self.__class__.__name__): if not self.config.has_section(self.__class__.__name__):
@ -34,9 +36,9 @@ class Seen(Module):
self.config.set(self.__class__.__name__, nick, userhost + '|:|' + datetime.utcnow().isoformat() + '|:|' + what) self.config.set(self.__class__.__name__, nick, userhost + '|:|' + datetime.utcnow().isoformat() + '|:|' + what)
whats = what.split(' ') match = re.search('^!seen\s+(\S+)$', what)
if whats[0] == 'seen' and len(whats) >= 2: if match:
query = whats[1] query = match.group(1)
if query != 'debug': if query != 'debug':
try: try:
seendata = self.config.get(self.__class__.__name__, query).split('|:|') seendata = self.config.get(self.__class__.__name__, query).split('|:|')

View File

@ -17,6 +17,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
""" """
import base64 import base64
import re
from extlib import irclib from extlib import irclib
@ -47,9 +48,10 @@ class TextTransform(Module):
Apply a rot13 method to the text if first word is 'rot13'. Apply a rot13 method to the text if first word is 'rot13'.
""" """
whats = what.split(' ') match = re.search('^!rot13\s+(.*)$', what)
if whats[0] == "rot13": if match:
reply[0] = ' '.join(whats[1:]).encode('rot13', 'ignore') text = match.group(1)
reply[0] = text.encode('rot13', 'ignore')
return True return True
def base64(self, what, reply): def base64(self, what, reply):
@ -57,12 +59,16 @@ class TextTransform(Module):
Encode/decode base64 string. Encode/decode base64 string.
""" """
whats = what.split(' ') match = re.search('^!base64\s+encode\s+(.*)$', what)
if whats[0] == 'base64e' or whats[0] == 'base64': if match:
reply[0] = base64.encodestring(' '.join(whats[1:])).replace('\n','') text = match.group(1)
reply[0] = base64.encodestring(text).replace('\n','')
return True return True
if whats[0] == 'base64d':
reply[0] = base64.decodestring(' '.join(whats[1:])).replace('\n','') match = re.search('^!base64\s+decode\s+(.*)$', what)
if match:
text = match.group(1)
reply[0] = base64.decodestring(text).replace('\n','')
return True return True
def upper(self, what, reply): def upper(self, what, reply):
@ -70,9 +76,10 @@ class TextTransform(Module):
Convert a string to uppercase. Convert a string to uppercase.
""" """
whats = what.split(' ') match = re.search('^!upper\s+(.*)$', what)
if whats[0] == 'upper' and len(whats) >= 2: if match:
reply[0] = ' '.join(whats[1:]).upper() text = match.group(1)
reply[0] = text.upper()
return True return True
# vi:tabstop=4:expandtab:autoindent # vi:tabstop=4:expandtab:autoindent

View File

@ -16,8 +16,9 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
""" """
import urlparse import re
import oauth2 as oauth import oauth2 as oauth
import urlparse
from extlib import irclib from extlib import irclib
from extlib import twitter from extlib import twitter
@ -25,13 +26,11 @@ from extlib import twitter
from Module import Module from Module import Module
class Twitter(Module): class Twitter(Module):
""" """Access Twitter via the bot as an authenticated client."""
Access Twitter via the bot as an authenticated client.
"""
def __init__(self, irc, config, server): def __init__(self, irc, config, server):
"""
Prompt the user for oauth stuff when starting up. """Prompt the user for oauth stuff when starting up.
TODO: make this optional, and have API calls log if they need auth. TODO: make this optional, and have API calls log if they need auth.
""" """
@ -58,68 +57,81 @@ class Twitter(Module):
Attempt to do twitter things. Attempt to do twitter things.
""" """
whats = what.split(' ') match = re.search('^!twitter\s+getstatus\s+(\S+)$', what)
if whats[0] == 'twitter' and len(whats) >= 2: if match:
if whats[1] == 'status' and len(whats) == 3: status = match.group(1)
try: try:
tweet = self.twit.GetStatus(whats[2]) tweet = self.twit.GetStatus(status)
return self.reply(connection, replypath, self.tweet_or_retweet_text(tweet=tweet, print_source=True)) return self.reply(connection, replypath, self.tweet_or_retweet_text(tweet=tweet, print_source=True))
except twitter.TwitterError as e: except twitter.TwitterError as e:
return self.reply(connection, replypath, 'Couldn\'t obtain status: ' + str(e)) return self.reply(connection, replypath, 'Couldn\'t obtain status: ' + str(e))
elif whats[1] == 'user' and len(whats) >= 3:
if len(whats) >= 4: match = re.search('^!twitter\s+getuserstatus\s+(\S+)(\s+.*|$)', what)
index = int(whats[3]) if match:
if index > 0: user = match.group(1)
index = 0 index = match.group(2)
else:
if index:
index = int(index)
if index > 0:
index = 0 index = 0
else:
index = 0
count = (-1*index) + 1
count = (-1*index) + 1 try:
try: tweets = self.twit.GetUserTimeline(screen_name=user, count=count, include_rts=True)
tweets = self.twit.GetUserTimeline(screen_name=whats[2], count=count, include_rts=True) if tweets:
if tweets: tweet = tweets[-1*index]
tweet = tweets[-1*index] return self.reply(connection, replypath, self.tweet_or_retweet_text(tweet=tweet))
return self.reply(connection, replypath, self.tweet_or_retweet_text(tweet=tweet)) except twitter.TwitterError as e:
except twitter.TwitterError as e: return self.reply(connection, replypath, 'Couldn\'t obtain status: ' + str(e))
return self.reply(connection, replypath, 'Couldn\'t obtain status: ' + str(e))
elif whats[1] == 'tweet' and len(whats) >= 3:
if self.authed is False:
return self.reply(connection, replypath, 'You must be authenticated to tweet.')
if admin_unlocked is False:
return self.reply(connection, replypath, 'Only admins can tweet.')
try: match = re.search('^!twitter\s+tweet\s+(.*)', what)
if self.twit.PostUpdates(' '.join(whats[2:]), continuation='\xe2\x80\xa6') is not None: if match:
return self.reply(connection, replypath, 'Tweet(s) sent.') tweet = match.group(1)
else: if self.authed is False:
return self.reply(connection, replypath, 'Unknown error sending tweet(s).') return self.reply(connection, replypath, 'You must be authenticated to tweet.')
except twitter.TwitterError as e: if admin_unlocked is False:
return self.reply(connection, replypath, 'Couldn\'t tweet: ' + str(e)) return self.reply(connection, replypath, 'Only admins can tweet.')
elif whats[1] == 'gettoken':
# get request token
resp, content = self.client.request(self.request_token_url, "GET")
if resp['status'] != '200':
raise Exception("Invalid response %s." % resp['status'])
self.request_token = dict(urlparse.parse_qsl(content)) try:
if self.twit.PostUpdates(tweet, continuation='\xe2\x80\xa6') is not None:
return self.reply(connection, replypath, 'Tweet(s) sent.')
else:
return self.reply(connection, replypath, 'Unknown error sending tweet(s).')
except twitter.TwitterError as e:
return self.reply(connection, replypath, 'Couldn\'t tweet: ' + str(e))
# have the user auth match = re.search('^!twitter\s+gettoken$', what)
return self.reply(connection, replypath, 'Go to the following link in your browser: %s?oauth_token=%s and then send me the pin.' % (self.authorize_url, self.request_token['oauth_token'])) if match:
elif whats[1] == 'auth' and len(whats) >= 3: # get request token
oauth_verifier = whats[2] resp, content = self.client.request(self.request_token_url, "GET")
if resp['status'] != '200':
raise Exception("Invalid response %s." % resp['status'])
# request access token self.request_token = dict(urlparse.parse_qsl(content))
token = oauth.Token(self.request_token['oauth_token'], self.request_token['oauth_token_secret'])
token.set_verifier(oauth_verifier)
client = oauth.Client(self.consumer, token)
resp, content = client.request(self.access_token_url, "POST") # have the user auth
self.access_token = dict(urlparse.parse_qsl(content)) return self.reply(connection, replypath, 'Go to the following link in your browser: %s?oauth_token=%s and then send me the pin.' % (self.authorize_url, self.request_token['oauth_token']))
# finally, create the twitter API object match = re.search('^!twitter\s+auth\s+(\S+)$', what)
self.twit = twitter.Api(self.consumer_key, self.consumer_secret, self.access_token['oauth_token'], self.access_token['oauth_token_secret']) if match:
self.authed = True authtoken = match.group(1)
return self.reply(connection, replypath, 'The bot is now logged in.') oauth_verifier = authtoken
# request access token
token = oauth.Token(self.request_token['oauth_token'], self.request_token['oauth_token_secret'])
token.set_verifier(oauth_verifier)
client = oauth.Client(self.consumer, token)
resp, content = client.request(self.access_token_url, "POST")
self.access_token = dict(urlparse.parse_qsl(content))
# finally, create the twitter API object
self.twit = twitter.Api(self.consumer_key, self.consumer_secret, self.access_token['oauth_token'], self.access_token['oauth_token_secret'])
self.authed = True
return self.reply(connection, replypath, 'The bot is now logged in.')
def tweet_or_retweet_text(self, tweet, print_source=False): def tweet_or_retweet_text(self, tweet, print_source=False):
""" """

View File

@ -32,7 +32,7 @@ class Urls(Module):
"""Search for a URL from the store, or return a random one, or add one.""" """Search for a URL from the store, or return a random one, or add one."""
whats = what.split(' ') whats = what.split(' ')
if whats[0] == "url": if whats[0] == "!url":
try: try:
filename = self.config.get(self.__class__.__name__, 'urlfile') filename = self.config.get(self.__class__.__name__, 'urlfile')

View File

@ -33,10 +33,11 @@ class Weather(Module):
def do(self, connection, event, nick, userhost, replypath, what, admin_unlocked): def do(self, connection, event, nick, userhost, replypath, what, admin_unlocked):
"""Query Google Weather for a location's weather.""" """Query Google Weather for a location's weather."""
whats = what.split(' ') match = re.search('^!weather\s+(.*)$', what)
if whats[0] == "weather" and len(whats) >= 2: if match:
query = match.group(1)
try: try:
google_weather = pywapi.get_weather_from_google(quote(' '.join(whats[1:]))) google_weather = pywapi.get_weather_from_google(quote(query))
city = google_weather['forecast_information']['city'].encode('utf-8') city = google_weather['forecast_information']['city'].encode('utf-8')
condition = google_weather['current_conditions']['condition'].encode('utf-8') condition = google_weather['current_conditions']['condition'].encode('utf-8')
temp_f = google_weather['current_conditions']['temp_f'].encode('utf-8') temp_f = google_weather['current_conditions']['temp_f'].encode('utf-8')