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

Orbit X- Case study: Creating a management portal during the pandemic

Web Developer Ignition: Visual Clone of FabIndia.com

Frontend Insights — January

Flutter Widgets (Grid View) The Whole Picture

Home IoT Part 1 — Cluster Setup

The first step into emulation

Binho Host Adapter with I2C and Python

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

My Journey with Python: Day 1 (and a half).

Why Learn Python? Reasons and Benefits of Learning Python

You will never misunderstood PYTHON’S *args and **kwargs again.

Getting started Python 101: Ultimate python basics.