Showing posts with label Python Twitter. Show all posts

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.

Python Twitter tutorial - 5 steps to tweet a message from python script

In this tutorial, you will learn how to send tweets using Python. I will try to keep it as simple as possible. UPDATE: I wrote a similar Python tutorial for Facebook.

Step 1

  • You must add your mobile phone to your Twitter profile before creating an application.
  • Go to: Settings -> Add Phone -> Add number -> Confirm -> Save.
  • Do not forget to turn off all text notifications.

Step 2

  • Set up a new app
  • Go to: Twitter Apps -> Create New App -> Leave Callback URL empty -> Create your Twitter application.
  • You should see "Your application has been created. Please take a moment to review and adjust your application's settings".

Step 3

  • By default, app's access level is read-only. To send out tweets, it requires write permission.
  • Go to: Permissions tab -> What type of access does your application need? -> Choose Read and Write -> Update settings.
  • You should see "The permission settings have been successfully updated. It may take a moment for the changes to reflect."

Step 4

  • Time to get the keys and access tokens for OAuth.
  • Go to: Keys and Access Tokens tab . You'll see this under "Your Access Token" : You haven't authorized this application for your own account yet. By creating your access token here, you will have everything you need to make API calls right away. The access token generated will be assigned your application's current permission level.
  • Click Create my access token
  • You should see "Your application access token has been successfully generated. It may take a moment for changes you've made to reflect. Refresh if your changes are not yet indicated. This access token can be used to make API requests on your own account's behalf. Do not share your access token secret with anyone."
  • Verify that you see access token/secret - and the permission is set to "read and write".
  • From this page, note down the Access Token, Access Token Secret, Consumer Key (API Key), Consumer Secret (API Secret). Consumer Key/Secret help twitter identify the app and Access Token/Secret help twitter identify the user (that is you).

Step 5

  • We will use tweepy to access Twitter's API. You can install it using pip: pip install tweepy (try to setup a virtualenv for this - they are very useful).
Finally, this simple python script sends out a tweet:
import tweepy

def get_api(cfg):
  auth = tweepy.OAuthHandler(cfg['consumer_key'], cfg['consumer_secret'])
  auth.set_access_token(cfg['access_token'], cfg['access_token_secret'])
  return tweepy.API(auth)

def main():
  # Fill in the values noted in previous step here
  cfg = { 
    "consumer_key"        : "VALUE",
    "consumer_secret"     : "VALUE",
    "access_token"        : "VALUE",
    "access_token_secret" : "VALUE" 
    }

  api = get_api(cfg)
  tweet = "Hello, world!"
  status = api.update_status(status=tweet) 
  # Yes, tweet is called 'status' rather confusing

if __name__ == "__main__":
  main()