How to create a Twitter Bot with Python3 and Tweepy

Halil Cetiner
Chatbots Life
Published in
3 min readJan 25, 2018

--

Introduction

A Twitter Bot is a program that integrates with Twitter API and automatically executes Twitter actions like posting a tweet, retrieving a user’s tweets etc. At this story I will go through a live Twitter Bot which I published on the 25th of Jan.

What do we need?

I will handle the process in two parts, Twitter part and Python part.

Trending Articles on Chatbot Marketing:

1. How my Chatbot got 100K users in 1 week

2. BotXperts asked — with Veronica Belmont of Growbot.io

3. Messenger User Acquisition: How to build Facebook Comment Auto Reply

Twitter part

  • Firstly and obviously you need a Twitter account.
  • Then you need to go to apps.twitter.com and create an app.
  • After creating application you need to go Keys and Access Tokens tab and regenerate Consumer Key and Consumer Secret.
  • Then you should authorize the application for your own profile.

Python part

  • You need to install Tweepy. You can do it either by downloading Tweepy from github and installing manually or just use pip. Second way is much more easier than installing manually.
$ sudo pip3 install tweepy

Let’s Write Some Code

Firstly I want to explain _twin_primes a bit. It is a twitter bot which posts the next twin prime pair every 30 minutes.

And a twin prime is a prime number that is either 2 less or 2 more than another prime number — for example, either member of the twin prime pair (41, 43). wiki

_twin_primes is based on the data I took from https://primes.utm.edu/lists/. It contains the first 100000 twin prime pairs.

  • At first, we need to import tweepy
import tweepy
  • Then we need to write a function to parse the data from primes.utm.edu

parse_primes traverses the text and appends every numerical expression between spaces to a list.

  • At the bot part firstly we need to send twin_primes.txt to parse_primes function. Then validate the API connection easily thanks to Tweepy.

The logic of the bot is using the last tweet as the index and posting the next pair.

  • You need to enter your keys to the lines, 5 to 8
  • At lines 9 to 11, API access granted.
  • At lines 13 and 14, we are getting the last tweet, split the pair and take the first element. Because, only first elements of the twin prime pairs are listed at the twin_primes.txt (memory optimization).
  • At lines 14 and 15, we are finding the last posted pair’s index and assign next number to next_index.
  • At line 16, we assign the string in format of our tweets to the twit.
  • And at the line 17 we post the twit. 🎉

The Code

Full code can be found at my GitHub repo.

To see the result check the Twitter profile.

--

--