import tweepy
import time
from datetime import datetime, timedelta
import random
# Twitter API credentials
CONSUMER_KEY = 'your_consumer_key'
CONSUMER_SECRET = 'your_consumer_secret'
ACCESS_TOKEN = 'your_access_token'
ACCESS_TOKEN_SECRET = 'your_access_token_secret'
# Authenticate to Twitter
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
# Create API object
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
# List of tweets to post
tweets = [
"Hello, Twitter! This is tweet number 1.",
"Another day, another tweet! #Python",
"Automating tweets with Python is fun!",
"Tweeting at random times using Python.",
# Add more tweets here
]
# Function to post a tweet
def post_tweet(tweet):
try:
api.update_status(tweet)
print(f"Tweeted: {tweet}")
except tweepy.TweepError as e:
print(f"Error: {e.reason}")
# Schedule tweets
def schedule_tweets(tweets, num_tweets=20, hours_range=(8, 22)):
today = datetime.now()
start_time = today.replace(hour=hours_range[0], minute=0, second=0, microsecond=0)
end_time = today.replace(hour=hours_range[1], minute=0, second=0, microsecond=0)
for _ in range(num_tweets):
# Select a random tweet
tweet = random.choice(tweets)
# Calculate the random time to post
random_seconds = random.randint(0, int((end_time - start_time).total_seconds()))
post_time = start_time + timedelta(seconds=random_seconds)
# Wait until the post time
wait_time = (post_time - datetime.now()).total_seconds()
if wait_time > 0:
time.sleep(wait_time)
# Post the tweet
post_tweet(tweet)
# Start scheduling tweets
schedule_tweets(tweets)
- Authentication: The script uses Tweepy to authenticate with Twitter using your credentials.
- Tweet List: You can prepare a list of tweets you want to post automatically.
- Post Function: The
post_tweet
function sends a tweet using the Twitter API. - Scheduling: The
schedule_tweets
function schedules tweets at random times within a specified range (8 AM to 10 PM by default).