twitterbot
This is an example Twitter bot that uses the tweepy library. It was written for an article that can be read on dev.to.
This website collects cookies to deliver better user experience
Read + Write + Read and post direct messages
permissions by going to this screen:API key/secret
and the access token/secret
. I recommend putting them in a text document, as you cannot access them again once they are generated.Hello world!
├───twitterbot
└───.env # File that contains our keys
└───main.py # Our main application
└───requirements.txt # The packages we will be using
$ sudo mkdir twitterbot
cd
into the directory using:$ cd twitterbot
main.py
and requirements.txt
.tweepy==3.10.0
python-dotenv==0.17.1
$ pip install -r requirements.txt
tweepy
is the library that utilizes the Twitter API, and python-dotenv
is the library that allows environment variables to be utilized in your program..env
and paste the following with the keys you generated in the earlier steps:consumer_key=XXX # Found in the API/Secret section
consumer_secret=XXX # Found in the API/Secret section
access_token=XXX # Found in the Access Token/Secret section
access_token_secret=XXX # Found in the Access Token/Secret section
main.py
file, add the following:import os
import tweepy
from dotenv import load_dotenv
# Loads the .env file for the credentials
load_dotenv()
# Credentials set in the .env file
consumer_key = os.environ.get('consumer_key')
consumer_secret = os.environ.get('consumer_secret')
access_token = os.environ.get('access_token')
access_token_secret = os.environ.get('access_token_secret')
tweepy
library to use these credentials and authenticate with Twitter:auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
# Create API object
api = tweepy.API(auth)
# Checks if the credentials entered are correct
def authenticate():
if not api.verify_credentials():
print('Authentication: FAILED')
return False
else:
print('Authentication: OK')
return True
main
function:def tweet():
# If authenticate returns true, execute the following
if authenticate():
# Calls the API to tweet the following
api.update_status('Hello World!')
print('Tweet has been sent!')
# If authenticate returns false, print the following
else:
print('Tweet has not been sent.')
if __name__ == "__main__":
tweet()
python main.py
and you should see the following:Authentication: OK
Tweet has been sent!
This is an example Twitter bot that uses the tweepy library. It was written for an article that can be read on dev.to.