Twitter is quite possibly the most broadly utilized informal community. For some associations and individuals, having an incredible Twitter presence is a vital factor in keeping their crowd locked in.
Part of having an incredible Twitter presence includes keeping your record dynamic with new tweets and retweets, following fascinating records and rapidly answering to your supporters’ messages. You can accomplish this work physically, however that can take a great deal of time. All things being equal, you can depend on a Twitter bot, a program that mechanizes all or part of your Twitter action. This will be a simple and quick instructional exercise to make a basic Twitter bot utilizing the Python language and the Tweepy library.
Twitter API
The Twitter API gives engineers admittance to the greater part of Twitter’s usefulness. You can utilize the API to peruse and compose data identified with Twitter substances like tweets, clients, and patterns.
Actually, the API uncovered many HTTP endpoints identified with:
- Tweets
- Retweets
- Preferences
- Direct messages
- Top choices
- Patterns
- Media
Tweepy, as we’ll see later, gives a way of summoning those HTTP endpoints without managing low-level subtleties.
The Twitter API utilizes OAuth, a generally utilized open approval convention, to verify every one of the solicitations. Prior to settling on any decision to the Twitter API, you really wanted to make and design your confirmation certifications. Later in this article, you’ll discover definite directions for this.
You can use the Twitter API to assemble various types of mechanization, like bots, investigation, and different apparatuses. Remember that Twitter forces specific limitations and strategies concerning what you can and can’t fabricate utilizing its API. This is done to ensure clients a decent encounter. The improvement of devices to spam, deceive clients, etc. is prohibited.
The Twitter API additionally forces rate limits regarding how every now and again you’re permitted to conjure API techniques. On the off chance that you surpass these cutoff points, you’ll need to stand by somewhere in the range of 5 and 15 minutes to have the option to utilize the API once more. You should think about this while planning and executing bots to stay away from superfluous pauses.
You can discover more data about the Twitter API’s approaches and cutoff points in its authority documentation:
What Is Tweepy?
Tweepy is an open-source Python bundle that gives you an exceptionally advantageous way of getting to the Twitter API with Python. Tweepy incorporates a bunch of classes and strategies that address Twitter’s models and API endpoints, and it straightforwardly handles different execution subtleties, for example,
- Information encoding and deciphering
- HTTP demands
- Results pagination
- OAuth verification
- Rate limits
- Streams
In the event that you weren’t utilizing Tweepy, you would need to manage low level subtleties having to do with HTTP demands, information serialization, confirmation, and rate limits. This could be tedious and inclined to blunder. All things being equal, because of Tweepy, you can zero in on the usefulness you need to construct.
Practically all the usefulness given by Twitter API can be utilized through Tweepy. The main current limit, as of rendition 3.7.0, is that Direct Messages don’t work as expected because of some new changes in the Twitter API.
Step 1:Import the Libraries
The Twitter API gives designers admittance to the greater part of Twitter’s usefulness. You can utilize the API to peruse and compose data identified with Twitter substances like tweets, clients, and patterns.
Arrangement a designer’s record on Twitter to get the tokens and keys.
Making Twitter API Authentication Credentials
As we have recently seen, the Twitter API necessitates that all solicitations use OAuth to validate. So you wanted to make the necessary confirmation certifications to have the option to utilize the API. These qualifications are four text strings:
- Consumer key
- Consumer secret
- Access token
- Access secret
In the event that you, as of now, have a Twitter client account, follow these means to make the key, token, and privileged insights. In any case, you need to join as a Twitter client prior to continuing.
Apply for a Twitter Developer Account
Go to the Twitter developer site to apply for a creator account. Here, you need to choose the Twitter client liable for this record. It ought to most likely be you or your association. This is what this page resembles:
For this situation, I decided to utilize my own record.
Twitter then, at that point, demands some data regarding how you intend to utilize the engineering account, as displayed beneath:
You need to determine the designer account name and regardless of whether you are intending to utilize it for individual purposes or for your association.
Stage 2: Create an Application
Twitter awards confirmation accreditations to applications, not accounts. An application can be any apparatus or bot that utilizes the Twitter API. So you really wanted to enroll your application to have the option to settle on API decisions.
To enroll your application, go to your Twitter applications page and select the Create an application choice.
You really wanted to give the accompanying data about your application and its motivation:
Application name: a name to recognize your application (like model bot)
Application portrayal: the motivation behind your application (for example, A model bot for a Real Python article).
Your or your application’s site URL: required, yet can be your own site’s URL since bots needn’t bother with a URL to work.
Utilization of the application: how clients will utilize your application, (for example, This application is a bot that will consequently react to clients).
Step 3: Create the Authentication Credentials
To create the authentication credentials, go to your Twitter apps page. Here’s what the Apps page looks like:
Here you’ll find the Details button of your app. Clicking this button takes you to the next page, where you can generate the credentials.
By selecting the Keys and tokens tab, you can generate and copy the key, token, and secrets to use them in your code:
After generating the credentials, save them to later use in your code.
You can test the credentials using the following snippet:
import tweepy
from tkinter import *consumer_key= ‘’consumer_secret= ‘’access_token= ‘’access_token_secret= ‘’auth = tweepy.OAuthHandler(consumer_key, consumer_secret)auth.set_access_token(access_token, access_token_secret)api = tweepy.API(auth)user = api.me()print(user.name)print(user.location)
Step 2: Setup the GUI
Here we are using labels to setup Search text and what response would you like to give for it.
root = Tk()
label1 = Label( root, text=”Search”)E1 = Entry(root, bd =5)label2 = Label( root, text=”Number of Tweets”)E2 = Entry(root, bd =5)label3 = Label( root, text=”Response”)E3 = Entry(root, bd =5)label4 = Label( root, text=”Reply?”)E4 = Entry(root, bd =5)label5 = Label( root, text=”Retweet?”)E5 = Entry(root, bd =5)label6 = Label( root, text=”Favorite?”)E6 = Entry(root, bd =5)label7 = Label( root, text=”Follow?”)E7 = Entry(root, bd =5)def getE1():return E1.get()def getE2():return E2.get()def getE3():return E3.get()def getE4():return E4.get()def getE5():return E5.get()def getE6():return E6.get()def getE7():return E7.get()
Step 3: Retweet, Follow, Reply
The function analyzes your response and does the intended action. It’s a simple switch statement with each response triggering a corresponding tweepy function.
def mainFunction():
getE1()search = getE1()getE2()numberOfTweets = getE2()numberOfTweets = int(numberOfTweets)getE3()phrase = getE3()getE4()reply = getE4()getE5()retweet = getE5()getE6()favorite = getE6()getE7()follow = getE7()if reply == “yes”:for tweet in tweepy.Cursor(api.search, search).items(numberOfTweets):try:#Replyprint(‘nTweet by: @’ + tweet.user.screen_name)print(‘ID: @’ + str(tweet.user.id))tweetId = tweet.user.idusername = tweet.user.screen_nameapi.update_status(“@” + username + “ “ + phrase, in_reply_to_status_id = tweetId)print (“Replied with “ + phrase)except tweepy.TweepError as e:print(e.reason)except StopIteration:breakif retweet == “yes”:for tweet in tweepy.Cursor(api.search, search).items(numberOfTweets):try:#Retweettweet.retweet()print(‘Retweeted the tweet’)except tweepy.TweepError as e:print(e.reason)except StopIteration:breakif favorite == “yes”:for tweet in tweepy.Cursor(api.search, search).items(numberOfTweets):try:#Favoritetweet.favorite()print(‘Favorited the tweet’)except tweepy.TweepError as e:print(e.reason)except StopIteration:breakif follow == “yes”:for tweet in tweepy.Cursor(api.search, search).items(numberOfTweets):try:#Followtweet.user.follow()print(‘Followed the user’)except tweepy.TweepError as e:print(e.reason)except StopIteration:breaksubmit = Button(root, text =”Submit”, command = mainFunction)label1.pack()E1.pack()label2.pack()E2.pack()label3.pack()E3.pack()label4.pack()E4.pack()label5.pack()E5.pack()label6.pack()E6.pack()label7.pack()E7.pack()submit.pack(side =BOTTOM)root.mainloop()
Found this article useful? Follow me (Rahula Raj) on Medium and check out my most popular articles below! Please 👏 this article to share !
_________________________________*****_____________________________
Open for collaboration
Contact me at rahular2020@iimbg.ac.in.
_________________________________*****_____________________________