#!/usr/bin/python3 # -*- coding: utf-8 -*- import tweepy from tweepy import OAuthHandler from tweepy import Stream from tweepy.streaming import StreamListener from auth import * from config import hashtags, white_kwds from db import LikeMemory import json import sys class StdOutListener(StreamListener): """A listener handles tweets are the received from the stream.""" def __init__(self, api, memory): """Build the Python object.""" super().__init__() self._api = api self._memory = memory self._white = [ s.lower() for s in white_kwds.split(' ') ] def get_status_info(self, data): """Parse status data to get information about its author and content.""" # Do not rely on https://dev.twitter.com/overview/api/tweets # as the specs seem outdated... sid = data['id'] username = data['user']['screen_name'] if 'extended_tweet' in data: content = data['extended_tweet']['full_text'] else: content = data['text'] content = content.replace('\n', '') return sid, username, content def on_data(self, data): """Receive Tweets matching the given hashtags.""" decoded = json.loads(data) if 'retweeted_status' in decoded: sid, username, content = self.get_status_info(decoded['retweeted_status']) else: sid, username, content = self.get_status_info(decoded) like = False words = content.split(' ') for kwd in self._white: for w in words: if w.lower() == kwd: like = True break if like: break if like: if self._memory.is_original_content(content): try: self._api.create_favorite(sid) self._memory.save_liked_status(sid, username, content) print('@%s: "%s" (id=%d)' % (username, content, sid)) print(' -> https://twitter.com/%s/status/%d' % (username, sid)) except tweepy.error.TweepError: pass else: print('Already seen "%s"' % content) else: print('Reject "%s"' % content) return True def on_error(self, code): """Handle errors.""" print('Error:', code) if code == 420: #returning False in on_data disconnects the stream return False if __name__ == '__main__': """Start of the script.""" auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) api = tweepy.API(auth) memory = LikeMemory(api) if len(sys.argv) > 1 and sys.argv[1] == '--purge': memory.purge_old_status() else: listener = StdOutListener(api, memory) stream = Stream(auth, listener) stream.filter(track=hashtags.split(' '))