Python Twitter Automation for Posting Tweet

Python Twitter Automation for Posting Tweet

In this article we are going to see how to use twitter api and automate the task of posting tweet on twitter.

We can classify this task into 2 sub task.
1. Apply for twitter developer account and create 4 secret keys which will be required later.
2. write actual script for tweet posting.

we will see each of them.

1. Apply for twitter developer account and create 4 secret keys which will be required later.
first go to twitter developer website.

Click on Apply for Access.

After this Fill all the Details.

After Filling all the details, Submit it.

After submitting you have to verify your account. For this twitter will sent a verification email. 
When account is verified successfully then you will receive an email from twitter asking again, the use of twitter api like you have filled during registration phase. 
you have to reply that email.
"" I want to use the developer api to explore some features of twitter automation and its features. 
I am thinking to create a automation program using python as a part of research

This is the main purpose why i am asking the api 
Kindly provide me 

After this your Developer account will be Approved with in 24-48 hour. 
When developer account is approved then you have to login in account and create a app and Generate your secret keys and store it.

Now the first phase is completed.

Let's come to second Phase

To run this script you will need following modules
install these modules using pip

This is a script to post tweet on Twitter using Twitter API. 
it has feature of command line Argument

for Running the Script : 

1 . # python 'filename' --url 'your url link as string' 

2 . # python 'filename' --path 'path of excel workbook' --time 'time interval in seconds as integer'
    here --time argument is optional if you did not pass the time argument it will take 10 seconds as default

Note  : 
1 . Make sure pass pass atleast 1 argument (--url or --path)
    if anyone failed to pass both argument then the program will exit automatically

2. Only Excel book is supported and in excel book make sure that your link is in 1st column

3. if you pass both of the first two arguments then it will post tweet from both the function
    first it will post tweet from url after that it post tweet from excel workbook

if any doubt is there or any problem in the script you face then 
mail me at : ''


import argparse
import random
import tweepy
import openpyxl
import time

class Twitter:

def create_api(self):
# these keys generated from twitter developer account
'your API Key'
'Your Access Token'
'Your Access Token Secrets'

# setting login details with twitter
auth = tweepy.OAuthHandler(API_KEY, API_SECRET_KEY)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

# creating a variable which will help to verify login details with twiiter
# and returns the API object which will be used in future to tweet
api = tweepy.API(auth, wait_on_rate_limit=
True, wait_on_rate_limit_notify=True)
"Error in verifying Credentials")
return api

# Setting some trendings tags
# a function which will return some random trending tags
def trending_part(self):
trending_list =
#python #Airtel #programming #deeplearning #pythoncode #coding #css #datascientist #cppsecrets #100DaysOfCode #100DaysOfMLCode #100DaysOfPython #100DaysOfCplusplus #TREASURE #BlackTechTwitter #MachineLearning #AI #BigData #cyber #Python #AI #programming #deeplearning #pythoncode #coding #CSS #datascientist #cppsecrets #100DaysOfCode #100DaysOfMLCode #100DaysWithCppsecrets #100DaysOfPython #nifity #python #ai #programming #deeplearning #pythoncode #coding #css #datascientist #cppsecrets #100DaysOfCode #100DaysOfMLCode #100DaysWithCppsecrets #100DaysOfPython #100DaysOfCplusplus

# split the above string into a list
list1 = trending_list.split(
' ')

# generate a random number between 10 to 12
# (random.randint(a,b) generates random number between a and (b-1))
number = random.randint(
10, 13)

# picking some random tags from list
trend = random.sample(list1, number)

# join the list to return trends as a string
trend =
' '.join(trend)
return trend

def update_tweet(self, link):
api = Twitter.create_api(self)
# Verify credentials from twitter
trends = Twitter.trending_part(self)
# get list of some hastags
content =
'\n' + link + '\n\n' + '#cppsecrets' + trends

# Method to upload tweet
# print(content)
"Tweet Updated Successfully")

except Exception as e:

class CommandLineParser:

def __call__(self):

# Create object of the Argument Parser
parser = argparse.ArgumentParser(description=
"Script to get employee details")

# Create a group for requirement
required_arguments = parser.add_argument_group(
'Required command line arguments')

# URL argument as --url
"--url", type=str, action='store', help="Enter URL")

# Path argument as --path
"--path", type=str, action='store', help="Enter Path")

# time interval as --time
"--time", type=int, action='store', help="Enter time lapse")

# Parse the arguments and get all the values in the form of namespace.
# Here args is of namespace and values will be accessed through tag names
args = parser.parse_args()

# it will return namespace of arguments
return args

# a function to update tweet when --path argument is passed in console
# we can pass time_lapse in the argument as well using --time. by default it is set to 10
def update_tweet_using_path(path, time_lapse = 10):

# create a instance of twitter
twitter = Twitter()

# load the excel workbook from specified path
wb = openpyxl.load_workbook(path)

# get active sheet from the workbook
sheet =

# loop till last rows and get the value of first column from each rows
# link should be in first column so that script is able to get the link from excel sheet
for i in range(1, sheet.max_row + 1):
link = sheet.cell(row=i, column=
# twitter.update_tweet(link) this line should be uncommented when using script in real time

def main():

# Create a instance of commandlineparser class so that we can use entered arguments
a = CommandLineParser()()
if (a.url != None or a.path != None): # if both of the first 2 argument is not recieved then the script will be ended automatically so make sure to pass atleast one argument
if (a.url != None):
twitter = Twitter()
# this line should be uncommented when using script in real time
# this line should be uncommented when using script in real time
# print("url section is working")
if (a.path != None):
update_tweet_using_path(a.path, a.time)

'No argument recieved...')

if __name__ == '__main__':

Sample code to run the script
python --url "your url"
python --path 'path of excel file'