Tutorial: Twitter Bots

00

UPDATE 9/14: A few things have changed for setting up a Twitter application since this tutorial was written. The main change is you will need a phone number to register your app. Most of this guide should be fairly close to the current system, though the screenshots may look a bit different.

Creating Twitter bots, automated text-generators that spew spam, poetry, and other things, can be a bit of a confusing process. This tutorial will hopefully get you through the tough bits and make bot-building possible!

For this tutorial I will be using Python, a language whose simplicity and natural syntax is great for working with text. However, this tutorial should be easily portable to your language of choice. I assume you know at least enough programming to write your own algorithmic text; if you need some help, I would suggest one of the myriad resources including Learn X in Y Minutes. Finally, this post is written from a Mac user’s perspective – if you use another OS and have suggestions or required different steps, my apologies and let me know so I can add them.

If your programming is not up to snuff, you might consider using IFTTT to trigger a Tweet. While the range of possible text is much more limited, you can easily do things like post a Tweet when tomorrow’s weather is forecasted to be nice or you like a video on Vimeo! (You can also use this as a backup for storing your bot’s awesome Tweets.)

You can view the source files used here, screenshots, and other miscellany for this tutorial on GitHub.

Contents

  1. Create A Twitter Account
  2. Create An Email Address
  3. Complete Your Bot’s Profile
  4. Setup OAuth Access
  5. Allow Write-Access To Your Twitter Account
  6. Save OAuth Details
  7. Make Your Bot Write Something!
  8. Load OAuth Into Your Script
  9. Download And Install Twitter Library
  10. Connect To Twitter And Post!
  11. Test, Launch, And Celebrate
  12. Additional Resources

If you have any questions or suggestions, please post them in the comments!

01-web

Create A Twitter Account

First, create a Twitter account for your bot (easy!). I like to include the word “bot” in the account name if possible, so followers are clear the Tweets are generated, not written by a human. Of course, if the goal of your bot is confusing the two, then a more cryptic name might be better-suited.

You will need an email address for this step, so you may want to simultaneously check available usernames, quickly set up your email address (see step 2), then create your bot’s account.

02-web

Create An Email Address

Also easy: create an email address for your bot. If you have web hosting with the top hosting ranking agencies it likely includes a lot of email addresses (my basic hosting allows me to create up to 1200), or use a service like Gmail.

03-web

Complete Your Bot’s Profile

Style your bot’s page as desired. Just like the bot’s username, I generally make clear in the description that the Tweets are algorithmically-generated. Don’t forget a memorable profile image, too!

04-web

Setup OAuth Access

Ok, now for the part you probably haven’t done before. In order for your bot to auto-upload to Twitter, you need to set up OAuth, essentially a set of passwords for 3rd parties to access your account (this is how you can auto-Tweet when you like video on Vimeo, for example). Read more about the OAuth process here and here.

Head to dev.twitter.com and sign in using your bot account. Then click on the My Applications link as seen above.

05-web

You should have no applications for this account, so click the Create New Account button in the upper-right…

06-web

Give your application a name, a short description, and a link to your website – this is all just for your use, so don’t sweat the details too much.

07-web

Allow Write-Access To Your Twitter Account

Once filled out, your new app should appear with some details including the first two parts of the OAuth settings: consumer key and consumer secret. However, the default settings are read-only, which means we’re still missing the ability to use our application to post Tweets.

Click on the Settings tab…

08-web

Change access to “read, write, and access direct messages”, allowing us full access to the account. Save the settings.

09-web

Return to the Details tab – you should now have a Create access token button at the bottom. Click it to generate the other half of the OAuth settings. The page should refresh and you’ll see them appear like in the image below.

Note: sometimes this step is a little buggy. You might need to click the button once or twice, or re-select “Read, write…” in the Settings tab.

10-web

Save OAuth Details

Now we have the four parts needed for OAuth access:

  1. Consumer key (kind of a like a username for the app)
  2. Consumer secret (the matching password for the app)
  3. Access token (a sort of username for access to write to the account)
  4. Access token secret (the matching password to write)

Copy/paste the above details into a new text file in the following format:

… and save to a file called  OAuthSettings.py  (of course, replacing  xxxx  with your settings).

We’re using a separate file for security reasons: by keeping these details separate from our source code, we can share the bot’s source without fear of accidentally including the passwords!

Note: if releasing your bot’s code on GitHub, be sure to add  OAuthSettings.*  to your  gitignore  file.

Make Your Bot Write Something!

Create your bot’s basic code, without worrying about the Twitter side. This let’s you test your bot locally and work out the details. Just keep in mind the basic limitations of Twitter: 140 characters or less, and no text formatting like bold or italic (though Unicode characters and Emoji are likely supported for most users).

Here’s a simple example written in Python that creates little math problems – not very interesting as a bot but the code is easy to understand:

Test your code locally and tweak the results. For more complex text-generation, it may be helpful to use the  len()  command to test the length of your resulting Tweets.

Notice my final Tweet is stored in a variable called tweet . You can call it whatever you want, but you’ll need to remember it when you post your Tweet in a few steps.

Load OAuth Into Your Script

Once your bot’s inner workings are all set, we need to load the OAuth settings from the file we created earlier (named  OAuthSettings.py ) with a few extra lines of code. Put this line at the start of your script:

This loads the settings from the file into a Python dictionary, which can be accessed like this:

We’ll use these variables in the next step to connect to Twitter. Easy!

Download And Install Twitter Library

While we could create a connection to Twitter by writing all our own Python code, why re-invent the wheel? We’ll use Mike Taylor’s simple Twitter library, available at: https://github.com/bear/python-twitter. Save the library to your computer by clicking the Download Zip button, then run the following commands to install it:

This navigates to the directory that the Twitter library is saved (as a shortcut, type  cd  followed by a space, then drag the folder into the Terminal window instead of typing the full path).

Enter your password, hit Enter, and the library will be installed on your computer, along with any other required modules. If everything went well, test the installation by running the following commands:

If you don’t get an error, you’re all set to launch your bot!

Connect To Twitter And Post!

We can now load the Twitter library into our script, connect to Twitter using our OAuth credentials, and post a Tweet – nearly there! First, import the Twitter library (do this at the top of your script):

Then, later in your script (after you’ve generated the Tweet’s text) we connect to Twitter using the OAuth settings and post your Tweet. Since I called my Tweet’s string tweet  earlier, I use that here. If you used a different variable name, change the code below.

Notice that everything is wrapped in a  try/except  statement to catch any errors along the way. This gives us feedback if there’s a problem connecting or posting.

Test, Launch, and Celebrate

Now it’s time to test your bot by running your finished Python code. Just run the script the way you normally do and if all went well, you should see your new Tweet appear online immediately! Congrats!

11-web

You now have a few options on how to launch your bot:

  1. Run Locally
    Just run your bot when you feel like it, like we did above for testing.
  2. Schedule Automatic Posting
    For more automated and regular posting, try using Applescript or Cron (I use Cronnix, a free Cron-scheduling tool for Mac that makes the process a little easier). This can be set to run at regular intervals (for example, using Cron/Cronnix I can set the script to run every hour using 0 * * * *  or every 5 minutes using */5 * * * * . The downside to this method is it only works when your computer is on and connected to the internet.
  3. Dedicated Computer/Server
    If you’re building a lot of bots, you’ll want to consider running them on a dedicated computer or your web server. Since my web hosting isn’t set up for Python (and would cost extra), I’m currently using a Mac Mini in my studio that’s dedicated to chores like running bots, rendering video, etc.

Additional Resources

While there are a lot of possible extensions and tools that can make your bots even more special, here are a few that might be most helpful.

Other resources? Suggestions? Please leave them in the comments!

Did you find this post helpful or interesting? A small donation goes a long way towards helping produce this content. If you can't, please share what you've done with others!
Donate via Flattr

7 Replies to “Tutorial: Twitter Bots”

  1. Strictly speaking, this is not a robot at all. Just request APIs provided by twitter. If you have a real bot which can posts statuses to twitter + auto login + auto register with given emails, and most importantly, doing these thing without being detected and refused by twitter… That’s really great!

  2. I’m scared that using sudo will mess up my computer. It is not mine: It is my works even though I’m allowed to do anything on it.

  3. In this case, sudo is nothing to be afraid of! It’s required to install software (which is what the python command is doing here). Most commands run with sudo are ok, so long as you know what they’re doing – if you’re worried, you can always Google the command or type man for info on it.

Leave a Reply

Your email address will not be published. Required fields are marked *