Noob's Guide to Twython

Welcome to the third installment of The Noob’s Guide to Twython, where we’re playing around with the Twitter API with Python, using the Twython module. These tutorials are aimed at those who are perhaps learning to code for the first time, or have only a beginner’s knowledge of Python. If you’re looking for some advanced stuff, you’ve come to the wrong place!

So far, we’ve covered setting up your Twython for the first time and ReTweeting status updates based on search query using filters to keep out all that pesky noise!

But there’s nothing really interesting about a Twitter bot that does nothing but ReTweet things. In fact, it might even be a little bit boring. People like original content, or just a little something more that they can interact with. So why not have your bot automatically Tweet things as well as ReTweet things? You could even use this for promotions of a product or service or what have you. Of course you can schedule posts on a daily or weekly basis. But if you don’t want to be Tweeting anything from the bot account manually everyday…

Let’s make a Twython Twitter Bot!

So let’s take a quick gander at what we can expect to create, before we start dissecting it all up and going through what everything actual means! You might notice we’ve added two new things to import that weren’t in our previous bot. We’re now going to need to import time and random too.

#Importing time and random now!
from twython import Twython, TwythonError
import time
import random

app_key = "YOUR_APP_KEY"
app_secret = "YOUR_APP_SECRET"
oauth_token = "YOUR_OAUTH_TOKEN"
oauth_token_secret = "YOUR_OAUTH_TOKEN_SECRET"

twitter = Twython(app_key, app_secret, oauth_token, oauth_token_secret)

#Small list of Tweets to Tweet
list = [
    "Hello, I'm a Tweet.",
    "And I'm another!",
    "Yoohoo! I'm here too!",
    "We're all here together!",
    "Isn't Twitter so much fun =D",
    "(I think you get the idea by this point...)"
    ]

#This is called a while loop.
while True:
    try:
        if len(list) > 0:
            toTweet = list[random.randint(0,len(list))-1]
            twitter.update_status(status=toTweet)
            list.remove(toTweet)
            time.sleep(60)
        else:
#Oops! Our twitter.update_status should all be on one line!
            twitter.update_status(status="Oh dear... I'm afraid I'm rather empty =(")
            break
    except TwythonError as e:
        print e

Ready? Great! Let’s get started…

Creating a bunch of Tweets to Tweet!

First we’re going to need to create a list of Tweets that our Twitter Bot can choose from to Tweet. We can then just add new Tweets to our list whenever we want.

Lists in Python look a little something like this:

list = ["Something 1", "Something 2", "Something 3"]

 

Each Something is an item in our list, separated by a comma. And since it’s a string it’s enclosed in quotation marks. list is what they they’re all called together (which makes sense). We can also spread them across multiple lines, just so they’re easier to read. Like so:

list = [
    "Something 1",
    "Something 2",
    "Something 3"
    ]

 

Which might be easier if you have a dozen or so items in your list and want to be able to read them easily. So for this example, you can replace each Something with a Tweet. It can be an inspiring quote or message, or a promotion or whatever you want!

While Loops that Loop While Something

A while loop is like an if statement that repeats over and over again until something tells it to stop.

This whole block of code right here is our while loop:

#This is called a while loop.
while True:
    try:
        if len(list) > 0:
            toTweet = list[random.randint(0,len(list))-1]
            twitter.update_status(status=toTweet)
#Removal of the Tweet is optional
            list.remove(toTweet)
            time.sleep(60)
        else:
#Oops! twitter.update_status should all be on one line!
            twitter.update_status(status="Oh dear... I'm afraid I'm rather empty =(")
            break
    except TwythonError as e:
        print e

 

Basically we’re telling our bot that while True (which is always until we tell it it’s not), we want it to try grabbing a random item in our list and Tweeting it, then removing it from our list so it never gets Tweeted again, then pausing for a duration of time, before going through the process again. But ONLY if there’s something in our list to actually Tweet. If our list is empty, we want to update our Twitter status to say “Oh dear… I’m afraid I’m rather empty =(“, notifying us that we need to add more things to our list, before breaking out of the while loop and exiting the program completely.

FYI: The =( is supposed to be a sad face…

Pheww! That was a confusing explanation. I even confused myself. So let’s break it down even further…

if len(list) > 0:

 

That just means that if the length of list is more than 0 (i.e. if there is something in our list to be Tweeted), do the following. len means length, so to get the length of something we just put that something in the brackets!

toTweet = list[random.randint(0,len(list))-1]

 

Here we are setting a new variable called toTweet, which is going to stand for a random item our list. Remember we imported random earlier? It was like the first thing we did – this is why we needed it!

Notice how everything following list is enclosed in [square brackets]. Like how when we first created in our list, we inserted all our items between square brackets and separated them by a comma. To use a single item in our list, we need to call it by where it is in the index. The index starts from 0. So the first item in our list can be called using list[0].

So looking back at our example list earlier:

list = [
    "Something 1",    #This would be list[0]
    "Something 2",    #This would be list[1]
    "Something 3"     #This would be list[2]
    ]

 

But the problem with this is that we want to Tweet a random item from our list, so we can’t tell the bot where in the index to extract our Tweet from! This is where we use our random module…

Because we need an integer (a whole number) from our index – like list[1], 1 being the integer – we need to use randint (which means random integer) from our random module. Within the randint parameters, we need to specify between what number and what number do we want to select a random integer. So we set our parameters to (0,len(list)). Remember what len means? We’re telling our randint to randomly select an integer between 0 and the length of our list, since the length of our list is going to be dynamic and we can’t set it to a static number. We’re going to be adding and removing items from our list all the time, so we can’t state how many items are going to be in our list.

And the -1? What does that mean? Well, if you recall, the index of a list starts at 0. So list[1] isn’t actually the first item in our list but the second! Therefore, we need to add -1 so that the random integer we get acknowledges that the first item in our list starts at list[0]. Make sense?

twitter.status_update(status=toTweet)

Here we’re just telling Twitter to Tweet the random item from our list that we’ve grabbed!

Removing already Tweeted Tweets from our list

This is completely optional. If you want to repeat statuses, you might not want to remove it from the list. You might want it Tweeted again some time. But in case you don’t want your Twitter bot to be repeating itself, you’re going to want to remove it from our list of things to Tweet:

list.remove(toTweet)

The above bit of code tells our program to do just that. Once something’s been Tweeted, remove it from our list so it doesn’t get Tweeted again! If you have a small number of items in your list, it’s more likely that two duplicate Tweets might get Tweeted back-to-back. In which case, you might experience a 403 Error, which is like Twitter warning us that they’ve detected spam activity on our account because we’re trying to Tweet a duplicate status so soon after we posted the last one. So just be careful of that. We don’t want that to happen too many times…

Putting Twython to Sleep…

We obviously don’t want our bot to immediately go back to the start of the loop, and go through it again so soon. Our Twitter needs a rest, otherwise it’s going to just be spamming new Tweets one after another. (And we’re going to run out of things to Tweet pretty quickly…)

This is why we needed to import time into our Twitter bot. To give it a sense of time!

time.sleep(60)

 

What this tells our bot is that, from our time module, we would like to use the sleep function. And we would like to sleep for 60 seconds please!

In the wild, 60 seconds is actually far too short a duration. We certainly do not want our account to be Tweeting something new every minute. That’s a quick way of getting yourself thrown under the ban hammer.

In actuality, you’ll probably want your Twitter bot to nap for AT LEAST an hour or two. So for easy reference, there are 3600 seconds in an hour. So three hours would be 10800 seconds. You can work out the rest…

What if our list is empty?

Everything been removed from your list? Either you’ve been Tweeting too much or you haven’t been actively maintaining your list by adding new items! Either way, we need to tell our bot to stop trying to find random items in our list when we don’t have anything left in our list.

Earlier, we told our bot to only do those things if len(list) > 0. So now we need to tell our bot what to do if our list is empty.

else:
    twitter.update_status(status="Oh dear... I'm afraid I'm rather empty =(")
    break

 

We learnt this one in our first tutorial! Just a simple status update to tell us that we’ve run out of things to Tweet. Followed by a break. A break is exactly what it sounds like. You’re breaking out of the while loop, since there’s nothing left to do here…

Empty List Tweet

One more thing…

This program relies on it being run in the background the entire time. You close the program, it’s not going to keep Tweeting. You need to host the program somewhere and run it online if you want it to be running 24/7. But that’s a tutorial for another time. Also, if you were to use cron or Windows scheduler, you wouldn’t need to contain it in a while loop or tell the bot when to sleep. You could just simply schedule the program to run every three hours. But that again is a tutorial for another time!

The Final Product

It should look something like this:

from twython import Twython, TwythonError
import time
import random

app_key = "YOUR_APP_KEY"
app_secret = "YOUR_APP_SECRET"
oauth_token = "YOUR_OAUTH_TOKEN"
oauth_token_secret = "YOUR_OAUTH_TOKEN_SECRET"

twitter = Twython(app_key, app_secret, oauth_token, oauth_token_secret)

list = [
    "Hello, I'm a Tweet.",
    "And I'm another!",
    "Yoohoo! I'm here too!",
    "We're all here together!",
    "Isn't Twitter so much fun =D",
    "(I think you get the idea by this point...)"
    ]

while True:
    try:
        if len(list) > 0:
            toTweet = list[random.randint(0,len(list))-1]
            twitter.update_status(status=toTweet)
            list.remove(toTweet)
            time.sleep(60)
        else:
            twitter.update_status(status="Oh dear... I'm afraid I'm rather empty =(")
            break
    except TwythonError as e:
        print e

HOMEWORK:

Play around with ways to combine your ReTweet bot and your Random Tweet bot!

How To Get Going With TwythonThe Noob’s Guide to Twython – Part 2:

ReTweeting with your Twython Twitter Bot

The Noob’s Guide to Twython – Part 5:

Playing with Followers with Twython

4 Comments

  1. Hi Ria please let me know how i can do favorite tweets using search query and also let me know how i can repeat this sequence again again after sleeping my bot for 60 seconds

    1. Hi Nicole,

      If you check out the previous Twython tutorial on ReTweeting based on a search query, you can substitute RTing for Favoriting using:

      twitter.create_favorite(id = tweet[“id_str”])

      instead of:

      twitter.retweet(id = tweet[“id_str”])

      and you can use what you have learnt in this tutorial. like the time.sleep(60), to build a Favorite bot however you like.

      Hope that’s helped!

  2. hey, i want to combine both, RT and Fav. for that do I write seprate loops or can it be done in a single loop.
    For Ex:

    while True:
    try:
    for tweet in search_results["statuses"]:
    try:
    twitter.create_favorite(id = tweet["id_str"])
    twitter,retweet(id = tweet["id_str"])
    time.sleep(60)
    except TwythonError as e:
    print e
    except TwythonError as e:
    print e

    Will the above work or not