How To Write a Twitter Bot with Python and tweepy

How To Write a Twitter Bot with Python and tweepy

Twitter is the social media site for robots. You probably have robot friends and followers and don’t even realize it! In this tutorial, you will write your own Twitter bot with Python and tweepy, and then set it loose in the world.

First we need to create a Twitter Application. Go to https://dev.twitter.com/ and log in with your Twitter account.

Creating a new Twitter Application

Under your account toggle, select ‘My applications’. On the following screen, select the option to create a new application and fill in the required information.

Settings tab in Twitter Application

Once your new application is created, select its Settings tab and towards the bottom of the page click the ‘Read and Write’ radio button. Return to the Details tab and click the big blue button at the bottom of the page to generate your access keys.

Next, we need to install tweepy. tweepy is the library we will be using to access the Twitter API with Python. From the command line, run:

If you don’t have pip installed, run:

Now it’s time to make our robot. Open your favorite text editor or IDE and create a new file (don’t use a word processor; it will load your file with unnecessary junk). Save it as helloworld.py

Below is our complete code. Enter your Twitter application keys and tokens accordingly:

That’s our robot. But it’s hungry. Let’s feed it! Create a new text file in the same directory as helloworld.py. Save it as helloworld.txt. Enter a few memorable lines, such as:

Hello World!
I’m a robot!
Robots are superior to humans in every conceivable way!

Be sure to use lots of exclamation points so your robot can be heard. Twitter is a noisy place. Also be sure there are no blank lines in-between your lines of text. Our robot is not an existentialist.

Now we’re ready to go! At the command line enter:

Check your Twitter feed and you should see:

Hello World!

Let’s break that down into byte sized pieces.

Our first line of Python,

includes the three packages we need for our program: tweepy, time & sys. We already know what tweepy is for. time will allow us to schedule intervals between our Tweets (so we don’t get in trouble with Twitter), and sys will allow us to feed our robot a file for it to read and Tweet.

The next line is how we feed the file to our robot.

We’re assigning our text file to argfile. No, not arg as in the sound a pirate makes, but arg as in short for argument. When we run our program from the command line, we are passing the python interpreter two arguments, the first argument, argv[0], is our .py file, helloworld.py; the second argument, argv[1], is our text file, helloworld.txt. What we are saying here is that argfile contains the string,¬†helloworld.txt.

The next big chunk of code is how we connect our robot to Twitter through our Application:

Here we are creating a variable, auth, and via tweepy, we are authorizing our account with our consumer and access keys. We then create a variable, api, and via tweepy connect to the Twitter API with auth.

After that, we open and read the helloworld.txt file:

Here we’re using the open() function to read argfile, which you will recall is holding the string¬†helloworld.txt. We read the file with the parameter, ‘r’, for read. Next we read the lines of our file and pass them to a variable called f, for file. Finally, we close the file. Closing something you’ve opened is a good habit. Like the refrigerator.

The last block of code is where the magic happens:

Using a for loop, we iterate through every line stored in f. For each line, we send out a Tweet using api.update_status(line). Then we tell our robot to snooze with time.sleep(900). The for loop will continue until it reads and Tweets the last line in f(or finds an error in your file), and will then exit.

That’s it! Keep in mind there are best practices to be followed on Twitter. You will want to check before you modify this code or you risk getting your account suspended. And that’s no fun for you or your robot.

Special thanks to robincamille for writing the post that inspired this tutorial.

Learn With Us

We want to take you on a journey through the other side of the creative process: making a living. Explore the necessary evils of business as we develop a creative media studio using free and open source software. Sign up for our New Moon newsletter delivered on, you guessed it, every New Moon.

Become a GNU/Linux Superuser!

Master the commands and structure of the fastest-growing computer operating system, Linux. Join super friends Adelie the penguin and Aramis the gnu on surreal adventures saving files in the file tree. Learn the essential commands you need to take greater control of your computer including help, cd, pwd, ls, mkdir, rmdir, cp, mv, rm, cat, and man.

Get It Now!
About the Author

How To Write a Twitter Bot with Python and tweepy was posted by on . Jared is one half of the creative force behind Dototot. In addition to writing scripts and tutorials, he draws and animates both the digital and the analog.

Discuss this article in the Comments below, or and it with your friends. Learn more about , , and our creative process by subscribing to the New Moon Newsletter .

Recommended for you
Join the discussion
  • Joseph Daniel

    Was quite helpful thank you! ^.^

  • Anon.

    thank you, really thank you !!!

  • Ari Warren

    I’m getting an error when I try to run this. It gives me NameError: name ‘tweepy’ is not defined. When I execute “import tweepy” it doesn’t give any error. Do you know why it might be giving this error?

  • Nash

    Hello Guys I need a Help last 3days i have try to work this out but i couldnt, i dont have no idea what els to do.. please any one help me weith this AIP. Thank you so much…

    root@Nash00:~/Desktop/robot# python helloworld.py helloworld.txt
    Traceback (most recent call last):
    File “helloworld.py”, line 23, in
    api.update_status(line)
    File “build/bdist.linux-x86_64/egg/tweepy/binder.py”, line 138, in _call
    tweepy.error.TweepError: Twitter error response: status code = 301

  • Juan Pablo Moreno G

    Hi my name is Juan Pablo I’m from Venezuela I have a question. I really read your tutorials about How To Write a Twitter Bot with Python and tweepy (“http://www.dototot.com/how-to-write-a-twitter-bot-with-python-and-tweepy/”), so i ask can you guys help me. I want to know if one of my tweet was retweeted, and Who retweeted??? Can you help me? Sorry for my english. Thankyou

  • Juan Pablo Moreno G

    I used
    for retweet in api.retweeted_to_me():
    print ‘–>’, retweet.author.screen_name, ‘:’ ,retweet.text, ‘n’
    but i got this error
    AttributeError: ‘API’ object has no attribute ‘retweeted_to_me’
    I’m using python2.6
    # Tweepy
    # Copyright 2009-2010 Joshua Roesslein

    Thank you if you can help me!!

  • I had the same error. You probably use an old version of Tweepy using API v1.0 instead of v1.1.

  • Looney

    I got the same problem from Nash, To fix it. i used tweepy 2.3.0 instead of the latest version and python 2.7.
    No problems now :)

  • Mary

    This is great! My first bot! Thanks for the terrific tutorial :) Hmmm… if my computer goes to sleep does that mean it will not tweet out? (I set it to tweet 8 times a day instead of every 15 minutes). https://twitter.com/BletchleyRoll <–tweets women who served at Bletchley Park.

  • Patrick Vos

    Thank you for this tutorial.

    Just to note. When using a newer tweepy version, the helloworld.py example doesn’t work anymore.
    Tweety added a variable to the update_status function. In L22 api.update_status(line), line gets assigned to a different variable now resulting in: tweepy.error.TweepError: [{u’message’: u’media_ids parameter is invalid.’, u’code’: 44}].

    Assigning line to the right parameter solves this.
    api.update_status(status=line)

    Because dev.twitter didn’t give me the shown screens, I used https://apps.twitter.com/ instead

  • dototot

    Hi Patrick,
    Thanks for the note. This tutorial was written way back in 2013! It’s due for an update as a lot has changed with Twitter and Tweepy. Now to find the time…
    Cheers!

  • Rose

    I have checked my code it seems to be correct (I did substitute the line api.update_status(status=line) instead of api.update_status(line) which I believe is the correct version.

    I am trying to get used to the command line so I typed in:

    python helloworld.py helloworld.txt

    I am returned

    >>> python helloworld.py helloworld.txt
    File “”, line 1
    python helloworld.py helloworld.txt
    ^
    SyntaxError: invalid syntax

    I do not really understand why? I mean it’s the right file name and I followed the tutorial and from my understand it just means in python run the robot program and the txt file. Does anyone have suggestions?

  • dototot

    Hi Rose,
    What operating system are you using? Do you have Python on your PATH? Did you import the sys module? Like this:

    import tweepy, time, sys

  • Rose

    I think Python is on my PATH. I have made other python/twitter projects in this folder and they worked.
    I did import my program looks like this right now. I use windows 7 and I use Anaconda+Spider for programming in python (because that’s what everyone else in my department does).

    Thank you.

  • Daniel

    hi, i get exactly the same error message as you, but with this code:

    import tweepy

    CONSUMER_KEY = ‘abc’

    CONSUMER_SECRET = ‘abc’

    ACCESS_KEY = ‘abc’

    ACCESS_SECRET = ‘abc’

    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)

    auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)

    api = tweepy.API(auth)

    api.update_status(‘test’)

    do you see what’s going wrong?

  • Patrick Vos

    Try changing lastline to:

    api.update_status(status=’test’)

  • zys

    thanks it works

  • JohnMorocco

    Hi all, you should put : api.update_status(status=line) instead of api.update_status(line).

    Then it will work.

  • mohit

    Try changing lastline to: api.update_status(status=line)

    Worked for me.Thanks a lot for this tutorial.

  • Aleksandar Petrovic

    Tnx man

  • delprofundo

    thank you Patrick! great update saved me hours!

  • Kelsey Wilkerson

    Does anyone have any idea why mine says “command not found” and “no such file or directory” when I enter the .txt and .py files? I followed directions precisely and even made the corrections mentioned in comments. Thanks in advanced!

  • Can you provide more information? What OS are you using? Do you have Python and Tweepy installed? Are you running the command from the same directory as the .txt file?

  • Kelsey Wilkerson

    Im using OS X Yosemite. Yes, I installed Python and Tweepy. Im not sure if I am running the command from the same directory as the .txt file. How do I make sure I am doing that correctly? Im sorry Im very new at this, but I greatly appreciate the help!

  • How comfortable are you with Terminal and the command line? You will need to change directory(cd) within Terminal to the location where you saved your .py and .txt files. Say, for example you saved them on your desktop:

    cd Desktop

    Then run the command.

    Alternatively, you can specify the path to the files. For example:

    python /home/yourname/Desktop/helloworld.py /home/yourname/Desktop/helloworld.txt

    You can use Finder to see the full path to your files.

    Give that a try, and if it’s not the issue, we’ll do some more troubleshooting. See also: http://www.thehelloworldprogram.com/linux/cd-change-directory/

  • Kelsey Wilkerson

    I don’t have any experience using the terminal and command line. I’ve been trying to teach myself so thank you for the video! It was very helpful and enjoyable. I put the files onto my desk top then changed directory to the desktop. I figured that would be the easiest. It seemed like it started to work because it detected my accesses key from my .py file but it still gave a weird error response:

    SyntaxError: EOL while scanning string literal

    I feel like there may be something wrong with how I am doing the .txt? Thank you for responding by the way. I greatly appreciate it!

  • Tweepi don’t work like it used to guys. Slow your roll when creating it now because it does limit the unfollowers

  • Carlos Lorenz Filho

    I am getting the following error:

    Traceback (most recent call last):

    File “python-twitter.py”, line 22, in

    api.update_status(status=line)

    File “/usr/local/lib/python2.7/dist-packages/tweepy/api.py”, line 193, in update_status

    )(post_data=post_data, *args, **kwargs)

    File “/usr/local/lib/python2.7/dist-packages/tweepy/binder.py”, line 243, in _call

    return method.execute()

    File “/usr/local/lib/python2.7/dist-packages/tweepy/binder.py”, line 189, in execute

    raise TweepError(‘Failed to send request: %s’ % e)

    tweepy.error.TweepError: Failed to send request: ‘_socketobject’ object has no attribute ‘set_tlsext_host_name’

    DO YOU THINK YOU CAN HELP?

  • Hi Carlos,
    What OS are you using? Is Python on your path? Are you using 2.7 or 3? And are you using the newest version of Tweepy?

  • Logan

    what if I want to write a code that returns True if and only if the word limit is between 1 to 140 words of a potential tweet and return False otherwise?

    def is_valid_tweet():
    I dont know what to write further to make python read a given sentence

  • Amy Ireland

    Hey there, I’m getting a syntax error on line 9 (CONSUMER_KEY = ‘abc’) when I run helloworld.py … can’t figure out what I’m doing wrong. Anyone got any suggestions?

  • Nambona890

    Traceback (most recent call last):
    File “thing.py”, line 22, in
    api.update_status(status=line)
    File “C:UsersZanderAppDataLocalProgramsPythonPython35-32libsite-packa
    gestweepyapi.py”, line 194, in update_status
    )(post_data=post_data, *args, **kwargs)
    File “C:UsersZanderAppDataLocalProgramsPythonPython35-32libsite-packa
    gestweepybinder.py”, line 245, in _call
    return method.execute()
    File “C:UsersZanderAppDataLocalProgramsPythonPython35-32libsite-packa
    gestweepybinder.py”, line 229, in execute
    raise TweepError(error_msg, resp, api_code=api_error_code)
    tweepy.error.TweepError: [{‘message’: ‘Could not authenticate you.’, ‘code’: 32}
    ]

    Does anyone know what is going on? I’ve done all the steps, but I think something screwed up with some new Tweepy update or something.

  • Bill Cipher

    Everything except for the for loop worked for me… It did not update with the new tweet after 15 mins. Thanks for the post though very informative. Also what is the coding: utf-8 for? I was assuming it’s so you don’t have creds hard coded into the program but you commented them out.

  • Moritz

    I get following error:

    Traceback (most recent call last):
    File “perlenbot.py”, line 26, in
    api.update_status(status=line)
    File “build/bdist.linux-armv7l/egg/tweepy/binder.py”, line 225, in _call
    File “build/bdist.linux-armv7l/egg/tweepy/binder.py”, line 180, in execute
    tweepy.error.TweepError: Failed to send request: – [Errno 111] Connection refused

    Somebody knows what is wrong?

  • morit

    I get following error:

    Traceback (most recent call last):
    File “perlenbot.py”, line 26, in
    api.update_status(status=line)
    File “build/bdist.linux-armv7l/egg/tweepy/binder.py”, line 225, in _call
    File “build/bdist.linux-armv7l/egg/tweepy/binder.py”, line 180, in execute
    tweepy.error.TweepError: Failed to send request: – [Errno 111] Connection refused

    somebody knows whats wrong?

  • Souveek Pal

    Hi all!

    I realize that is quite old tutorial.. I am a python novice and while I am learning python in school, the idea of being able to send a tweet using a python script is really enticing.

    I am using Python 2.7 on Windows 7 OS

    I get the following error :

    TweepError(error_msg, resp, api_code=api_error_code) tweepy.error.TweepError: [{u’message’:u’Could not authenticate you.’, u’code’:32}]

  • Hatep198

    Some educational institutes are also developing their logos in order to create the uniqueness in educational competitions, they also deliver what they claim and get highest attentions to the people regarding the admission of their kids.

  • Thomas D Martino

    hey guys, i keep getting the following messages…. any help??

    thomasmartino$ python helloworld.py helloworld.txt
    Traceback (most recent call last):
    File “helloworld.py”, line 39, in
    api.update_status(status=line)
    File “/Users/thomasmartino/Dev/anaconda/lib/python3.5/site-packages/tweepy/api.py”, line 194, in update_status
    )(post_data=post_data, *args, **kwargs)
    File “/Users/thomasmartino/Dev/anaconda/lib/python3.5/site-packages/tweepy/binder.py”, line 245, in _call
    return method.execute()
    File “/Users/thomasmartino/Dev/anaconda/lib/python3.5/site-packages/tweepy/binder.py”, line 229, in execute
    raise TweepError(error_msg, resp, api_code=api_error_code)
    tweepy.error.TweepError: [{‘code’: 215, ‘message’: ‘Bad Authentication data.’}]

  • Alemx Gammer

    Hi!
    Can I change text to images?
    I like post random images

  • Alemx Gammer

    The access code dont work

Subscribe to our New Moon Newsletter

How do you make money doing what you love? Sign up for monthly emails exploring the necessary evils of business as we develop a creative media studio using free and open source software.

The email entered is invalid
×