In this commodity, you'll learn how to make your own Twitter Bot in Python with Tweepy, a package that provides a very user-friendly way to utilise the Twitter API.

Twitter is one of the nigh widely used social networks. For many organizations and people, having a peachy Twitter presence is a key factor to keeping their audition engaged.

Function of having a great Twitter presence involves keeping your account agile with new tweets and retweets, following interesting accounts, and quickly replying to your followers' messages. Y'all tin do all this work manually, but that can accept a lot of time. Instead, y'all can rely on a Twitter Bot, a program that automates all or part of your Twitter activity.

In this article, y'all'll learn how to:

  • Better and automate your interactions with your Twitter audition
  • Install Tweepy
  • Sign upwardly as a Twitter developer to use its API
  • Use Tweepy to invoke the Twitter API
  • Build Twitter Bots
  • Deploy the bots to a server using Docker and AWS

Howdy Tweepy

To commencement, hither'southward how you lot tin can use Tweepy to create a tweet saying Hello Tweepy:

                                            import                tweepy                # Cosign to Twitter                auth                =                tweepy                .                OAuthHandler                (                "CONSUMER_KEY"                ,                "CONSUMER_SECRET"                )                auth                .                set_access_token                (                "ACCESS_TOKEN"                ,                "ACCESS_TOKEN_SECRET"                )                # Create API object                api                =                tweepy                .                API                (                auth                )                # Create a tweet                api                .                update_status                (                "Hello Tweepy"                )                          

This is a short instance, merely it shows the four steps common to all Tweepy programs:

  1. Import the tweepy package
  2. Set the authentication credentials
  3. Create a new tweepy.API object
  4. Use the api object to call the Twitter API

Objects belonging to the tweepy.API course offering a vast set of methods that y'all can utilise to access almost all Twitter functionality. In the code snippet, we used update_status() to create a new Tweet.

Nosotros will encounter subsequently in this article how the authentication works and how you lot can create the required hallmark cardinal, token, and secrets.

This is just a little example of what you can do with Tweepy. Through this article, you'll learn how to build programs that interact with Twitter in much more than interesting and complex ways.

Twitter API

The Twitter API gives developers admission to virtually of Twitter'southward functionality. Yous can use the API to read and write data related to Twitter entities such as tweets, users, and trends.

Technically, the API exposes dozens of HTTP endpoints related to:

  • Tweets
  • Retweets
  • Likes
  • Direct messages
  • Favorites
  • Trends
  • Media

Tweepy, as we'll run across after, provides a way to invoke those HTTP endpoints without dealing with low-level details.

The Twitter API uses OAuth, a widely used open authorization protocol, to authenticate all the requests. Earlier making whatever call to the Twitter API, you lot need to create and configure your authentication credentials. Later in this commodity, you'll find detailed instructions for this.

Y'all can leverage the Twitter API to build different kinds of automations, such as bots, analytics, and other tools. Keep in mind that Twitter imposes certain restrictions and policies virtually what you can and cannot build using its API. This is washed to guarantee users a good feel. The evolution of tools to spam, mislead users, and so on is forbidden.

The Twitter API also imposes rate limits about how frequently you're allowed to invoke API methods. If yous exceed these limits, you'll have to wait between 5 and fifteen minutes to be able to utilize the API again. You must consider this while designing and implementing bots to avoid unnecessary waits.

You can detect more data about the Twitter API's policies and limits in its official documentation:

  • Twitter Automation
  • Rate limits

What Is Tweepy?

Tweepy is an open source Python package that gives you a very convenient way to admission the Twitter API with Python. Tweepy includes a set of classes and methods that represent Twitter's models and API endpoints, and it transparently handles various implementation details, such equally:

  • Data encoding and decoding
  • HTTP requests
  • Results pagination
  • OAuth authentication
  • Rate limits
  • Streams

If you weren't using Tweepy, then you would accept to deal with low-level details having to do with HTTP requests, information serialization, authentication, and rate limits. This could be time consuming and prone to error. Instead, thank you to Tweepy, you tin focus on the functionality you want to build.

Almost all the functionality provided by Twitter API can exist used through Tweepy. The only current limitation, every bit of version 3.7.0, is that Directly Letters don't work properly due to some contempo changes in the Twitter API.

Using Tweepy

In this section, you'll acquire how to install Tweepy for development, configure hallmark credentials, and interact with the Twitter API.

Installation

Tweepy can be installed using pip, a Python package manager. In this article, we're going to use a virtual environment (virtualenv) for the projects to avert depending on system-broad packages. For more than information on virtual environments and pip, check out Python Virtual Environments: A Primer and What Is Pip? A Guide for New Pythonistas.

Yous tin can get started past creating a project called tweepy-bots. The starting time step is to create a directory and a virtual surroundings:

                                                  $                  mkdir tweepy-bots                  $                                    cd                  tweepy-bots                  $                  python3 -thou venv venv                              

The commands in a higher place create the virtual environment inside the project directory.

Then you can install the Tweepy package. First, you lot need to activate the newly created virtual environment and and then apply pip to do the installation:

                                                  $                                    source                  ./venv/bin/activate                  $                  pip install tweepy                              

Now that Tweepy is installed, let's create a requirements.txt file containing the names of your dependencies. You tin apply the pip command freeze for this job:

                                                  $                  pip freeze > requirements.txt                              

You'll use this requirements.txt file when you're deploying the project.

Creating Twitter API Hallmark Credentials

Every bit nosotros have previously seen, the Twitter API requires that all requests use OAuth to authenticate. So you need to create the required hallmark credentials to be able to use the API. These credentials are four text strings:

  1. Consumer fundamental
  2. Consumer secret
  3. Admission token
  4. Access secret

If you lot already take a Twitter user account, then follow these steps to create the key, token, and secrets. Otherwise, you have to sign upwards as a Twitter user before proceeding.

Step ane: Apply for a Twitter Developer Account

Go to the Twitter developer site to apply for a developer account. Here, you have to select the Twitter user responsible for this account. It should probably be you lot or your organization. Here's what this page looks similar:

Apply for a developer account

In this case, I chose to use my own account, @MikezGarcia.

Twitter then requests some information about how you plan to utilize the developer account, as showed below:

Complete account information

Yous have to specify the developer business relationship name and whether you are planning to utilise it for personal purpose or for your organization.

Step ii: Create an Awarding

Twitter grants hallmark credentials to apps, non accounts. An app can be any tool or bot that uses the Twitter API. So y'all need to register your an app to be able to brand API calls.

To register your app, go to your Twitter apps folio and select the Create an app choice.

Yous need to provide the post-obit information well-nigh your app and its purpose:

  • App name: a name to place your application (such as examplebot)
  • Awarding description: the purpose of your application (such as An example bot for a Real Python article)
  • Your or your awarding'southward website URL: required, but can exist your personal site's URL since bots don't need a URL to work
  • Utilise of the app: how users will use your app (such as This app is a bot that volition automatically respond to users)

Step 3: Create the Hallmark Credentials

To create the authentication credentials, get to your Twitter apps page. Here's what the Apps folio looks like:

Edit app details

Here you'll find the Details push button of your app. Clicking this button takes you to the next page, where you can generate the credentials.

By selecting the Keys and tokens tab, y'all can generate and copy the key, token, and secrets to employ them in your code:

Generate keys and tokens

After generating the credentials, save them to later on employ them in your code.

You can test the credentials using the following snippet:

                                                  import                  tweepy                  # Authenticate to Twitter                  auth                  =                  tweepy                  .                  OAuthHandler                  (                  "pGBDoAaEpkliVKBOLwjtcmHGc"                  ,                  "xF3g1wrP50b6BlZEd20u4oVfjgH1FGQcuWUzlQO5aUWOufvlhw"                  )                  auth                  .                  set_access_token                  (                  "622518493-6VcLIPprbQbv9wkcBBPvCle8vsjU9fE85Dq9oStl"                  ,                  "tH9aKQbQQ1iRdYTcLSsPwitl44BkAc6jilrsU0ifnXvZhq"                  )                  api                  =                  tweepy                  .                  API                  (                  auth                  )                  try                  :                  api                  .                  verify_credentials                  ()                  impress                  (                  "Hallmark OK"                  )                  except                  :                  print                  (                  "Error during hallmark"                  )                              

In this snippet, credentials are tested using verify_credentials(). If all goes well, you should see a message saying Authentication OK.

Review of Tweepy Functionality

Tweepy gives you an interface to access the Twitter API from Python. It does and then by encapsulating much of the Twitter API's complexity and adding a model layer and other useful functionalities on top of it.

Since, over time, the names of various Twitter concepts have evolved, some old names are still used in Tweepy. Then go on in mind that, in the context of this article, these equivalences hold:

  • A status is a tweet .
  • A friendship is a follow-follower human relationship.
  • A favorite is a like.

At present that you know how Tweepy names things, permit's see how it works.

Tweepy'south functionality can be divided into the following groups:

  • OAuth
  • The API course
  • Models
  • Cursors
  • Streams

Now y'all're going to look into these groups to larn about the functionality each i provides.

OAuth

Tweepy takes intendance of all the details for using OAuth required by the Twitter API to authenticate each request. It provides an OAuthHandler class that you can apply to set the credentials to be used in all API calls.

This code snippet shows how yous tin create an OAuthHandler object that can afterward be used for API calls:

                                                  import                  tweepy                  # Authenticate to Twitter                  auth                  =                  tweepy                  .                  OAuthHandler                  (                  "CONSUMER_KEY"                  ,                  "CONSUMER_SECRET"                  )                  auth                  .                  set_access_token                  (                  "ACCESS_TOKEN"                  ,                  "ACCESS_TOKEN_SECRET"                  )                              

Here y'all're telling Tweepy to utilise the credentials that you lot created in Pace 3: Create the Authentication Credentials. You must supervene upon CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, and ACCESS_TOKEN_SECRET with the values yous previously generated.

The API Course

The API class has many methods that provide access to Twitter API endpoints. Using these methods, you can access the Twitter API'southward functionality.

The following code snippet creates an API object that you can utilize to invoke Twitter API methods. Setting wait_on_rate_limit and wait_on_rate_limit_notify to True makes the API object impress a message and wait if the charge per unit limit is exceeded:

                                                  import                  tweepy                  # Authenticate to Twitter                  auth                  =                  tweepy                  .                  OAuthHandler                  (                  "CONSUMER_KEY"                  ,                  "CONSUMER_SECRET"                  )                  auth                  .                  set_access_token                  (                  "ACCESS_TOKEN"                  ,                  "ACCESS_TOKEN_SECRET"                  )                  # Create API object                  api                  =                  tweepy                  .                  API                  (                  auth                  ,                  wait_on_rate_limit                  =                  True                  ,                  wait_on_rate_limit_notify                  =                  True                  )                              

In the lawmaking to a higher place, we've fix the hallmark credentials and created an api object. Y'all can invoke this object's methods to do any API telephone call.

The API methods tin can exist grouped into the following categories:

  • Methods for user timelines
  • Methods for tweets
  • Methods for users
  • Methods for followers
  • Methods for your business relationship
  • Methods for likes
  • Methods for blocking users
  • Methods for searches
  • Methods for trends
  • Methods for streaming

In the post-obit subsections, yous're going to review different groups of API methods. Y'all tin visit the API Class Documentation for a detailed list of all API methods.

Methods for User Timelines

These methods bargain with reading tweets, mentions, and retweets from your timeline or any other user'south timeline, as long as information technology'due south public.

This lawmaking snippet prints the author and text of the last tweets in your dwelling house timeline:

                                                  timeline                  =                  api                  .                  home_timeline                  ()                  for                  tweet                  in                  timeline                  :                  print                  (                  f                  "                  {                  tweet                  .                  user                  .                  name                  }                                      said                                    {                  tweet                  .                  text                  }                  "                  )                              

home_timeline(), a Tweepy API method, is used to get the last 20 entries in your timeline. 20 is the default value in Tweepy. You'll see later on how to become more than 20 results and work with paginated results.

Methods for Tweets

These methods have to do with creating, fetching, and retweeting tweets.

The post-obit code uses Tweepy to create a tweet with some text:

                                                  api                  .                  update_status                  (                  "Test tweet from Tweepy Python"                  )                              

We've used update_status() to create a new tweet from a Python cord.

Methods for Users

Methods in this grouping enable you to search users with a filter criteria, fetch user details, and listing the followers of any user, every bit long as that user account is public.

The snippet below fetches my user, @MikezGarcia, and and then prints its details every bit well every bit its twenty nearly contempo followers:

                                                  user                  =                  api                  .                  get_user                  (                  "MikezGarcia"                  )                  print                  (                  "User details:"                  )                  print                  (                  user                  .                  name                  )                  print                  (                  user                  .                  description                  )                  print                  (                  user                  .                  location                  )                  print                  (                  "Last 20 Followers:"                  )                  for                  follower                  in                  user                  .                  followers                  ():                  print                  (                  follower                  .                  name                  )                              

get_user() returns an object containing the user details. This returned object also has methods to access information related to the user. You used the followers attribute to become the list of followers.

Methods for Followers

This group of methods deals with following and unfollowing users, querying a user's followers, and listing the accounts any user is following.

This code shows how you tin use Tweepy to get-go following @realpython:

                                                  api                  .                  create_friendship                  (                  "realpython"                  )                              

create_friendship() adds @realpython to the list of accounts that you follow.

Methods for Your Account

These methods allow you to read and write your own profile details.

For case, you tin can employ this lawmaking snippet to update your profile clarification:

                                                  api                  .                  update_profile                  (                  description                  =                  "I like Python"                  )                              

The keyword argument description is passed to update_profile() to change your profile clarification to "I like Python".

Methods for Likes

Using these API methods, y'all tin mark whatsoever tweet as Liked or remove the Similar marker if it was already added.

You can mark the almost contempo tweet in your home timeline as Liked as follows:

                                                  tweets                  =                  api                  .                  home_timeline                  (                  count                  =                  1                  )                  tweet                  =                  tweets                  [                  0                  ]                  print                  (                  f                  "Liking tweet                                    {                  tweet                  .                  id                  }                                      of                                    {                  tweet                  .                  author                  .                  name                  }                  "                  )                  api                  .                  create_favorite                  (                  tweet                  .                  id                  )                              

This code uses home_timeline() to get the most recent tweet. Then, the tweet.id is passed to create_favorite() to mark the tweet as Liked.

Methods for Blocking Users

This group of methods deals with blocking and unblocking users, as well as list blocked users.

Hither's how y'all can come across the users that you lot have blocked:

                                                  for                  block                  in                  api                  .                  blocks                  ():                  print                  (                  block                  .                  name                  )                              

This lawmaking iterates through the list of accounts that you have blocked. You can become this list using blocks().

Methods for Searches

Using these methods, y'all can search tweets using text, language, and other filters.

For example, you can attempt this code to get the x most recent public tweets that are in English and comprise the give-and-take "Python":

                                                  for                  tweet                  in                  api                  .                  search                  (                  q                  =                  "Python"                  ,                  lang                  =                  "en"                  ,                  rpp                  =                  x                  ):                  print                  (                  f                  "                  {                  tweet                  .                  user                  .                  name                  }                  :                  {                  tweet                  .                  text                  }                  "                  )                              

Y'all used search() to filter tweets that friction match the desired criteria. This will search in any public tweet, not just in tweets from people you are following.

Methods for Trends

This group of methods allows you to list the electric current trends for any geographical location.

For example, here'southward how to listing the earth-wide trending topics:

                                                  trends_result                  =                  api                  .                  trends_place                  (                  1                  )                  for                  trend                  in                  trends_result                  [                  0                  ][                  "trends"                  ]:                  print                  (                  trend                  [                  "name"                  ])                              

Using trends_place(), you get the list of trends for any place, passing as the only argument the place id. Hither, one means world-broad. You can see the full list of available locations using api.trends_available().

Methods for Streaming

Streaming allows you to actively spotter for tweets that match sure criteria in real time. This means that when there aren't any new tweet matching the criteria, then the program will expect until a new tweet is created and so process information technology.

To use streaming y'all accept to create 2 objects:

  1. The stream object uses the Twitter API to get tweets that match some criteria. This object is the source of tweets that are then processed by a stream listener.
  2. The stream listener receives tweets from the stream.

Here's how yous do that:

                                                  import                  json                  import                  tweepy                  course                  MyStreamListener                  (                  tweepy                  .                  StreamListener                  ):                  def                  __init__                  (                  self                  ,                  api                  ):                  cocky                  .                  api                  =                  api                  cocky                  .                  me                  =                  api                  .                  me                  ()                  def                  on_status                  (                  self                  ,                  tweet                  ):                  impress                  (                  f                  "                  {                  tweet                  .                  user                  .                  name                  }                  :                  {                  tweet                  .                  text                  }                  "                  )                  def                  on_error                  (                  self                  ,                  status                  ):                  impress                  (                  "Mistake detected"                  )                  # Authenticate to Twitter                  auth                  =                  tweepy                  .                  OAuthHandler                  (                  "CONSUMER_KEY"                  ,                  "CONSUMER_SECRET"                  )                  auth                  .                  set_access_token                  (                  "ACCESS_TOKEN"                  ,                  "ACCESS_TOKEN_SECRET"                  )                  # Create API object                  api                  =                  tweepy                  .                  API                  (                  auth                  ,                  wait_on_rate_limit                  =                  True                  ,                  wait_on_rate_limit_notify                  =                  Truthful                  )                  tweets_listener                  =                  MyStreamListener                  (                  api                  )                  stream                  =                  tweepy                  .                  Stream                  (                  api                  .                  auth                  ,                  tweets_listener                  )                  stream                  .                  filter                  (                  track                  =                  [                  "Python"                  ,                  "Django"                  ,                  "Tweepy"                  ],                  languages                  =                  [                  "en"                  ])                              

You declared a new class, MyStreamListener. This grade is used for the stream listener tweets_listener. By extending Tweepy's StreamLister, we reused code that is common to all stream listeners. Tweets from the stream are processed by on_status().

We created the stream using tweepy.Stream, passing the authentication credentials and our stream listener. To start getting tweets from the stream, you have to phone call the stream's filter(), passing the criteria to use to filter tweets. And then, for each new tweet that matches the criteria, the stream object invokes the stream listener's on_status().

Models

Tweepy uses its own model classes to encapsulate the responses from various Twitter API methods. This gives you a convenient style to use the results from API operations.

The model classes are:

  • User
  • Condition
  • Friendship
  • SearchResults

Suppose you want to fetch every tweet in which yous are mentioned, and then marking each tweet as Liked and follow its author. Yous tin can practice that similar this:

                                                  tweets                  =                  api                  .                  mentions_timeline                  ()                  for                  tweet                  in                  tweets                  :                  tweet                  .                  favorite                  ()                  tweet                  .                  user                  .                  follow                  ()                              

Since each tweet object returned past mentions_timeline() belongs to the Condition form, you can utilise:

  • favorite() to marker it as Liked
  • user to get its author

This user attribute, tweet.user, is also an object that belongs to User, so yous can use follow() to add the tweet's author to the listing of people you follow.

Leveraging Tweepy models enables you to create concise and understandable code.

Cursors

A lot of Twitter API endpoints utilize pagination to return their results. By default, each method returns the first page, which usually contains a few dozen items.

Tweepy cursors have away part of the complexity of working with paginated results. Cursors are implemented every bit a Tweepy form named Cursor. To apply a cursor, you select the API method to utilize to fetch items and the number of items you want. The Cursor object takes intendance of fetching the various consequence pages transparently.

This code shows how, by using a cursor, you can get not only the first page from your timeline, but also the last 100 tweets:

                                                  for                  tweet                  in                  tweepy                  .                  Cursor                  (                  api                  .                  home_timeline                  )                  .                  items                  (                  100                  ):                  impress                  (                  f                  "                  {                  tweet                  .                  user                  .                  proper noun                  }                                      said:                                    {                  tweet                  .                  text                  }                  "                  )                              

A cursor object is created using tweepy.Cursor. The class constructor receives an API method to use every bit the source for results. In the example, we used home_timeline() as the source since we wanted tweets from the timeline. The Cursor object has an items() method that returns an iterable you can utilize to iterate over the results. You tin laissez passer items() the number of result items that you want to get.

How to Make a Twitter Bot in Python With Tweepy

Now that you know how Tweepy works, let's see how you can make a Twitter bot in Python with Tweepy. Bots work by continuously watching for some Twitter action and automatically reacting to it.

Watching for Twitter Activity

There are two ways to continuously sentinel for Twitter activity:

  1. Using streams: to be notified when new content, such every bit tweets, that matches certain criteria is created
  2. Using polling: to periodically make Tweepy API calls and then check their results to encounter if they contain something new

Which choice to choose depends on your employ case. Using streams is the nearly efficient option, but then you lot tin only spotter activity related to tweets, and so information technology's less flexible. In this section, both options are used to build unlike bots.

Presenting the Example Bots

In this commodity, you lot'll learn how to build iii different bots that perform automatic actions to react to some Twitter events:

  1. The Follow Followers Bot automatically follows anyone who follows y'all.
  2. The Fav & Retweet Bot automatically likes and retweets tweets that match certain criteria.
  3. The Respond to Mentions Bot automatically replies to tweets mentioning y'all that comprise the words help or support.

We are going to use a directory named bots to store all the Python files of the project as shown below:

                                tweepy-bots/ │ ├── bots/ │   ├── config.py │   └── followfollowers.py │   └── favretweet.py │   └── autoreply.py │ └── requirements.txt                              

The adjacent section explains the config module.

The Config Module

All the bots we are building have some functionality in common. For example, they demand to authenticate to the Twitter API.

Yous tin create a reusable Python module containing the logic common to all bots. We named this module config.

This module reads the authentication credentials from environment variables and creates the Tweepy API object. By reading the credentials from surround variables, yous avoid hard coding them into the source lawmaking, making it much more secure.

The bots volition read the credentials from these surround variables:

  • CONSUMER_KEY
  • CONSUMER_SECRET
  • ACCESS_TOKEN
  • ACCESS_TOKEN_SECRET

Afterwards, you'll run across how to set these variables to lucifer the credentials you lot have previously generated for your Twitter app.

Below is the consummate source code for the config module. It contains create_api(), a office that reads authentication credentials from environs variables and creates the Tweepy API object:

                                                  # tweepy-bots/bots/config.py                  import                  tweepy                  import                  logging                  import                  os                  logger                  =                  logging                  .                  getLogger                  ()                  def                  create_api                  ():                  consumer_key                  =                  os                  .                  getenv                  (                  "CONSUMER_KEY"                  )                  consumer_secret                  =                  os                  .                  getenv                  (                  "CONSUMER_SECRET"                  )                  access_token                  =                  bone                  .                  getenv                  (                  "ACCESS_TOKEN"                  )                  access_token_secret                  =                  os                  .                  getenv                  (                  "ACCESS_TOKEN_SECRET"                  )                  auth                  =                  tweepy                  .                  OAuthHandler                  (                  consumer_key                  ,                  consumer_secret                  )                  auth                  .                  set_access_token                  (                  access_token                  ,                  access_token_secret                  )                  api                  =                  tweepy                  .                  API                  (                  auth                  ,                  wait_on_rate_limit                  =                  True                  ,                  wait_on_rate_limit_notify                  =                  True                  )                  try                  :                  api                  .                  verify_credentials                  ()                  except                  Exception                  as                  e                  :                  logger                  .                  mistake                  (                  "Error creating API"                  ,                  exc_info                  =                  True                  )                  enhance                  e                  logger                  .                  info                  (                  "API created"                  )                  return                  api                              

This code uses os.getenv() to read surround variables so creates the Tweepy auth object. So the API object is created.

Passing wait_on_rate_limit and wait_on_rate_limit_notify in the creation of the tweepy.API object makes Tweepy wait and print a message when the charge per unit limit is exceeded.

Before returning the API object, create_api() calls verify_credentials() to check that the credentials are valid.

This module and, equally you will meet afterward, the bot's source lawmaking, employ the logging Python module to inform errors and info messages that assistance you debug them if whatsoever effect arise. Y'all can read more near it in Logging in Python.

The Follow Followers Bot

This bot gets your list of followers from Twitter every minute and then iterates through it to follow each user that y'all're non already following.

Bot Source Code

Here's the full source code of this bot. Information technology uses the previously created config module, the Tweepy API, and cursors:

                                                  #!/usr/bin/env python                  # tweepy-bots/bots/followfollowers.py                  import                  tweepy                  import                  logging                  from                  config                  import                  create_api                  import                  time                  logging                  .                  basicConfig                  (                  level                  =                  logging                  .                  INFO                  )                  logger                  =                  logging                  .                  getLogger                  ()                  def                  follow_followers                  (                  api                  ):                  logger                  .                  info                  (                  "Retrieving and following followers"                  )                  for                  follower                  in                  tweepy                  .                  Cursor                  (                  api                  .                  followers                  )                  .                  items                  ():                  if                  not                  follower                  .                  post-obit                  :                  logger                  .                  info                  (                  f                  "Following                                    {                  follower                  .                  proper noun                  }                  "                  )                  follower                  .                  follow                  ()                  def                  main                  ():                  api                  =                  create_api                  ()                  while                  Truthful                  :                  follow_followers                  (                  api                  )                  logger                  .                  info                  (                  "Waiting..."                  )                  time                  .                  sleep                  (                  60                  )                  if                  __name__                  ==                  "__main__"                  :                  main                  ()                              

main() creates a Tweepy API object using create_api() from the config module y'all previously created. Then, inside a loop, follow_followers() is called one time every minute.

follow_followers() uses a Tweepy cursor and the Tweepy API method followers() to get your list of followers. This list contains a Tweepy user model for each user that is following you.

Then the bot iterates through the list and uses following to check if yous are already following each user. Users that are not already beingness followed are followed using follow().

Running the Bot

To run the bot, yous must commencement create the surround variables for the hallmark credentials. You can exercise this by running this commands from a terminal and replacing the values with your actual credentials:

                                                  $                                    export                  CONSUMER_KEY                  =                  "pGBDoAaEpkliVKBOLwjtcmHGc"                  $                                    export                  CONSUMER_SECRET                  =                  "xF3g1wrP50b6BlZEd20u4oVfjgH1FGQcuWUzlQO5aUWOufvlhw"                  $                                    consign                  ACCESS_TOKEN                  =                  "622518493-6VcLIPprbQbv9wkcBBPvCle8vsjU9fE85Dq9oStl"                  $                                    export                  ACCESS_TOKEN_SECRET                  =                  "tH9aKQbQQ1iRdYTcLSsPwitl44BkAc6jilrsU0ifnXvZhq"                              

Afterwards you run the commands, your environment variables volition contain the credentials needed to use the Twitter API.

Next, you have to actuate your virtual environment and run the bot's primary file, bots/followfollowers.py:

                                                  $                                    source                  ./venv/bin/activate                  $                  python bots/followfollowers.py                              

While it'south running, the bot will follow everyone who follows you. You can test that information technology works by unfollowing someone that is following you. After a infinitesimal, they will be followed once again. You can stop the bot using Ctrl-C.

The Fav & Retweet Bot

This bot uses the previously introduced Tweepy stream to actively watch for tweets that contain certain keywords. For each tweet, if y'all're not the tweet author, information technology will mark the tweet as Liked and then retweet it.

You can use this bot to feed your account with content that is relevant to your interests.

Bot Source Code

Below, you tin can come across the total source code of this bot. It uses a stream to filter tweets that contain the words "Python" or "Tweepy". Each tweet from the stream is marked as Liked and retweeted:

                                                  #!/usr/bin/env python                  # tweepy-bots/bots/favretweet.py                  import                  tweepy                  import                  logging                  from                  config                  import                  create_api                  import                  json                  logging                  .                  basicConfig                  (                  level                  =                  logging                  .                  INFO                  )                  logger                  =                  logging                  .                  getLogger                  ()                  class                  FavRetweetListener                  (                  tweepy                  .                  StreamListener                  ):                  def                  __init__                  (                  cocky                  ,                  api                  ):                  cocky                  .                  api                  =                  api                  self                  .                  me                  =                  api                  .                  me                  ()                  def                  on_status                  (                  cocky                  ,                  tweet                  ):                  logger                  .                  info                  (                  f                  "Processing tweet id                                    {                  tweet                  .                  id                  }                  "                  )                  if                  tweet                  .                  in_reply_to_status_id                  is                  not                  None                  or                  \                  tweet                  .                  user                  .                  id                  ==                  self                  .                  me                  .                  id                  :                  # This tweet is a answer or I'm its writer so, ignore it                  return                  if                  non                  tweet                  .                  favorited                  :                  # Mark information technology equally Liked, since we take not washed it yet                  effort                  :                  tweet                  .                  favorite                  ()                  except                  Exception                  as                  e                  :                  logger                  .                  error                  (                  "Error on fav"                  ,                  exc_info                  =                  True                  )                  if                  not                  tweet                  .                  retweeted                  :                  # Retweet, since we accept non retweeted it yet                  try                  :                  tweet                  .                  retweet                  ()                  except                  Exception                  as                  e                  :                  logger                  .                  fault                  (                  "Error on fav and retweet"                  ,                  exc_info                  =                  True                  )                  def                  on_error                  (                  self                  ,                  condition                  ):                  logger                  .                  error                  (                  condition                  )                  def                  primary                  (                  keywords                  ):                  api                  =                  create_api                  ()                  tweets_listener                  =                  FavRetweetListener                  (                  api                  )                  stream                  =                  tweepy                  .                  Stream                  (                  api                  .                  auth                  ,                  tweets_listener                  )                  stream                  .                  filter                  (                  rail                  =                  keywords                  ,                  languages                  =                  [                  "en"                  ])                  if                  __name__                  ==                  "__main__"                  :                  main                  ([                  "Python"                  ,                  "Tweepy"                  ])                              

Equally with the previous bot, the principal function uses create_api() from the config module to create a Tweepy API object.

A Tweepy stream is created to filter tweets that are in the English language and include some of the keywords specified in the main part argument, "Python" or "Tweepy" in this case.

The on_status() of FavRetweetListener processes tweets from the stream. This method receives a status object and uses favorite() and retweet() to mark the tweet as Liked and retweet.

To avert retweeting and liking tweets that are replies to other tweets, on_status() uses an if to see if in_reply_to_status_id is non None. Also, the code checks if you lot're the tweet author to avoid retweeting and liking your own content.

You tin run this bot using the same instructions used for the previous bot, changing the Python plan to favretweet.py.

The Respond to Mentions Bot

This bot periodically fetches tweets in which you are mentioned. If the tweet is not a reply to another tweet, and it contains the words "help" or "back up", then the tweet writer will exist followed, and the tweet will be replied to with some other tweet saying "Please reach us via DM".

You can utilise this bot to automate the initial process of answering your followers' questions.

Bot Source Code

Hither's the total source code for this bot. It uses a cursor to fetch your mentions:

                                                  #!/usr/bin/env python                  # tweepy-bots/bots/autoreply.py                  import                  tweepy                  import                  logging                  from                  config                  import                  create_api                  import                  time                  logging                  .                  basicConfig                  (                  level                  =                  logging                  .                  INFO                  )                  logger                  =                  logging                  .                  getLogger                  ()                  def                  check_mentions                  (                  api                  ,                  keywords                  ,                  since_id                  ):                  logger                  .                  info                  (                  "Retrieving mentions"                  )                  new_since_id                  =                  since_id                  for                  tweet                  in                  tweepy                  .                  Cursor                  (                  api                  .                  mentions_timeline                  ,                  since_id                  =                  since_id                  )                  .                  items                  ():                  new_since_id                  =                  max                  (                  tweet                  .                  id                  ,                  new_since_id                  )                  if                  tweet                  .                  in_reply_to_status_id                  is                  not                  None                  :                  proceed                  if                  any                  (                  keyword                  in                  tweet                  .                  text                  .                  lower                  ()                  for                  keyword                  in                  keywords                  ):                  logger                  .                  info                  (                  f                  "Answering to                                    {                  tweet                  .                  user                  .                  name                  }                  "                  )                  if                  not                  tweet                  .                  user                  .                  following                  :                  tweet                  .                  user                  .                  follow                  ()                  api                  .                  update_status                  (                  status                  =                  "Please reach usa via DM"                  ,                  in_reply_to_status_id                  =                  tweet                  .                  id                  ,                  )                  return                  new_since_id                  def                  main                  ():                  api                  =                  create_api                  ()                  since_id                  =                  1                  while                  True                  :                  since_id                  =                  check_mentions                  (                  api                  ,                  [                  "help"                  ,                  "support"                  ],                  since_id                  )                  logger                  .                  info                  (                  "Waiting..."                  )                  time                  .                  slumber                  (                  threescore                  )                  if                  __name__                  ==                  "__main__"                  :                  main                  ()                              

Every bit with the others bots, the principal role creates a Tweepy API object. After that, it initializes the variable since_id with the value 1. This variable is used to but fetch mentions created subsequently those already candy.

Inside a loop, check_mentions() is called once every minute.

This function uses a Tweepy cursor and mentions_timeline() to get all the tweets mentioning you that have an id greater than the since_id variable.

For each tweet mentioning you, its author is followed using tweet.user.follow() if you are not already post-obit them.

Then a answer to the tweet is created using update_status(), passing the id of the original tweet as in_reply_to_status_id.

check_mentions() returns the greatest processed tweet id. This data will be used every bit the since_id in the next call to look only for tweets more recent than the ones already fetched.

You can run the bot using the same instructions used previously. Merely modify the Python program to autoreply.py.

Deploying Bots to a Server Using Docker

Existence able to run your Twitter bots in your local machine is fine for development, merely for product you'll probably need to run your bots in a server. This section details how yous can package your bot and its dependencies using Docker and so deploy it to a server.

Docker provides a way to packet whatsoever app in a Docker image containing not but the app itself, but all its dependencies too. You tin can larn more near Docker and its setup in Docker in Activity – Fitter, Happier, More Productive

Building the Docker Image

To bundle your bot or application, yous accept to create a Dockerfile in the project's root directory. This file contains a set of instructions used to create the Docker image containing your app.

This is how your project construction should look:

                                tweepy-bots/ │ ├── bots/ │   ├── config.py │   └── followfollowers.py │   └── favretweet.py │   └── autoreply.py │ ├── requirements.txt └── Dockerfile                              

As you lot tin can run across, the Dockerfile and requirements.txt alive within your project top directory.

Y'all can use the following Dockerfile to create the paradigm for the Fav & Retweet bot. It uses Python:3.seven-alpine as the base image. Nosotros chose this epitome as the base since it'southward very small and contains Python3.7 and pip. This Dockerfile then copies the bot code and the requirements.txt file to the image. Finally, the dependencies are installed inside the prototype using pip3:

                                                  FROM                  python:iii.vii-alpine                  Re-create                  bots/config.py /bots/                  Re-create                  bots/favretweet.py /bots/                  COPY                  requirements.txt /tmp                  RUN                  pip3 install -r /tmp/requirements.txt                  WORKDIR                                      /bots                  CMD                  [                  "python3"                  ,                  "favretweet.py"                  ]                              

The final line says what command must be run when this image is used.

At present you lot can build the image using this command:

                                                  $                  docker build . -t fav-retweet-bot                              

Then, using the docker images command, yous can see the details of the newly generated epitome.

Finally, you can apply the docker run control to exam the image, passing it the surroundings variables holding the authentication credentials:

                                                  $                  docker run -it -due east                  CONSUMER_KEY                  =                  "uDRNy31oWfoiKV9AvPoNavy0I"                  \                  -e                  CONSUMER_SECRET                  =                  "lnAL5VAgZLWNspQVpd3X6tEo47PRCmsPEwuxpvLCLSR08DMa4O"                  \                  -e                  ACCESS_TOKEN                  =                  "622518593-j7gWSqzQO31ju7Bf7idB47NlZeSENsuADGU9B69I"                  \                  -east                  ACCESS_TOKEN_SECRET                  =                  "iutFsxvP5IglRckJ1I1why6017xMNkzxqBID48Azw0GvT"                  \                  fav-retweet-bot                              

While it's running, you'll see the bot'southward logs output on the screen.

This aforementioned procedure tin can be used to create the Docker image for other bots.

Case: Deploying a Twitter Bot to Amazon AWS

Now that the Docker image is set, at that place are a lot of ways to deploy it to run in any server. In this section, you'll come across ane method you tin can use to deploy a bot to a server in Amazon AWS. This setup uses an Amazon AWS EC2 instance, like a virtual server, to run the Docker epitome.

Footstep 1: Export The Docker Image

From the calculator where you lot have created the Docker paradigm, run these commands to consign information technology to a file and compress it. Y'all're going to use this file later to upload the prototype to your EC2 instance:

                                                  $                  docker image salve fav-retweet-bot:latest -o fav-retweet-bot.tar                  $                  gzip fav-retweet-bot.tar                              

Now the image has been compressed into fav-retweet-bot.tar.gz.

Step 2: Create an Amazon EC2 Example

The first step in AWS is to create a new EC2 example. The bot volition run within this instance. Log in to your AWS console, choose the EC2 service, and select Instances. You'll see something similar this:

Create an EC2 instance

Click the Launch instance push button and select Ubuntu Server 18.04 as the base epitome:

Select EC2 instance base image

Now yous tin can choose the instance type. This depends on the calculating resources needed past your bot. For the bots described in this article, the t2.micro instance type is a good starting signal. Select it and click Review and Launch:

Select EC2 instance type

On the next folio, yous tin can review and cheque your configuration. Then click the Launch button to begin the creation of your EC2 example:

Review and launch EC2 instance

After y'all've clicked Launch, you'll exist asked to create a key pair. It's used to permit you to connect to your instance and deploy the bot Docker image. Select Create a new key pair, enter a key pair name, and download the fundamental pair.

Remember where you're downloading the key pair. You'll need information technology later.

Then click the Launch instances button to proceed:

Create key pair

You will see a page proverb that your instance is existence created. Click the View instances button to see the status of your example:

Instance is getting created

At first, your case state will be pending. Y'all have to wait until it transitions to running:

EC2 instance is in peding status
EC2 instance is ready

Step 3: Install Docker in Your EC2 Instance

Now you have to connect to your example using SSH to install Docker on information technology.

If, in the previous screen, yous right click on your instance, you'll find a context menu. Select the Connect option to see how to connect using SSH:

Context menu for EC2 instance

This dialog shows how to connect to your example:

EC2 connection dialog

Showtime, change the permissions of your key pair file using the post-obit control. Otherwise, you won't be able to connect to your EC2 instance using this key pair:

                                                  $                  chmod                  400                  mykeypair.pem                              

So connect to your instance using SSH. Yous tin can copy the command you need to execute from the Connect To Your Example dialog:

                                                  $                  ssh -i                  "mykeypair.pem"                  ubuntu@ec2-3-86-66-73.compute-one.amazonaws.com                              

Once yous're connected, run the following commands to install Docker in the instance:

                                                  ubuntu@ip-172-31-44-227:~$                  sudo apt-get update                  ubuntu@ip-172-31-44-227:~$                  sudo apt install docker.io                  ubuntu@ip-172-31-44-227:~$                  sudo adduser ubuntu docker                  ubuntu@ip-172-31-44-227:~$                                    exit                              

It's of import that you exit the SSH session after the installation, so that in the adjacent login your user permissions will be reloaded.

Stride iv: Upload Your Bot'south Docker Prototype

From your local figurer, upload the bot Docker image to your instance using scp. This tin can take some time depending on your cyberspace connection:

                                                  $                  scp -i                  "mykeypair.pem"                  fav-retweet-bot.tar.gz                  \                  ubuntu@ec2-3-86-66-73.compute-1.amazonaws.com:/tmp                              

When the image upload finishes, log in again to your example using SSH:

                                                  $                  ssh -i                  "mykeypair.pem"                  ubuntu@ec2-3-86-66-73.compute-1.amazonaws.com                              

Run these commands in your instance to decompress and import the Docker epitome:

                                                  ubuntu@ip-172-31-44-227:~$                  gunzip /tmp/fav-retweet-bot.tar.gz                  ubuntu@ip-172-31-44-227:~$                  docker image load -i /tmp/fav-retweet-bot.tar                              

Pace 5: Run Your Bot's Docker Prototype

The concluding step to deploy the bot is to run the Docker prototype in your EC2 case, passing it the authentication credentials.

You can do this using the docker command. Passing the flags -d and --restart-e'er assures that the bot will go on running if you lot disconnect from the SSH session or if the case is restarted:

                                                  ubuntu@ip-172-31-44-227:~$                  docker run -d --restart always                  \                  -e                  CONSUMER_KEY                  =                  "uDRNy31oWfoiKV9AvPoNavy0I"                  \                  -due east                  CONSUMER_SECRET                  =                  "lnAL5VAgZLWNspQVpd3X6tEo47PRCmsPEwuxpvLCLSR08DMa4O"                  \                  -e                  ACCESS_TOKEN                  =                  "622518593-j7gWSqzQO31ju7Bf7idB47NlZeSENsuADGU9B69I"                  \                  -e                  ACCESS_TOKEN_SECRET                  =                  "iutFsxvP5IglRckJ1I1why6017xMNkzxqBID48Azw0GvT"                  \                  fav-retweet-bot                              

Using docker ps, you can check that the bot is running and find its container id. Finally, using the docker logs control and the container id, you can bank check the output from the bot to see if it works properly:

                                                  $                  ubuntu@ip-172-31-44-227:~$ docker logs e6aefe73a885                  INFO:root:API created                  INFO:root:Processing tweet id 1118276911262785538                  INFO:root:Processing tweet id 1118276942162214918                  INFO:root:Processing tweet id 1118276990853951488                  INFO:root:Processing tweet id 1118277032360722433                  INFO:root:Processing tweet id 1118277034466324480                              

Now, even if you disconnect from the SSH session or turn off your estimator, the bot will keep to run on your AWS EC2 case.

Free AWS Resources

To salve resource and coin (if your AWS complimentary tier period has ended), you lot can stop or terminate your EC2 instance:

EC2 terminate or stop and instance

Stopping it will allow you to restart it in the future, but information technology will notwithstanding eat some resources related to your instance storage. Past contrast, if yous Terminate an EC2 instance, then all its resource will be released, but you won't be able to restart it.

There's a lot more to using AWS, similar creating an AWS image of your instance, just that goes beyond the scope of this article.

Wrapping Upward

Edifice your own Twitter bots allows yous to accept your Twitter presence to the next level. By using bots, you tin automate content creation and other Twitter activities. This tin relieve you a lot of fourth dimension and give your audience a better feel.

The Tweepy bundle hides many low level details of the Twitter API, assuasive you lot to focus on the logic of your Twitter bots.

In this article, y'all learned how to:

  • Improve and automate your interactions with your Twitter audience
  • Install Tweepy
  • Sign up as a Twitter developer to utilise its API
  • Use Tweepy to invoke the Twitter API
  • Build Twitter bots
  • Deploy the bots to a server using Docker and AWS

You can employ the bots in this article as a starting point to automate role of your Twitter activity. Don't forget to have a look at the whole Tweepy API documentation and use your imagination to make more complex bots that are meaningful to your utilize case.