dr.botzo/modules/Twitter.py

128 lines
5.0 KiB
Python
Raw Normal View History

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/>.
"""
import urlparse
import oauth2 as oauth
from extlib import irclib
from extlib import twitter
from Module import Module
class Twitter(Module):
"""
Access Twitter via the bot as an authenticated client.
"""
def __init__(self, config, server, modlist):
"""
Prompt the user for oauth stuff when starting up.
TODO: make this optional, and have API calls log if they need auth.
"""
Module.__init__(self, config, server, modlist)
# begin oauth magic
consumer_key = 'N2aSGxBP8t3cCgWyF1B2Aw'
consumer_secret = '0aQPEV4K3MMpicfi2lDtCP5pvjsKaqIpfuWtsPzx8'
request_token_url = 'https://api.twitter.com/oauth/request_token'
access_token_url = 'https://api.twitter.com/oauth/access_token'
authorize_url = 'https://api.twitter.com/oauth/authorize'
consumer = oauth.Consumer(consumer_key, consumer_secret)
client = oauth.Client(consumer)
# get request token
resp, content = client.request(request_token_url, "GET")
if resp['status'] != '200':
raise Exception("Invalid response %s." % resp['status'])
request_token = dict(urlparse.parse_qsl(content))
# have the user auth
print('Go to the following link in your browser:')
print('%s?oauth_token=%s' % (authorize_url, request_token['oauth_token']))
# verify user auth
oauth_verifier = raw_input('Enter the PIN you are provided: ')
# request access token
token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret'])
token.set_verifier(oauth_verifier)
client = oauth.Client(consumer, token)
resp, content = client.request(access_token_url, "POST")
access_token = dict(urlparse.parse_qsl(content))
# finally, create the twitter API object
self.twit = twitter.Api(consumer_key, consumer_secret, access_token['oauth_token'], access_token['oauth_token_secret'])
def do(self, connection, event, nick, userhost, replypath, what, admin_unlocked):
"""
Attempt to do twitter things.
"""
whats = what.split(' ')
if whats[0] == 'twitter' and len(whats) >= 2:
if whats[1] == 'status' and len(whats) == 3:
try:
tweet = self.twit.GetStatus(whats[2])
return self.reply(connection, replypath, self.tweet_or_retweet_text(tweet=tweet, print_source=True))
2010-12-15 23:08:08 -06:00
except twitter.TwitterError as e:
return self.reply(connection, replypath, 'Couldn\'t obtain status: ' + str(e))
elif whats[1] == 'user' and len(whats) >= 3:
if len(whats) >= 4:
index = int(whats[3])
if index > 0:
index = 0
else:
index = 0
count = (-1*index) + 1
2010-12-15 23:31:26 -06:00
try:
tweets = self.twit.GetUserTimeline(screen_name=whats[2], count=count, include_rts=True)
if tweets:
tweet = tweets[-1*index]
return self.reply(connection, replypath, self.tweet_or_retweet_text(tweet=tweet))
2010-12-15 23:31:26 -06:00
except twitter.TwitterError as e:
return self.reply(connection, replypath, 'Couldn\'t obtain status: ' + str(e))
2010-12-15 23:08:08 -06:00
def tweet_or_retweet_text(self, tweet, print_source=False):
"""
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
if print_source:
return '%s (RT %s): %s' % (tweet.user.name.encode('utf-8', 'ignore'), retweet.user.name.encode('utf-8', 'ignore'), retweet.text.encode('utf-8', 'ignore'))
else:
return '(RT %s): %s' % (retweet.user.name.encode('utf-8', 'ignore'), retweet.text.encode('utf-8', 'ignore'))
else:
if print_source:
return '%s: %s' % (tweet.user.name.encode('utf-8', 'ignore'), tweet.text.encode('utf-8', 'ignore'))
else:
return '%s' % (tweet.text.encode('utf-8', 'ignore'))
2010-12-15 23:08:08 -06:00
# vi:tabstop=4:expandtab:autoindent
# kate: indent-mode python;indent-width 4;replace-tabs on;