twitter bot

Contributed by – Harshit Roy

  1. What is a twitter bot
  2. Setup Requirements
  3. Creating the GUI
  4. Creating the bot

What is a Twitter Bot

Twitter bots are automated user accounts that interact with Twitter using an application programming interface (API). These bots are programmed to perform tasks normally associated with human interaction such as

  •  following users,
  •  like tweets,
  •  direct message (DM) other users, 
  • and, most importantly, they can tweet content, and retweet anything posted by a specific set of users or featuring a specific hashtag. 

Many of these bots perform important tasks, such as tweets about earthquakes in real-time and serve as part of a warning system. In the case of a campaign, however, political or otherwise, they are normally used to generate mass interest in specific content by spreading messages at a rate that isn’t possible with human users. A research paper produced by Indiana University in March 2017 found that 15 percent of all Twitter accounts were bots. 

In this tutorial, we are going to make a bot that can like posts related to a specific hashtag.

Setup Requirements for Twitter Bot

Follow the steps below to fulfill the requirements for designing and running the bot successfully.

Install Python: We will use the Python programming language to create the bot. Incase Python is not already installed, follow these steps:

  1. Download the installer from here 
  2. Install it

. Alternatively, you can check out this article to get a step by step guide for installing python.

Download Webdriver: WebDriver is a remote control interface that enables introspection and control of user agents. It provides a way for out-of-process programs to remotely instruct the behavior of web browsers. In this tutorial, we use a driver called ” gecko” which is designed for Mozilla firefox. Follow the steps below to download and use it

  1. Download the appropriate version from here
  2. Extract the executable file (.exe) file from the zip and paste it in the following folder. Go to your C drive and follow this path
  3. Users→” Your user folder”→AppData→Local→Programs→Python→Python36-32(“the name of the folder can be slightly different for different users”)
  4. Paste the .exe file in the Python36-32 folder.

Note that the Mozilla Firefox should be installed on your PC for this tutorial to run.You can download it from here

Now let us install the necessary packages required:

Install Selenium: Selenium is an open-source tool that automates web browsers. It provides a single interface that lets you write test scripts in programming languages like Ruby, Java, NodeJS, PHP, Perl, Python, and C#, among others.

We use the Selenium web driver for the purpose of logging in into an account and scrolling the page of the feeds. To install selenium, open the command prompt, and type this code and press enter.

pip install selenium

Install Tkinter: Tkinter is the standard GUI library for Python. Python, when combined with Tkinter, provides a fast and easy way to create GUI applications.

In this program, we use Tkinter to get the username and password of the user. Also, the user puts the specific hashtag for which the posts are to be liked. To install Tkinter, open the command prompt and type this code and press enter.

pip install tkintertable


Install Pyautogui: PyAutoGUI lets your Python scripts control the mouse and keyboard to automate interactions with other applications.

We use Pyautogui to click on the like button. To install Pyautogui, open the command prompt, and type this code and press enter.

pip install PyAutoGUI

Creating GUI

We create a form using the Tkinter module to get information about the user. In the form, we ask the user email address, user password, and the keyword for which the posts are to be liked. Here is the code for creating the form:

from tkinter import *
window=Tk()
#set dimensions of form window
window.geometry("700x200") #change the values to change size of window

#Get email from the user and store it in entry1
emails=Label(window,text="Enter your email here",font='times 24 bold')
emails.grid(row=0,column=0) #define loc of the label on from
entry1=Entry(window)
entry1.grid(row=0,column=6)#define loc of the entry on from

#Get password  from the user and store it in entry2
password=Label(window,text="Enter your password here",font='times 24 bold')
password.grid(row=2,column=0)
entry2=Entry(window,show="*")
entry2.grid(row=2,column=6)

#Get hashtag from the user and store it in entry3
hashtag=Label(window,text="Enter the seach keyword here",font='times 24 bold')
hashtag.grid(row=3,column=0)
entry3=Entry(window)
entry3.grid(row=3,column=6)

b1=Button(window,text=" GO ",command=execute,width=12,bg='grey')
b1.grid(row=6,column=0)
window.mainloop()

 Creating the Bot

Finally, let us create an automated bot to like tweets for us automatically. First, create a class, twiiter_bot which contains all the necessary functions. The objects of this class need three attributes, viz- username (email address of account), password and the web driver we are using

class twitter_bot:
	def __init__(self,username,password):
		self.username=username
		self.password=password
		self.bot=webdriver.Firefox()

Next, we define a login function which performs the following task:

  • Open the browser and open twitter
  • Login using the credentials from the form
def login(self):
		bot=self.bot
		bot.get('https://twitter.com/')
		time.sleep(5)
   		#find elements for username and password in the webpage
		email=bot.find_element_by_name('session[username_or_email]')
		password=bot.find_element_by_name('session[password]')
		email.clear() #clear the session variable incase it contains anything
		password.clear()
		email.send_keys(self.username)
		password.send_keys(self.password)
		password.send_keys(Keys.RETURN)
		time.sleep(10)

Note that we have used the sleep function to delay the process. This is done so that the process may seem natural and twitter does not detect the bot.

Next, we define a function  like_tweet  which takes the keyword as an argument. This function searches the given keyword as a hashtag and likes the posts by taking the mouse to the location with a heart image (like button) and clicking on it. 

You can use the snippet tools to crop this image from the twitter page and save it in the same folder as the python file. Also, this page automatically scrolls down to load new tweets until interrupted.

def like_tweet(self,entry3):
	bot=self.bot
        #search the twitter with the hashtag keyword
	bot.get('https://twitter.com/search?q='+str("%23" + entry3)+'&src=typed_query')
		
	while True:
		#locate like button on screen	
		if pyautogui.locateCenterOnScreen('1.png'):
                        #click on like button         
			pyautogui.click(pyautogui.locateCenterOnScreen('1.png'),duration=1)
		else:
                       #move cursor to the top of screem
			pyautogui.moveTo(650,150)
			pyautogui.scroll(-25)#scroll down
			time.sleep(1)

Here is the code for the whole script:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import pyautogui
from tkinter import *



class twitter_bot:
	def __init__(self,username,password):
		self.username=username
		self.password=password
		self.bot=webdriver.Firefox()


	def login(self):
		bot=self.bot
		bot.get('https://twitter.com/')
		time.sleep(5)
		email=bot.find_element_by_name('session[username_or_email]')
		password=bot.find_element_by_name('session[password]')
		email.clear()
		password.clear()
		email.send_keys(self.username)
		password.send_keys(self.password)
		password.send_keys(Keys.RETURN)
		time.sleep(10)


	def like_tweet(self,entry3):
		bot=self.bot
		bot.get('https://twitter.com/search?q='+str("%23" + entry3)+'&src=typed_query')
		
		while True:
			#use the indentation as shown in last code block
			if pyautogui.locateCenterOnScreen('1.png'):
				pyautogui.click(pyautogui.locateCenterOnScreen('1.png'),duration=1)
			else:
				pyautogui.moveTo(650,150)
				pyautogui.scroll(-25)
				time.sleep(1)
			
			
		


def execute():
	log=twitter_bot(str(entry1.get()),str(entry2.get()))
	log.login()
	log.like_tweet(entry3.get())



window=Tk()
window.geometry("700x200")
emails=Label(window,text="Enter your email here",font='times 24 bold')
emails.grid(row=0,column=0)
entry1=Entry(window)
entry1.grid(row=0,column=6)


password=Label(window,text="Enter your password here",font='times 24 bold')
password.grid(row=2,column=0)
entry2=Entry(window,show="*")
entry2.grid(row=2,column=6)


hashtag=Label(window,text="Enter the seach keyword here",font='times 24 bold')
hashtag.grid(row=3,column=0)
entry3=Entry(window)
entry3.grid(row=3,column=6)

b1=Button(window,text=" GO ",command=execute,width=12,bg='grey')
b1.grid(row=6,column=0)
window.mainloop()

Output:

As we can see in the video, the mouse goes to each like button and clicks it while the page is scrolling down. While the already liked posts are not affected in any way.

This brings us to the end of this tutorial where we created a twitter bot that can like posts for you related to a hashtag.

Learn python from expert faculty under Great Learning’s PG program in Artificial Intelligence and Machine Learning. You do not need any prior technical background to pursue this course and understand python’s functioning.

1

2 COMMENTS

  1. Please you also post some packages for Robotic process automation that is needed for Industrial automation particular to banking domain

LEAVE A REPLY

Please enter your comment!
Please enter your name here

1 × four =