We want to create a bot that will track specific topics and retweet them. We shall use the Twitter Streaming API to track topics. We will use the popular tweepy package to interact with Twitter.
Let’s first install Tweepy
1 |
pip install tweepy |
We need to create a Twitter app and get the tokens. We can do that from : https://apps.twitter.com/.
Now let’s see the codes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
from tweepy.streaming import StreamListener from tweepy import OAuthHandler, API from tweepy import Stream import json import logging import warnings from pprint import pprint warnings.filterwarnings("ignore") access_token = "4464294380-GHJ3PY...lEqzZ8FikULPnkxaS4huT" access_token_secret = "L033NEsDOA...tZVoaU8prpFbiREWhcVROw2" consumer_key = "D1G0bn...9Y88p" consumer_secret = "rGJjCU...FRISsiMURYlqCXJvOP" auth_handler = OAuthHandler(consumer_key, consumer_secret) auth_handler.set_access_token(access_token, access_token_secret) twitter_client = API(auth_handler) logging.getLogger("main").setLevel(logging.INFO) AVOID = ["monty", "leather", "skin", "bag", "blood", "bite"] class PyStreamListener(StreamListener): def on_data(self, data): tweet = json.loads(data) try: publish = True for word in AVOID: if word in tweet['text'].lower(): logging.info("SKIPPED FOR {}".format(word)) publish = False if tweet.get('lang') and tweet.get('lang') != 'en': publish = False if publish: twitter_client.retweet(tweet['id']) logging.debug("RT: {}".format(tweet['text'])) except Exception as ex: logging.error(ex) return True def on_error(self, status): print status if __name__ == '__main__': listener = PyStreamListener() stream = Stream(auth_handler, listener) stream.filter(track=['python', 'django', 'kivy', 'scrapy']) |
The code is pretty much self explanatory:
- We create a Twitter API client using the oAuth details we got earlier
- We subclass
StreamListener
to implement our ownon_data
method - We create an instance of this class, then create a new
Stream
by passing the auth handler and the listener - We use the
track
method to track a number of topics we are interested in - When we start to track the topics, it will pass the data to
on_data
method where we parse the tweet, check some common words to avoid, check language and then retweet it.