Creating a Twitter bot using Python

Dakshil Shah
6 min readJun 24, 2016

--

Learn how you can create a simple Twitter bot using Python and the Twitter API.

Disclaimer: This is for educational purposes only and serves to introduce readers to creating twitter bots. Please do not create twitter bots that annoy people or spam.

Last night I was seeing the news and the debate was on censorship in Indian cinema. The news channel allows viewers to tweet their opinion and airs the same. So taking inspiration from this I decided to create a satirical twitter bot which would do unnecessary censorship on twitter.

Here’s the gist:

The bot is written completely in Python. You supply a keyword to the bot. For the sake of censorship lets say I gave the keyword “shit”. Now, the latest tweet containing this word is fetched, this word is replaced by “poop” and this modified tweet is tweeted back to the user.

Yes, I know this bot is somewhat of an ass(all humor intended) but it’s just to get an idea of how entertaining twitter can be. I made this bot tweet every hour, given my previous experiment last year when a bot of mine was suspended for making too many requests in an hour and crossing the fair usage limit.(sorry Twitter, but I am proud I got over 3.5K followers on that account with only 2 tweets and not even controlling that account manually. Leave a comment/tweet out to me if you want this to be the next article)

I know what you all are here for so lets get down to it and get dirty with some code.

Prerequisites:

First you need Python installed but since you’re here, I’m assuming you have it installed. If not, just install Anaconda Python.

Next, we need to install Twitter for Python. Simply open your terminal or as the case may be and install using pip

pip install twitter

Now, you need to get a Twitter Account. I’d suggest make a new one for experimental purposes. Go to https://apps.twitter.com/ and create a new app. In order to access this, you need to provide your phone number(you can delete it later). Fill in the details and you’ll get access to the auth tokens that we will need. Please keep these to yourself and do not share them as they provide potentially disastrous access to your Twitter account and you don’t want that.

Now that we’re all set up, we can dig into the code.

Note: Do not copy paste the code. Python is indentation sensitive and copy pasting will definitely lead to indentation errors. Please type the code as you follow step by step. Full code will be provided ahead.

  1. We need to import the necessary libraries.
from twitter import Twitter, OAuth, TwitterHTTPError

2. We want readable code which can be debugged so we will use try and except. Replace errmsg in the the print statement with err to see actual error while debugging. I have used a dummy error message here as if we later write a hosted version, and an error occurs, the Auth details would get exposed on application crash and we don’t want that happening, so we simply mask it.

try:
...
except Exception as err:
errmsg = 'There has been an error.'
print(errmsg)

3. We need to provide the authentication details we had obtained while registering the application. Place this within try

try:
OAUTH_TOKEN = “enter within these quotes, do not remove these quotation marks”
OAUTH_SECRET = “enter within these quotes, do not remove these quotation marks”
CONSUMER_KEY = “enter within these quotes, do not remove these quotation marks”
CONSUMER_SECRET = “enter within these quotes, do not remove these quotation marks”
TWITTER_HANDLE = “Your twitter accounts handle without @, do not remove these quotation marks”
t = Twitter(auth=OAuth(OAUTH_TOKEN, OAUTH_SECRET,
CONSUMER_KEY, CONSUMER_SECRET))

4. Now that we have finished authentication, we can access tweets and our account, so lets go ahead and code the juicy part, the bot itself.

Note: All code occurs within the try block itself. Refer to complete code at https://github.com/dakshil/TwittterBot/blob/master/logic.py to get an idea of what goes where.

5. We create a new function called theBrain(). We first fetch the latest tweet containing our keyword. We keep count as 1 as we want only the latest tweet, you may modify it to any number(hence the loop in step 6).

def theBrain():
#The area where we can do whatever we want
#Fetch n number of tweets where n is given by count, having the keyword given in q
statement =t.search.tweets(q=”shit”, count=1)
#tweets are fetched in JSON format with a lot of related data
tweets = statement[‘statuses’]

6. Each fetched tweet is processed individually, the status(i.e. the actual tweet itself) is extracted from the extraneous data and converted to a string. We encode using utf-8 as the ascii format will cause errors for certain characters. You can use print to see what is the tweet you fetched, its okay if you skip this step but I highly recommend it as it helps visualize the process.

def theBrain():
statement =t.search.tweets(q=”shit”, count=1)
tweets = statement[‘statuses’]
#process each tweet individually
for statement in tweets:
text=str(statement['text'].encode("utf-8"))
print(text)

7. Next we replace the keyword with with a word of our choice. We store this string in a new variable as python strings are immutable.

def theBrain():
statement =t.search.tweets(q=”shit”, count=1)
tweets = statement[‘statuses’]
#process each tweet individually
for statement in tweets:
text=str(statement['text'].encode("utf-8"))
print(text)
textN=text.replace('shit','poop')
print(textN)

8. We now create the text we want to tweet. As we want to tweet back to the original tweeter, we mention them in the new tweet(alternately we could reply back to the tweet but lets not do that now). We first extract the twitter handle for that particular user and then create the tweet which we will send.

def theBrain():
statement =t.search.tweets(q=”shit”, count=1)
tweets = statement[‘statuses’]
#process each tweet individually
for statement in tweets:
text=str(statement['text'].encode("utf-8"))
print(text)
textN=text.replace('shit','poop')
print(textN)
handle=str(statement['user']['screen_name'])
sent='@' + handle + ' ' + textN
print sent

9. For the purpose of making this code easy to modify in the future, we want to separate the bots logic from the tweet sending mechanism. For this, we create a new function to send the tweet and call it from theBrain() and pass the variable “sent” to this new function which we will call “theTweet”.

def theBrain():
statement =t.search.tweets(q=”shit”, count=1)
tweets = statement[‘statuses’]
#process each tweet individually
for statement in tweets:
text=str(statement['text'].encode("utf-8"))
print(text)
textN=text.replace('shit','poop')
print(textN)
handle=str(statement['user']['screen_name'])
sent='@' + handle + ' ' + textN
print sent
theTweet(sent)

10. Lets create the function theTweet. Its pretty self explanatory. The status we want to use is stored in sent so we update our status using sent variable.

def theTweet(sent):
#This is the part which actually posts the tweet
if len(sent)<=140:
#Twitter allows only 140 character tweets
print(“tweetable”)
t.statuses.update(status=sent)
else:
print(“140 characters crossed”)

11. All that is left is to now call the theBrain function to get this code up and running. In option 1, we use an infinite loop here which runs every hour, however while doing this the first time, I suggest you avoid this and simply do option 2.

Option 1

from time import sleep
...
def main():
while True:
#This loop is merely to keep the code running. you may eliminate the above line and the sleep if you want to run the code every time or just test.
theBrain()
#To prevent abuse of the twitter API and usage limit, calling it only once an hour.
sleep(3600)
if __name__ == “__main__”:
main()

Option 2

def main():
theBrain()
if __name__ == “__main__”:
main()

Thats it. In 12 steps you have a Twitter bot which you can now tinker with further and build something better. You can find the entire project at https://github.com/dakshil/TwittterBot. Feel free to fork this repository or even contribute to it. In future articles I hope to show you how to host this bot online(Heroku) and even share some of my other twitter bots with with you or twitter analytics tutorials.

Hope you all enjoyed this and wish to hear from you.

--

--