2010-12-15 23:08:08 -06:00
"""
Twitter - access to Twitter through bot commands
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
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
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 / > .
"""
2011-01-07 20:37:24 -06:00
import re
2010-12-15 23:08:08 -06:00
import oauth2 as oauth
2011-01-07 20:37:24 -06:00
import urlparse
2010-12-15 23:08:08 -06:00
from extlib import irclib
from extlib import twitter
from Module import Module
class Twitter ( Module ) :
2011-01-19 19:44:04 -06:00
2011-01-07 20:37:24 -06:00
""" Access Twitter via the bot as an authenticated client. """
2010-12-15 23:08:08 -06:00
migrate some code that became pivotal to the bot into DrBotIRC.
this is a big change. DrBotIrc is now in charge of module loading
and unloading, aliases, and recursion. the Alias module is no more,
and a bunch of functionality was moved out of IrcAdmin, including
also config file saving, the sigint handler, and quitting the bot.
additionally, a lot of stuff got caught in the wake. dr.botzo.py
is simpler now, and lets DrBotIRC do the dynamic loading stuff.
Module.__init__ changed, modules no longer get modlist and instead
get a reference to the DrBotIRC object. IrcAdmin still has the same
exposed methods, but now calls out to DrBotIRC to achieve some of
them.
naturally, a recursion/alias rewrite was included with this change.
it is clearer now (i think), but probably brittle somewhere.
additionally, currently any module that has registered a pubmsg
handler can potentially fire more than once on one input (without
recursion). this may be the next thing to fix. do() may need to
be split, or maybe it's time to stop having modules deal with
pubmsg/privmsg entirely. need to decide.
WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
2011-01-07 17:38:26 -06:00
def __init__ ( self , irc , config , server ) :
2011-01-19 19:44:04 -06:00
""" Prepare for oauth stuff (but don ' t execute it yet). """
2011-01-07 20:37:24 -06:00
2011-01-19 19:44:04 -06:00
Module . __init__ ( self , irc , config , server )
2010-12-15 23:08:08 -06:00
2011-01-19 19:44:04 -06:00
# setup regexes
getstatuspattern = ' ^!twitter \ s+getstatus \ s+( \ S+)$ '
getuserstatuspattern = ' ^!twitter \ s+getuserstatus \ s+( \ S+)( \ s+.*|$) '
tweetpattern = ' ^!twitter \ s+tweet \ s+(.*) '
gettokenpattern = ' ^!twitter \ s+gettoken$ '
authpattern = ' ^!twitter \ s+auth \ s+( \ S+)$ '
2010-12-15 23:08:08 -06:00
2011-01-19 19:44:04 -06:00
self . getstatusre = re . compile ( getstatuspattern )
self . getuserstatusre = re . compile ( getuserstatuspattern )
self . tweetre = re . compile ( tweetpattern )
self . gettokenre = re . compile ( gettokenpattern )
self . authre = re . compile ( authpattern )
2010-12-15 23:08:08 -06:00
2011-01-19 19:44:04 -06:00
# prep oauth magic
2010-12-16 20:15:49 -06:00
self . consumer_key = ' N2aSGxBP8t3cCgWyF1B2Aw '
self . consumer_secret = ' 0aQPEV4K3MMpicfi2lDtCP5pvjsKaqIpfuWtsPzx8 '
2010-12-15 23:08:08 -06:00
2010-12-16 20:15:49 -06:00
self . request_token_url = ' https://api.twitter.com/oauth/request_token '
self . access_token_url = ' https://api.twitter.com/oauth/access_token '
self . authorize_url = ' https://api.twitter.com/oauth/authorize '
2010-12-15 23:08:08 -06:00
2010-12-16 20:15:49 -06:00
self . consumer = oauth . Consumer ( self . consumer_key , self . consumer_secret )
self . client = oauth . Client ( self . consumer )
2010-12-15 23:08:08 -06:00
2010-12-16 20:15:49 -06:00
# create a default twitter API account, in case we never auth
self . twit = twitter . Api ( )
2010-12-24 13:19:11 -06:00
self . authed = False
2010-12-15 23:08:08 -06:00
2011-01-07 23:09:07 -06:00
def do ( self , connection , event , nick , userhost , what , admin_unlocked ) :
2011-01-19 19:44:04 -06:00
""" Attempt to do twitter things. """
if self . getstatusre . search ( what ) :
return self . twitter_getstatus ( connection , event , nick , userhost , what , admin_unlocked )
elif self . getuserstatusre . search ( what ) :
return self . twitter_getuserstatus ( connection , event , nick , userhost , what , admin_unlocked )
elif self . tweetre . search ( what ) :
return self . twitter_tweet ( connection , event , nick , userhost , what , admin_unlocked )
elif self . gettokenre . search ( what ) :
return self . twitter_gettoken ( connection , event , nick , userhost , what , admin_unlocked )
elif self . authre . search ( what ) :
return self . twitter_auth ( connection , event , nick , userhost , what , admin_unlocked )
def twitter_getstatus ( self , connection , event , nick , userhost , what , admin_unlocked ) :
""" Get a status by tweet ID. """
match = self . getstatusre . search ( what )
2011-01-07 20:37:24 -06:00
if match :
status = match . group ( 1 )
try :
tweet = self . twit . GetStatus ( status )
2011-01-19 19:26:28 -06:00
return self . _return_tweet_or_retweet_text ( tweet = tweet , print_source = True )
2011-01-07 20:37:24 -06:00
except twitter . TwitterError as e :
2011-01-07 23:09:07 -06:00
return ' Couldn \' t obtain status: ' + str ( e )
2011-01-07 20:37:24 -06:00
2011-01-19 19:44:04 -06:00
def twitter_getuserstatus ( self , connection , event , nick , userhost , what , admin_unlocked ) :
""" Get a status for a user. Allows for getting one other than the most recent. """
match = self . getuserstatusre . search ( what )
2011-01-07 20:37:24 -06:00
if match :
user = match . group ( 1 )
index = match . group ( 2 )
if index :
index = int ( index )
if index > 0 :
2010-12-16 15:23:35 -06:00
index = 0
2011-01-07 20:37:24 -06:00
else :
index = 0
count = ( - 1 * index ) + 1
try :
tweets = self . twit . GetUserTimeline ( screen_name = user , count = count , include_rts = True )
if tweets :
tweet = tweets [ - 1 * index ]
2011-01-19 19:26:28 -06:00
return self . _return_tweet_or_retweet_text ( tweet = tweet )
2011-01-07 20:37:24 -06:00
except twitter . TwitterError as e :
2011-01-07 23:09:07 -06:00
return ' Couldn \' t obtain status: ' + str ( e )
2011-01-07 20:37:24 -06:00
2011-01-19 19:44:04 -06:00
def twitter_tweet ( self , connection , event , nick , userhost , what , admin_unlocked ) :
""" Tweet. Needs authentication. """
match = self . tweetre . search ( what )
2011-01-07 20:37:24 -06:00
if match :
tweet = match . group ( 1 )
if self . authed is False :
2011-01-07 23:09:07 -06:00
return ' You must be authenticated to tweet. '
2011-01-07 20:37:24 -06:00
if admin_unlocked is False :
2011-01-07 23:09:07 -06:00
return ' Only admins can tweet. '
2011-01-07 20:37:24 -06:00
try :
if self . twit . PostUpdates ( tweet , continuation = ' \xe2 \x80 \xa6 ' ) is not None :
2011-01-07 23:09:07 -06:00
return ' Tweet(s) sent. '
2011-01-07 20:37:24 -06:00
else :
2011-01-07 23:09:07 -06:00
return ' Unknown error sending tweet(s). '
2011-01-07 20:37:24 -06:00
except twitter . TwitterError as e :
2011-01-07 23:09:07 -06:00
return ' Couldn \' t tweet: ' + str ( e )
2011-01-07 20:37:24 -06:00
2011-01-19 19:44:04 -06:00
def twitter_gettoken ( self , connection , event , nick , userhost , what , admin_unlocked ) :
""" Get an oauth token, so that the user may authenticate the bot. """
match = self . gettokenre . search ( what )
2011-01-07 20:37:24 -06:00
if match :
# 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 ) )
# have the user auth
2011-01-07 23:09:07 -06:00
return ' 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 ' ] )
2011-01-07 20:37:24 -06:00
2011-01-19 19:44:04 -06:00
def twitter_auth ( self , connection , event , nick , userhost , what , admin_unlocked ) :
""" Authenticate, given a PIN (following gettoken). """
match = self . authre . search ( what )
2011-01-07 20:37:24 -06:00
if match :
authtoken = match . group ( 1 )
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
2011-01-07 23:09:07 -06:00
return ' The bot is now logged in. '
2010-12-15 23:08:08 -06:00
2011-01-19 19:26:28 -06:00
def _return_tweet_or_retweet_text ( self , tweet , print_source = False ) :
2010-12-16 13:04:58 -06:00
"""
Return a string of the author and text body of a status ,
accounting for whether or not the fetched status is a
retweet .
"""
if tweet . retweeted_status :
retweet = tweet . retweeted_status
2010-12-16 15:22:34 -06:00
if print_source :
2011-01-03 00:31:23 -06:00
return ' %s (RT %s ): %s [ %s ] ' % ( tweet . user . name . encode ( ' utf-8 ' , ' ignore ' ) , retweet . user . name . encode ( ' utf-8 ' , ' ignore ' ) , retweet . text . encode ( ' utf-8 ' , ' ignore ' ) , tweet . id )
2010-12-16 15:22:34 -06:00
else :
2011-01-03 00:31:23 -06:00
return ' (RT %s ): %s [ %s ] ' % ( retweet . user . name . encode ( ' utf-8 ' , ' ignore ' ) , retweet . text . encode ( ' utf-8 ' , ' ignore ' ) , tweet . id )
2010-12-16 13:04:58 -06:00
else :
2010-12-16 15:22:34 -06:00
if print_source :
2011-01-03 00:31:23 -06:00
return ' %s : %s [ %s ] ' % ( tweet . user . name . encode ( ' utf-8 ' , ' ignore ' ) , tweet . text . encode ( ' utf-8 ' , ' ignore ' ) , tweet . id )
2010-12-16 15:22:34 -06:00
else :
2011-01-03 00:31:23 -06:00
return ' %s [ %s ] ' % ( tweet . text . encode ( ' utf-8 ' , ' ignore ' ) , tweet . id )
2010-12-16 13:04:58 -06:00
2010-12-15 23:08:08 -06:00
# vi:tabstop=4:expandtab:autoindent
# kate: indent-mode python;indent-width 4;replace-tabs on;