Skip to content

How to increase your Twitter visibility with an Autoretweet and Autogreeting bot

I ran this experiment for several reasons…

  • Firstly, I wanted to subscribe to Twitter, explore how it works and whether it useful for sharing relevant content and making new connections.
  • Secondly, I wanted to sharpen my Python skills as I promised in a previous post, and learn more about the capability of this programming language to integrate with developers’ APIs.
  • Thirdly, I was keen to increase a bit my professional visibility.

Therefore, I decided to create an Autoretweet bot. In other words, a piece of software that would automatically repost tweets from other Twitter users based on certain keywords.

I chose the keywords to be hashtags based upon my professional interests: private equity, innovation, venture capital, investments, etc…

I was also keen to endow my bot with another functionality (which then I shut down because I found slightly annoying, but I will show it anyway): send a personal greeting message to every new Twitter follower (Autogreeting), where I would thank for the follow and introduce myself.

A DIY approach…

I am aware there may be commercial tools around doing the exact same thing, probably easier to deploy and customise than the solution I am going to propose. However, the DIY approach is often more fun, educational and – above all – FREE.

The basic ingredients to build an Autoretweet and Autogreeting Twitter bot are the following:

  1. Some familiarity with Python, one of today’s most powerful programming languages
  2. Tweepy, a programming library the wraps the Python language and the Twitter API
  3. quite obviously… A Twitter account, and
  4. Access to a Virtual Private Server (VPS).

While it may seem a daunting task for a newbie, programming the bot is actually easier than you may think.

In any case, I will guide you through the process step by step.

Step 1 -> Create a Twitter account

This should be fairly easy. Head to Twitter, click on the Sign Up button, and proceed with the registration.

Step 2 -> Create a Twitter App

Once you registered a Twitter account, you need to create a Twitter App. Browse to the Twitter Apps website and click on the “Create New App” button.

Give the app a “name”, a “description” and specify a “website”. Note: the website element is compulsory but not strictly required. You can put a placeholder (such as http://www.place.holder) if you do not have an actual website.

It is now important to change the app “permissions” to “read, write and access direct messages”.

It is equally important to generate or save four tokens via the “Keys and Access Tokens” tab (a token is an alphanumeric combination). We will need:

  1. Consumer Key
  2. Consumer Secret,
  3. Access Token, and
  4. Access Token Secret.

Note: Do NOT share these tokens with anyone or the security of your app will be compromised (i.e. a malicious agent could use it on your behalf).

Step 3 – Connect to a Virtual Private Server (VPS)

A VPS is a virtual machine, located somewhere in the world and connected 24/7 to the internet. Unless you want to leave your home computer up and running day and night (and always connected to the internet) you need a VPS to run a bot.

Many web-hosting companies provide VPS services. My provider is a French company called OVH. I bought from them a VPS SSD 1, with Linux Debian installed. It is an economical and user-friendly option. For our Twitter bot, we do not need anything fancier.

I haven’t tried many other alternatives so I cannot guarantee that the proposed VPS is the best available on the market. However, it has proven to be a satisfactory solution.

Once the VPS is up and running, you need to log into it from your computer. The login procedure is very easy on Linux and Mac, just one command from the terminal. Connecting to a secure VPS from Windows is instead slightly more complicated. If you are a Windows user, I suggest you refer to PuTTY and some online manuals on its usage.

Open a terminal window (in Linux or Mac) and do:

ssh root@yourvpsid.ovh.net

where yourvpsid is an address that you should have received by OVH after the registration. You will now need to insert the password provided by OVH in the same confirmation email.

Step 4 – Install Python and PIP onto the VPS

Once you are connected to the VPS, you need to install Python (2.7) and pip. Pip is the Python package manager, which we need to install the Twitter wrapper for Python.

Logged in terminal as root, type:

sudo apt-get -y update
sudo apt-get -y upgrade
sudo apt-get -y dist-upgrade
sudo apt-get -y install python2.7
sudo apt-get -y install python-pip

You can confirm successful installation by running the following commands: for Python, type python, and the result should be: python is /usr/bin/python; for pip type pip, and the result should be: pip is /usr/local/bin/pip.

To make sure you have the right Python version, type python --version. The result should be something like: Python 2.7.x

Via pip, you can then install Tweepy:

pip install tweepy==3.2.0

Go ahead then to create a directory where your bot files will reside.

mkdir autoretweet-personal

In the directory, create the necessary files (a config file, a main script file, and a cron job file) by executing the following commands:

cd autoretweet-personal
touch config
touch retweet.py
touch cron_job.sh

Step 5 – Create the Autoretweet script

First copy the following text and paste it into the “config” file you just created (you can edit it by launching the terminal command nano config). Insert in the right place the four tokens you generated when creating the Twitter App back at Step 2:

[settings]
# Leave empty for all languages
tweet_language: en

# Replace the text in italics with the tokens you created on http://apps.twitter.com
[twitter]
consumer_key: your_consumer_key
consumer_secret: your_consumer_secret
access_token: your_access_token
access_token_secret: your_access_token_secret

CTRL+O to write and CTRL+X to exit.

Now it is time to create the actual script. Try to understand – by reading carefully – what each line of the script is trying to achieve.

If you have no time, or willingness, to do that, simply focus on the “hashtags” line. Here, replace the [‘#hashtag1′ ,’#hashtag2′ ,’#hashtag3′ ,’#hashtag4’] list with the keywords that are of interest to you, and that you would like to retweet. When these keywords appear in other people’s tweets, the program will retweet them.

Open the retweet.py file with the Linux text editor (nano retweet.py) and paste into it the following code:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, ConfigParser, tweepy, inspect, hashlib, pickle, random

path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))

# read config
config = ConfigParser.SafeConfigParser()
config.read(os.path.join(path, "config"))

# tweet language (empty = all languages)
tweetLanguage = config.get("settings","tweet_language")

#Insert your hashtags here
hashtags = ['#hashtag1','#hashtag2','#hashtag3','#hashtag4']

hashtag = hashtags[random.randint(0,len(hashtags)-1)]

# blacklisted users and words
userBlacklist = []
wordBlacklist = ["RT", u"♺"]

# build savepoint path + file
hashedHashtag = hashlib.md5(hashtag).hexdigest()
last_id_filename = "last_id_hashtag_%s" % hashedHashtag
rt_bot_path = os.path.dirname(os.path.abspath(__file__))
last_id_file = os.path.join(rt_bot_path, last_id_filename)

# create bot
auth = tweepy.OAuthHandler(config.get("twitter","consumer_key"), config.get("twitter","consumer_secret"))
auth.set_access_token(config.get("twitter","access_token"), config.get("twitter","access_token_secret"))
api = tweepy.API(auth)

# retrieve last savepoint if available
try:
    with open(last_id_file, "r") as file:
        savepoint = file.read()
except IOError:
    savepoint = ""
    print "No savepoint found. Trying to get as many results as possible."

# search query
timelineIterator = tweepy.Cursor(api.search, q=hashtag, since_id=savepoint, lang=tweetLanguage).items(25)

# put everything into a list to be able to sort/filter
timeline = []
for status in timelineIterator:
    timeline.append(status)

try:
    last_tweet_id = timeline[0].id
except IndexError:
    last_tweet_id = savepoint

# filter @replies/blacklisted words & users out and reverse timeline
timeline = filter(lambda status: status.text[0] != "@", timeline)
timeline = filter(lambda status: not any(word in status.text.split() for word in wordBlacklist), timeline)
timeline = filter(lambda status: status.author.screen_name not in userBlacklist, timeline)
timeline.reverse()

tw_counter = 0
err_counter = 0

# iterate the timeline and retweet
for status in timeline:
    try:
        print "(%(date)s) %(name)s: %(message)s\n" % \
               { "date" : status.created_at,
               "name" : status.author.screen_name.encode('utf-8'),
               "message" : status.text.encode('utf-8') }

        api.retweet(status.id)
        tw_counter += 1
    except tweepy.error.TweepError as e:
        # just in case tweet got deleted in the meantime or already retweeted
        err_counter += 1
        #print e
        continue

print "Finished. %d Tweets retweeted, %d errors occured." % (tw_counter, err_counter)

# write last retweeted tweet id to file
with open(last_id_file, "w") as file:
    file.write(str(last_tweet_id))

Step 6 – Create the Autogreeting script

Only copy and paste the following if you intend to send a personalised greeting message to any new person that follows your Twitter profile. I used to do that, but then I found it was a bit annoying for some people, therefore I decided to let it go.

To personalise your greeting message, simply change the content of the “greetingmessage” line. Again, it would be great if you could make enough time to understand what each of the following Python commands is trying to achieve.

Simply append the following code at the bottom of the usual retweet.py file that you edited earlier:

#greeting message
greetingmessage = u'Insert your \n greeting \n message \n here'

#pickle file
followersdatabasename = "myfollowers.p"
followersdatabase = os.path.join(path, followersdatabasename)

try:
    with open(followersdatabase) as file:
        myfollowers_old = pickle.load( open( followersdatabase, "rb" ) ) #load old followers list
        myfollowers_new = api.followers_ids() #create new followers list
        newfollowers = [element for element in myfollowers_new if element not in myfollowers_old] #checks for new followers
        if newfollowers: #if new followers list is not empty
            for follower in newfollowers:
                api.send_direct_message(follower, text=greetingmessage)
            pickle.dump( myfollowers_new, open( followersdatabase, "wb" ) )
except IOError: #create the file if it does not exist
    myfollowers = api.followers_ids()
    pickle.dump( myfollowers, open( followersdatabase, "wb" ) )

Once you are done with the above (CTRL+O to write, CTRL+X to quit), it is time to schedule automated execution of the script at predetermined intervals.

Step 7 – Schedule automated execution via crontab

Your script will never run if you do not schedule its execution at predetermined intervals. This is achieved via a Linux tool called crontab, which should be by default present on your VPS machine.

Please feel free to run the script at will. That could be once in every half an our, or once a day, or once every two days. Just be careful NOT to schedule it TOO OFTEN, or you may annoy someone.

In order to do this, you have to set up a cron_job.

In the existing autoretweet-personal folder, open the cron_job.sh file that you created earlier (edit it with nano cron_job.sh) and paste into it:

#!/bin/bash
python $HOME/autoretweet-personal/retweet.py

CTRL+O to write the file, CTRL+X to quit (I won’t be repeating it again!).

Now go back to the root folder (cd ..), and type:

crontab -e

This command will open your crontab. At the bottom of the crontab file, paste the following code:

30 * * * * autoretweet-personal/cron_job.sh

and save.

The command above will run the bot every hour, at 30 minutes intervals. As you may have already noticed, the first 5 characters of the crontab instruction (30 * * * *) set the “tempo” at which the specific command will be executed.

For more information on the crontab and its syntax, you can check both the top commented lines of the crontab file, or an external reference, the crontab schedule expression editor.

Step 8 – ENJOY YOUR BOT!

After having followed all of the previous steps, you can logout from the VPS and let the script do his job.

From time to time, You can log back into your Twitter profile to witness how posts are being automatically retweeted, and greeting messages are being automatically sent to your new followers.

Should you wish to stop the bot execution at any time, just log back into the VPS, open the crontab (crontab -e) and comment out or delete the line that you just created. Save and close the crontab to make the change permanent.

Published inProgrammingTechnology