DeveloperBreeze

Twitter Developer Account Development Tutorials, Guides & Insights

Unlock 1+ expert-curated twitter developer account tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your twitter developer account skills on DeveloperBreeze.

Automate Tweet Posting with a Python Twitter Bot

Tutorial August 08, 2024
python

Let's create a Python script to automate tweet posting. Copy the following code into a new Python file (e.g., twitter_bot.py):

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)