Building a basic Twitter bot

During my time as an intern for Montana Space Grant I was part of a nationwide project to live stream the 2017 solar eclipse. During that time we realized that it would be great to live tweet the photos that we received from out payload as we were receiving them. To achieve this I developed a twitter bot using python that would monitor a folder and live tweet any jpg or png files that were added. It was super simple and surprisingly fun to put together.

First thing first, we need a pair of consumer and consumer secret keys to build our program. Thankfully these are really easy to get, just follow these steps.

  1. Go here and log in if required.
  2. Fill out the required fields, accept the Terms of Service and solve the CAPTCHA.
  3. Submit the form.
  4. Navigate to the API keys tab.
  5. Copy the consumer and consumer secret keys.

Once we have these keys we want to create a python file that holds this information. To keep it the same call it credentials.py, however it can be whatever you would like as long as you adjust the main python program to match it. All you will enter is the following.

consumer_key = 'Your Consumer Key'
consumer_secret = 'Your Consumer Secret'
access_token = 'Your Access Token'
access_token_secret = 'Your Access Token Secret'

Now just save and exit that file. The only time you will need to interact with it again is if you would like to use a different twitter account.

Now that we have the foundation out of the way we can get started on the main program. First we need to import our libraries and our credentials from the other file.

import tweepy
import time
from credentials import *
import sys
from watchdog.events import PatternMatchingEventHandler
from watchdog.observers import Observer

Make sure the line ” from credentials import * ” matches the name of your python file from the previous step, ie if you named your file security.py it would change the line to be ” from security import * “. Once the files have been imported we need to authenticate with twitter. Thanks to the tweepy library this is pretty simple.

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

To monitor the folder we use the watchdog library. We can create a class that will watch for a set of predefined “patterns”. In this case we set it to watch for .jpg and .png file types. This would also be where you can define any text or hashtags that will be tweeted out with your image.

class MyHandler(PatternMatchingEventHandler):
    patterns = ["*.jpg", "*.png"]

    tweet = "Text"

    def process(self, event):
        print("Processing")
    def on_modified(self, event):
        self.process(event)
        print("File Modified")
    def on_created(self, event):
        self.process(event)
        api.update_with_media(event.src_path,tweet)

The final part of the bot is to let it run continuously to monitor the desired folder. This is done in main. We create an instance of observer, which is part of the watchdog library, and allow it to recursively run our handler which we created above.

if __name__ == '__main__':

    observer = Observer()
    #Modify path in following line of code to where the pictures will be stored.
    observer.schedule(MyHandler(), path='File Path', recursive = True)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()

    observer.join()

That’s it! Now you can just start your program and let it run! The full program can be seen on my github page here: EclipseTwitterBot