Task 5: Use Python to post a message on Twitter.
Here’s how you can post a message on Twitter using Python with the tweepy
library:
Step 1: Install Tweepy
pip install tweepy
Step 2: Get Your Twitter API Keys
Go to the Twitter Developer Portal.
Create a project and app.
Note the following credentials:
API Key
API Key Secret
Access Token
Access Token Secret
Step 3: Write the Python Code
Save your credentials in a configuration file (config.py
):
API_KEY = "your_api_key"
API_KEY_SECRET = "your_api_key_secret"
ACCESS_TOKEN = "your_access_token"
ACCESS_TOKEN_SECRET = "your_access_token_secret"
import tweepy
import config
# Authenticate to Twitter
auth = tweepy.OAuthHandler(config.API_KEY, config.API_KEY_SECRET)
auth.set_access_token(config.ACCESS_TOKEN, config.ACCESS_TOKEN_SECRET)
# Create an API object
api = tweepy.API(auth)
# Post a tweet
try:
message = "Hello, Twitter! This is a tweet from Python. #PythonAutomation"
api.update_status(status=message)
print("Tweet posted successfully!")
except Exception as e:
print(f"Failed to post tweet: {e}")
Step 4: Run the Script
Run the main.py
file:
python main.py
Output
If everything is set up correctly, the message will appear as a tweet on your Twitter account.
Notes:
Ensure your app has write permissions in the Twitter Developer Dashboard.
Always keep your API keys and tokens secure.
For advanced use cases, like posting media or interacting with followers, explore the Tweepy Documentation.