Noob Guide to Twython

Why would you want to code your own Twitter Bot?

There are so many websites that offer free Twitter bot services, with options to retweet a certain hashtag or mine certain Twitter data. Unfortunately, these ready made bots don’t typically allow for a lot of freedom or control. How many times have you seen a Twitter ReTweet Bot that tweets everything containing its designated #hashtag, including all of the distasteful Tweets that contain offensive language? Or bots ReTweeting completely irrelevant Tweets, though it contains the #hashtag, that really don’t need to be ReTweeted? These bots aren’t particularly designed well and can come across rather spammy. By programming a Twitter bot of your own, you can filter out the kinds of Tweets you don’t want, allowing you to Tweet, ReTweet and mine only the relevant Twitter data that you need. There are so many awesome marketing uses for a Twitter bot, and it all starts with learning what it is and how it works.

What is Twython?

To create a Twitter bot, you will need to create an app to connect with Twitter’s API. API stands for “Application Programming Interface”. The Twitter API is a designed way for external programs to interact with Twitter. It’s kind of like Twitter giving two people a tin can each attached by a long bit of string (but hopefully more effective). It gives both parties a way to communicate with each other – one party being us and the other of course being Twitter.

Twython is a pure Python wrapper for the Twitter API which means that you will have to download and install Python to get this thing running. This tutorial is going to assume that you’ve already installed Python and are familiar enough with it to at least be able to save and run programs.

There are a couple of other well known wrappers that do the same job, such as Tweepy or Python-Twitter, but it seems that Tweepy has long been abandoned by its owner and formed some kind of merge with Twython. Twython is currently accepted generally to be the best, as it is actively maintained and includes functions for everything you’re going to need. There’s decent community support as well with Twython which is great!

A working knowledge of the Python programming language is obviously recommended to do anything particularly original, but to be honest there’s so much support for Twython that just to make a simple Twitter bot, all you’ll really need is the Twython documentation, Google and a little bit of patience. And hopefully a splash of creativity.

Installing Twython

You can download the Twython library on GitHub here. You will need to install the Twython packages too, but you can do this via pip or easy_install. Python should already have easy_install built in, in which case try:

$ easy_install twython

 

or for pip:

$ pip install twython

 

Twitter OAuth

I’m not sure why but authenticating seemed to be the biggest initial challenge for me. I had to regenerate my API keys and access tokens three times before they eventually got working. I think maybe my own impatience was to blame there though, as when I changed the API permissions it may have taken a little extra time after regenerating my keys maybe?

It seems that a lot of the tutorials or blog posts that I read online about authenticating access to the Twitter API are outdated, and written back when you only needed to enter your Twitter username and password to gain access to the API. You will need OAuth now, as it has been for a while.

Twitter Apps

On your Twitter homepage, you should see the footer items as pictured above. You can either navigate from Twitter’s Developers pages on the off-chance you bump into anything that interests you along the way. Or… you could just go straight to apps.twitter.com and hit that Create New App button!

If you’re still navigating via the Twitter Developers Page, you’ll get there eventually. I’ll wait for you.

The Application Form is pretty straight-forward. Twitter holds your hand through it enough, without me holding your other hand through it too. (Because then how would you type?!)

Yes, you agree! Create your Twitter application!

First thing you’re going to want to do is modify your app permissions so that you are able to Read, Write and Access direct messages. This will allow your Twitter bot to actually be fully functional.

Twitter app permissions

On the API Keys tab you should see the:

  • API key – This is your key to get in.
  • API secret – This code right here has to be kept secret
  • Access level – This should now read “Read, Write and Access direct messages”.
  • Owner – This should say your Twitter username.
  • Owner ID  – This number here is your Twitter ID. Not important to you.

And if you scroll down a bit, you want to click “Generate my access token”! You need this to make API requests on your Twitter account”s behalf. You should see:

  • Access token
  • Access token secret
  • Access level
  • Owner
  • Owner ID

Aside from the token and token secret, the last three points should match the previous Application Settings.

The reason that we need so many codes to get started is that, in order to be able to Tweet, ReTweet, Follow, Unfollow and all that good stuff via our Twitter bot, we need to identify ourselves securely to access Twitter’s API. The app key and secret are like our app’s unique username and password, different to our Twitter profile username and password as we can have multiple apps per user. The token and token secret are like the app’s credentials, usable only by the app, and determines the app’s level of access on behalf of the user account at the discretion of the OAuth provider. Basically, it’s a secret handshake with four moves. Twitter needs to know that you know all four moves, or you can’t be part of the Twitter API Cool Club.

Secret Handshake

While you’re here, if you really want, you can change your Application Icon or Organisation Details. But you shouldn’t need it for the sort of Twitter Bot you’re probably going to want to be building.

Testing Twython with a Twitter Status Update

# Importing the module
from twython import Twython

#Setting these as variables will make them easier for future edits
app_key = "YOUR_APP_KEY"
app_secret = "YOUR_APP_SECRET"
oauth_token = "YOUR_OAUTH_TOKEN"
oauth_token_secret = "YOUR_OAUTH_TOKEN_SECRET"

#Prepare your twitter, you will need it for everything
twitter = Twython(app_key, app_secret, oauth_token, oauth_token_secret)
#The above should just be a single line, without the break

#The obligatory first status update to test
twitter.update_status(status="Hello world.")

Now try running your program and visit your Twitter profile. Has it appeared?

Twython Status Update

“But what good is this? I could have just updated my status myself!”

Next week I’ll be going through what kind of magic you can actually perform with your newly acquired wizardry!

ReTweeting with your Twython Twitter BotThe Noob’s Guide to Twython – Part 2:

ReTweeting with your Twython Twitter Bot

11 Comments

  1. Hello,

    I tried to run the program in the terminal using python Hola.py and have obtained the following errors:

    cristian@cristian-30:~/Escritorio/CODIGO$ python HolaMundo.py
    Traceback (most recent call last):
    File “HolaMundo.py”, line 15, in
    twitter.update_status(status=”Hello world.”)
    File “/usr/local/lib/python2.7/dist-packages/twython/endpoints.py”, line 107, in update_status
    return self.post(‘statuses/update’, params=params)
    File “/usr/local/lib/python2.7/dist-packages/twython/api.py”, line 267, in post
    return self.request(endpoint, ‘POST’, params=params, version=version)
    File “/usr/local/lib/python2.7/dist-packages/twython/api.py”, line 257, in request
    api_call=url)
    File “/usr/local/lib/python2.7/dist-packages/twython/api.py”, line 198, in _request
    retry_after=response.headers.get(‘X-Rate-Limit-Reset’))
    twython.exceptions.TwythonAuthError: Twitter API returned a 401 (Unauthorized), Could not authenticate you.

    Can you help me? Thanks.

    1. Have you made sure that your Twitter Application is set up properly with the correct access permissions, and that you are authorising correctly within your program? Also sometimes, if you have only just made the Twitter Application, it will not work immediately.

      Good luck!

  2. First of all Nice tut!
    But now i need your help.
    I tried to install easy_install on Raspbian but it says:
    pi@raspberrypi ~ $ sudo easy_install pip
    sudo: easy_install: command not found
    I already tried to install the python-setuptools but again an error. Missing Files. (i think it’s the right translation. My PI is on german :D )
    I hope you can help me.

    1. Hi, I’m no Linux expert (at all!) but I believe easy_install there would be the command that you’re trying to give it whereas you’re trying to install it. The same way that on Raspbian you would type “python mycode.py” to run mycode.py using Python – python being the command. If you are trying to install, I think you should be trying “sudo apt-get install python-setuptools”, “sudo apt-get install python-pip”, etc.
      Try in this order and see if you have any luck!:

      1. sudo apt-get install python-setuptools
      2. sudo easy_install pip
      3. sudo pip install twython

      Good luck and let me know if it works!! :)

      1. Thank you soooo much for the quick answer!
        Surprisingly it worked after i reinstalled Raspbian :D
        I installed Twython succesfully and i’ll try the Scripts soon. One more question: Is there a way to fav instead of RT the tweets you searched? And do i have to start the Programm again when I want to let the bot for example the RT script or can i do it with “while 1==1: …”?

        1. Hi Keiran,

          Glad to hear that you’ve got Twython working properly.

          To Fav instead of RT, you’ll want to:
          twitter.create_favorite(id = “TWEET_ID”)
          instead of:
          twitter.retweet(id = “TWEET_ID”)

          And yes, you can set up a while loop to repeat the program infinitely. Just don’t forget to add a time.sleep() so you don’t get any request errors! How long you want the program to sleep for is up to you before repeating again from the beginning is up to you. So you could time.sleep(60) or time.sleep(600), etc. It’s in seconds. For this you will have to import time at the beginning.

          Good luck!

          1. Thank you!
            Everything is working now but sometimes it says:

            Warning (from warnings module):
            File “/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py”, line 90
            InsecurePlatformWarning
            InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.

            Do you know how to fix it? It’s not interupting the script or anything. It’s just a little bit annoying with all the red in the “command” line :D

            (I’m sorry for my engish. I live in germany :’D )

          2. Ooh, I’m not sure about this. I have never come across it before, I’m afraid. Sorry that I can’t help you.\n\nAnd your English is brilliant, don’t worry :)

  3. Hello, there is allways this Error: “ImportError: No module named ‘twython'”.
    I try to install twython, but i doesnt manage it. How to do it?

    Greatings!

Leave a Reply