Advertisement
ptrawt

AutoReplyTweet

May 30th, 2015
523
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.91 KB | None | 0 0
  1. import ConfigParser ,json ,tweepy
  2. from nltk.chat import eliza
  3.  
  4. config = ConfigParser.ConfigParser()
  5. config.read('.twitter')
  6.  
  7. consumer_key = config.get('apikey', 'key')
  8. consumer_secret = config.get('apikey', 'secret')
  9. access_token = config.get('token', 'token')
  10. access_token_secret = config.get('token', 'secret')
  11. account_user_id = config.get('app', 'account_user_id')
  12.  
  13. auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
  14. auth.secure = True
  15. auth.set_access_token(access_token, access_token_secret)
  16. twitterApi = tweepy.API(auth)
  17.  
  18. chatbot = eliza.Chat(eliza.pairs)
  19.  
  20. print 'Start'
  21.  
  22. class ReplyToTweet(tweepy.StreamListener):
  23.  
  24.     def on_data(self, data):
  25.         print data
  26.         tweet = json.loads(data.strip())
  27.        
  28.         retweeted = tweet.get('retweeted')
  29.         from_self = tweet.get('user',{}).get('id_str','') == account_user_id
  30.  
  31.         if retweeted is not None and not retweeted and not from_self:
  32.  
  33.             tweetId = tweet.get('id_str')
  34.             screenName = tweet.get('user',{}).get('screen_name')
  35.             tweetText = tweet.get('text')
  36.  
  37.             chatResponse = chatbot.respond(tweetText)
  38.  
  39.             replyText = '@' + screenName + ' ' + chatResponse
  40.  
  41.             #check if repsonse is over 140 char
  42.             if len(replyText) > 140:
  43.                 replyText = replyText[0:137] + '...'
  44.  
  45.             print('Tweet ID: ' + tweetId)
  46.             print('From: ' + screenName)
  47.             print('Tweet Text: ' + tweetText)
  48.             print('Reply Text: ' + replyText)
  49.  
  50.             # If rate limited, the status posts should be queued up and sent on an interval
  51.             twitterApi.update_status(status=replyText, in_reply_to_status_id=tweetId)
  52.  
  53.     def on_error(self, status):
  54.         print status
  55.  
  56.  
  57. if __name__ == '__main__':
  58.     streamListener = ReplyToTweet()
  59.     twitterStream = tweepy.Stream(auth, streamListener)
  60.     twitterStream.userstream(_with='user')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement