Description :
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.
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
Thanks
""
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
Requirements :
To run this script you will need following modules
openpyxl==3.0.6
tweepy==3.10.0
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 : 'gorakhgupta343@gmail.com'
Code :
import argparse
import random
import tweepy
import openpyxl
import time
class Twitter:
def create_api(self):
API_KEY = 'your API Key'
API_SECRET_KEY = 'Your API SECRET KEY'
ACCESS_TOKEN = 'Your Access Token'
ACCESS_TOKEN_SECRET = 'Your Access Token Secrets'
auth = tweepy.OAuthHandler(API_KEY, API_SECRET_KEY)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
try:
api.verify_credentials()
except:
print("Error in verifying Credentials")
return api
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
"""
list1 = trending_list.split(' ')
number = random.randint(10, 13)
trend = random.sample(list1, number)
trend = ' '.join(trend)
return trend
def update_tweet(self, link):
try:
api = Twitter.create_api(self)
trends = Twitter.trending_part(self)
content = '\n' + link + '\n\n' + '#cppsecrets' + trends
api.update_status(content)
print("Tweet Updated Successfully")
return
except Exception as e:
print(e)
return
class CommandLineParser:
def __call__(self):
parser = argparse.ArgumentParser(description="Script to get employee details")
required_arguments = parser.add_argument_group('Required command line arguments')
required_arguments.add_argument("--url", type=str, action='store', help="Enter URL")
required_arguments.add_argument("--path", type=str, action='store', help="Enter Path")
required_arguments.add_argument("--time", type=int, action='store', help="Enter time lapse")
args = parser.parse_args()
return args
def update_tweet_using_path(path, time_lapse = 10):
twitter = Twitter()
wb = openpyxl.load_workbook(path)
sheet = wb.active
for i in range(1, sheet.max_row + 1):
link = sheet.cell(row=i, column=1).value
print(link)
time.sleep(time_lapse)
def main():
a = CommandLineParser()()
if (a.url != None or a.path != None):
if (a.url != None):
twitter = Twitter()
twitter.update_tweet(a.url)
if (a.path != None):
update_tweet_using_path(a.path, a.time)
else:
print('No argument recieved...')
return
return
if __name__ == '__main__':
main()
Output :
Sample code to run the script
python script.py --url "your url"
or
python script.py --path 'path of excel file'
Comments