Python script that tweets for you| Daily Python #26

This article is a tutorial to build a bot that tweets inspirational quotes every minute using Python.

This article is a part of Daily Python challenge that I have taken up for myself. I will be writing short python articles daily.

Requirements:

  1. Python 3.0
  2. Pip

Install the following packages:

  1. tweepy — Library that provides easy access to Twitter APIs
  2. requests — Library to making HTTP requests.
  3. json — Library to handle JSON objects
  4. time
pip install tweepy requests

Let’s import the required modules

import requests
import tweepy
import time
import json

The first step is to set up the Twitter Bot using ‘tweepy’

Note: Follow the instructions in the following article and create your app

After you have created your twitter application and generated the API Keys and Access tokens, define a function to set up the twitter bot.

def setup_Bot():
consumerKey = "YOUR_API_KEY"
consumerSecret = "YOUR_API_KEY_SECRET"
accessToken = "YOUR_ACCESS_TOKEN"
accessTokenSecret = "YOUR_ACCESS_TOKEN_SECRET"
auth = tweepy.OAuthHandler(consumerKey, consumerSecret)
auth.set_access_token(accessToken, accessTokenSecret)
api = tweepy.API(auth)
return api

Now, let’s write a function that will fetch an inspirational quote for the bot

The following API provides random inspirational quotes:

We need to make a call to this method in order to fetch a random inspirational quote for our twitter bot.

def get_Quote():
params = {
'method':'getQuote',
'lang':'en',
'format':'json'
}
res = requests.get('http://api.forismatic.com/api/1.0/',params)
jsonText =json.loads(response.text)
return jsonText["quoteText"],jsonText["quoteAuthor"]

Using the JSON module we can convert the response text to a JSON object and access its individual key-value pairs.

Finally, let’s write a loop that will tweet an inspirational quote every minute

api = setup_Bot()
while True:
try:
quote,author = get_Quote()
status = quote+" -"+author+"\n"+"#python \
#dailypython #twitterbot #pythonquotes #programming"
print('\nUpdating : ',status)
api.update_status(status=status)
print("\nGoing to Sleep for 1 min")
time.sleep(60)
except Exception as ex:
print(ex)
break
The output of the twitter bot
Snip of the tweets posted by the bot

Modify this code and make your twitter bot do what you want. Read the terms and conditions given by twitter for developing twitter bots.

I hope this article was helpful, do leave some claps if you liked it.

Follow the Daily Python Challenge here:

Yet Another Developer Developer!