Build A Free Twitter Retweet Bot

Published on June 4, 2022

Twitter is a powerful tool for connecting with others, learning something new, and can be valuable for marketing a brand or startup. One way to gain more popularity on the platform is by creating a unique hashtag related to your brand and retweeting any tweets containing it. Manually retweeting every tweet is time consuming and boring. This guide will show you how to create a bot to do this for free.

Prerequisites 


  • Twitter account
  • A deployed Ruby on Rails application 
  • Basic ruby programming experience

This guide will setup a retweet bot for the hashtag #1manstartup. Any tweet containing that hashtag will be retweeted by me @davefaliskie within 10 minutes. 

Step 1: Create a twitter developer account

To begin you must create a twitter developer account. Go to https://developer.twitter.com/ and sign up for the developer program. Once signed in, you’ll be prompted to enter an app name to generate the API keys. I’ll name my app mine 1ManStartup.
Create account and name app
Once the keys are generated, copy all three of them (API Key, API Key Secret, and Bearer Token) to a safe location. We’ll use them later. Then click Skip To Dashboard.

Save API keys
Since we’ll be retweeting tweets we also need to apply for elevated access. Navigate to Projects & Apps > Project 1 on the left side. Then towards the top of the page you should see a button to apply for elevated access.
Click the Apply button

Complete the application, the following is what I wrote which you can modify or use to fit your project. 

How will you use the Twitter API or Twitter Data?


I would like to use the twitter API to create a simple retweet bot. My goal is to personally retweet anything that contains my brand’s specific hashtag. I only plan to set this up for one specific hashtag which is specifically related to my brand.

Will your App use Tweet, Retweet, Like, Follow, or Direct Message functionality?: YES


I plan to retweet any tweet that contains the specific hashtag related to my brand. I will only be retweeting the tweets containing the hashtag I'm following and don't plan to use any other functionality.

Answer no to the other questions
and click Next. Review and accept the terms and conditions. After completing you should be granted elevated access. 
Apply for elevated access
Now, we need to generate the Access Token and Secret so that we can authenticate with OAuth. Navigate to your app and click Keys and tokens then under the Authentication Tokens section find Access Token and Secret and click Generate. It’s not necessary to copy these keys yet because we will be regenerating them soon.

Generate the access token and secret
Notice that the new tokens were created with read only permission. Since the bot will be retweeting its necessary to also have write access. Click on the Settings under the app and find User authentication settings. Authentication will need to be set up so click Set up
Chick Set up to generate OAuth keys
Select the setup for OAuth 1.0a and then choose Read and write. You’ll also need to add a callback and website url. This bot won’t use callbacks so the url here isn’t too important I would suggest using your sites domain with a callbacks path like https://YOUR_DOMAIN/callbacks/twitter.  
Setup OAuth with read and write permissions
Click save and then continue to change permissions. Because we changed the permissions we will need to regenerate the Access Token and Secret. Go back to Keys and tokens and click Regenerate next to the Access Token and Secret. Save both the Access Token and Access Token Secret in a safe location. You should now see that the tokens were created with read and write permissions. 


Step 2: Search for tweets by hashtag


Begin by adding the 5 keys generated in Step 1 to your rails app credentials. I’m using Visual Studio Code but this can be done with any editor, edit the credentials file with the following command.

EDITOR="code --wait" rails credentials:edit

Add the 5 keys under the twitter namespace as seen below. 

twitter:
  api_key: API_KEY
  api_key_secret: API_KEY_SECRET
  Bearer_token: BEARER_TOKEN
  Access_token: ACCESS_TOKEN
  access_token_secret: ACCESS_TOKEN_SECRET


Install the gem

Open your Gemfile and add the Twitter ruby gem which can be found here. This gem makes interacting with the Twitter API in a rails app very simple. 

gem "twitter", "~> 7.0"

Then run bundle install to install the gem. 

Create the service class

The code to look retweet tweets with the given hashtag will be written in a service class. If you aren’t familiar with using service classes this guide will explain the concept and get your app setup to use service classes.

In the services directory of the rails app, create a new folder called twitter_manager and inside that create a new file called retweet.rb

File structure
Open up retweet.rb and create the module and class. Define the empty call method in the Retweet class.

module TwitterManager
  class Retweet < ApplicationService
    def call
    end
  end
end

Before we can interact with the Twitter API we need to authenticate a client. We can do this by creating a method called client which will use the Twitter rails gem to generate an authenticated client. Add the following below the call method.

private
  def client
    Twitter::REST::Client.new do |config|
      config.consumer_key        = Rails.application.credentials.dig(:twitter, :api_key)
      config.consumer_secret     = Rails.application.credentials.dig(:twitter, :api_key_secret)
      config.access_token        = Rails.application.credentials.dig(:twitter, :access_token)
      config.access_token_secret = Rails.application.credentials.dig(:twitter, :access_token_secret)
    end
  end

Now we can initialize the Retweet class with an instance of the client. Above the call method add the initialize method.

def initialize
  @client = client
end

To make the Retweet class more flexible we can pass it a parameter for the search query. In my case I want to search for tweets with the hashtag #1manstartup so I’ll set that as the default.

def initialize(query: "#1manstartup")
  @client = client
  @query = query
end

Now we can make a call to the twitter API to search for tweets containing the query string. Since we don’t want to retweet already retweeted tweets add the -rt  to ignore retweets from the search results. 

def initialize(query: "#1manstartup")
  @query = query
  @client = client
  @tweets = @client.search("#{@query} -rt")
end

Step 3: Retweet by tweet ID


With the class is initialized, we can use the call method to retweet all the tweets found in the search. Since the Twitter rails gem will return an array of tweets matching our search we can simply loop through them and, using the @client, retweet each tweet. We can also log out the tweet ID which will be retweeted.

def call
  @tweets.each do |tweet|
    Rails.logger.info "retweeting tweet id: #{tweet.id}"
    @client.retweet(tweet)
  end
end

This is good, but it can be better. Since we only want to retweet each tweet once, we can track the last retweeted tweet and update the search to start from that tweet. To do this we will need to store the last retweeted tweet's ID in the database.

This value can be stored in its own table but I prefer to create a Constant model which will only ever have one row. Run a migration to create a new Constant model and give it one column for the last retweeted tweets id.

rails g model constants

class CreateConstants < ActiveRecord::Migration[7.0]
  def change
    create_table :constants do |t|
      t.bigint :tweet_since_id
      t.timestamps
    end
  end
end

Open the rails console and create the first Constant object, which we can later use to update the last retweeted tweet’s id.

Constant.create(tweet_since_id: 0)

Update the search to the twitter API to pass the tweet ID of the last tweet returned from the previous search.

@tweets = @client.search("#{@query} -rt", since_id: Constant.first.tweet_since_id)

Next, update the call method to save the last searched tweet id to the Constant table. Since the Twitter API returns an array of tweets with the most recent first, the first tweet returned will be the most recent. Add this line to the end of the call method. 

Constant.first.update(tweet_since_id: @tweets.first.id)

If no tweets are returned from the search the current code would set tweet_since_id to nil, to prevent this add a check before updating the Constant table.

return if @tweets.first.blank?

You can run the code and watch the searched results be retweeted. From the rails console run the following to search and retweet.

TwitterManager::Retweet.call

NOTE: this will actually retweet any tweets returned from the search, so make sure what you’re searching is actually what you want to retweet. Using a very specific hashtag is best when testing.

The Full code for the Retweet class can be seen below

module TwitterManager
  class Retweet < ApplicationService
    def initialize(query: "#1manstartup")
      @query = query
      @client = client
      @tweets = @client.search("#{@query} -rt", since_id: Constant.first.tweet_since_id)
    end
 
    def call
      @tweets.each do |tweet|
        Rails.logger.info "retweeting tweet id: #{tweet.id}"
        @client.retweet(tweet)
      end
 
      return if @tweets.first.blank?
 
      Constant.first.update(tweet_since_id: @tweets.first.id)
    end
 
    private
 
    def client
      Twitter::REST::Client.new do |config|
        config.consumer_key        = Rails.application.credentials.dig(:twitter, :api_key)
        config.consumer_secret     = Rails.application.credentials.dig(:twitter, :api_key_secret)
        config.access_token        = Rails.application.credentials.dig(:twitter, :access_token)
        config.access_token_secret = Rails.application.credentials.dig(:twitter, :access_token_secret)
      end
    end
  end
end

Step 4: Create rake task


This bot should run continuously and retweet all new tweets with the given hashtag. To achieve this we can create a rake task and schedule it to run the code every 10 minutes. Create a new file lib/tasks/twitter.rake and write the following to call the service class.

namespace :twitter do
  desc 'Search twitter for tweets with #1manstartup and retweets them'
  task retweet: :environment do
    TwitterManager::Retweet.call
  end
end

Running rake twitter:retweet will now call the Retweet class. 

Step 5: Deploy & Schedule


I’ll be using Heroku to host this retweet bot. Once the code is deployed there are two additional steps needed before the bot will actually work.

1. Manually create the first object in the Constant model, open the rails console in production run the following.

Constant.create(tweet_since_id: 0)

2. Schedule the rake task. The Heroku scheduler can be used for this. I chose to have this run every 10 minutes but you may decide on a different duration.
Schedule the rake task

I hope this free twitter bot is useful to you. Mine is running now, so share your startup with the hashtag #1manstartup and watch my bot retweet it 😎.

ABOUT ME

Dave Faliskie

I'm a software developer interested in building world changing applications. My goal is to document and share all the knowledge I learn so others can quickly start building something awesome.

EXCLUSIVE OFFERS