Python script that tweets for you| Daily Python #26

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’

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

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"]

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

Follow the Daily Python Challenge here:

--

--

--

Yet Another Developer Developer!

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to setup dashboard using Elastic-Search, Kibana & Nginx

The End of Magento 1 Support — What Are Your Options?

Engineering Design Project: Obstacle Course Navigation

The Self-Taught Developer’s Guide On How to Code on Their Own

Solution to HackerRank’s: Jumping on the Clouds

Bad Agile Is Injurious To Your Product’s Health

Simple ways to manipulate datetime variables with pandas

Generic Analytics Manager

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ajinkya Sonawane

Ajinkya Sonawane

Yet Another Developer Developer!

More from Medium

How to Print Alphabet J in Python?

What Is Python Used for — 2022 Guide for Business Owners

Generating Passwords With Python

Image of a laptop screen with VSCode window open

Datatypes in python and typecasting