Skip to content

Instantly share code, notes, and snippets.

@guerrerocarlos
Created June 13, 2013 02:50
Show Gist options
  • Save guerrerocarlos/5770900 to your computer and use it in GitHub Desktop.
Save guerrerocarlos/5770900 to your computer and use it in GitHub Desktop.
from twython import Twython
import tweetstream
import sys
import os
#Credentials needed to access Twitter public Stream
stream_user = "PUT_TWITTER_USER_HERE"
stream_passwd = "PUT_TWITTER_USER_PASSWORD_HERE"
#Keys for Robot to be able to act as a Twitter App
app_key = "TWITTER_APP_KEY_HERE"
app_secret = "TWITTER_APP_SECRET_HERE"
class TwitterRobot(object):
def __init__(self):
"""
Initialization needed to Setup and Load
User Account to be used to send tweets
"""
try:
config = open('robot_credentials.conf','r')
self.auth_tokens = eval(config.readline())
print "[Robot]: Saved Credentials have been loaded"
except IOError:
print "INITIAL SETUP:\n==============\n"
t = Twython(app_key, app_secret)
auth_props = t.get_authentication_tokens()
oauth_token = auth_props['oauth_token']
oauth_token_secret = auth_props['oauth_token_secret']
print 'Please open this URL on your browser: %s' % auth_props['auth_url']
oauth_verifier = raw_input('log in with your Twitter account, click "Authorize App" and enter the resulting code in here:')
print "Checking credentials..."
t = Twython(app_key, app_secret, oauth_token, oauth_token_secret)
self.auth_tokens = t.get_authorized_tokens(oauth_verifier)
config = open('robot_credentials.conf','w')
config.write(str(self.auth_tokens))
print "Saving Credentials"
try:
oauth_token = self.auth_tokens['oauth_token']
oauth_token_secret = self.auth_tokens['oauth_token_secret']
self.t = Twython(app_key, app_secret, oauth_token, oauth_token_secret)
except KeyError:
print "There seems to be a problem, please try running this script again."
os.remove("robot_credentials.conf")
sys.exit(0)
def get_timeline(self):
""" Returns twitter account timeline """
return self.t.get_home_timeline()
def send_message(self,text):
""" Sends text as twitter account tweet """
self.t.update_status(status=text)
def username(self):
""" Returns Robot Credentials username """
return self.auth_tokens['screen_name']
if __name__=="__main__":
Robot = TwitterRobot()
stream = tweetstream.FilterStream(stream_user ,stream_passwd ,track=['OpenERP','ERP'])
print "Starting robot "+Robot.username()+"..."
for tweet in stream:
try:
adicional = "|| tweet %d " %(stream.count)
texto = tweet['user']['screen_name'] + "||" + tweet['text'] + adicional
print texto
if cmp(tweet['user']['screen_name'],Robot.username()) !=0:
text = '@'+tweet['user']['screen_name']+" have you tried OpenERP? Did you like it?"
print "Enviando: "+text
Robot.send_message(text)
except:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment