25 – Real-World Python Projects – Twitter Bot

🎯 Project Objective

To create a Python-based Twitter Bot that can automatically post tweets, reply, like posts, and perform scheduled actions using the Tweepy library.


🧩 1. Overview

Social media automation is widely used by:

  • Businesses β†’ Auto-post promotions or news
  • Creators β†’ Share daily updates automatically
  • Analysts β†’ Track trending hashtags and engagement

We’ll build a safe, API-based bot that follows Twitter’s official rules.


βš™οΈ 2. Requirements and Setup

We’ll use:

LibraryPurpose
tweepyAccess the Twitter API easily
pandasManage tweet logs (optional)
scheduleSchedule regular tweets

βœ… Auto-install if missing

import subprocess, sys

def install(pkg):
    try:
        __import__(pkg)
    except ImportError:
        subprocess.check_call([sys.executable, "-m", "pip", "install", pkg])

install("tweepy")
install("pandas")
install("schedule")

πŸ”‘ 3. Get Your Twitter API Keys

You’ll need to:

  1. Go to developer.x.com
  2. Create a project and get:
    • API_KEY
    • API_KEY_SECRET
    • ACCESS_TOKEN
    • ACCESS_TOKEN_SECRET

Then, store them securely (e.g., in a .env file).


πŸ”— 4. Authentication

import tweepy
import os

API_KEY = "your_api_key"
API_SECRET = "your_api_secret"
ACCESS_TOKEN = "your_access_token"
ACCESS_SECRET = "your_access_secret"

auth = tweepy.OAuthHandler(API_KEY, API_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
api = tweepy.API(auth)

# Test authentication
try:
    user = api.verify_credentials()
    print(f"βœ… Authenticated as {user.name}")
except Exception as e:
    print("❌ Authentication failed:", e)

🐦 5. Post a Tweet

def post_tweet(message):
    api.update_status(message)
    print(f"βœ… Tweet posted: {message}")

πŸ§ͺ Example:

post_tweet("Hello world! This is my first automated tweet using #Python 🐍")

πŸ’¬ 6. Reply to a Tweet

def reply_to_tweet(tweet_id, reply_message):
    api.update_status(
        status=reply_message,
        in_reply_to_status_id=tweet_id,
        auto_populate_reply_metadata=True
    )
    print("βœ… Replied successfully!")

πŸ§ͺ Example:

reply_to_tweet("1234567890123456789", "Thanks for sharing this! πŸš€")

❀️ 7. Like & Retweet

def like_and_retweet(tweet_id):
    api.create_favorite(tweet_id)
    api.retweet(tweet_id)
    print("βœ… Liked and retweeted!")

πŸ§ͺ Example:

like_and_retweet("1234567890123456789")

πŸ” 8. Search and Interact with Tweets

def search_and_interact(keyword, limit=5):
    for tweet in tweepy.Cursor(api.search_tweets, q=keyword, lang="en").items(limit):
        try:
            print(f"πŸ’¬ {tweet.user.name}: {tweet.text[:50]}...")
            api.create_favorite(tweet.id)
            api.retweet(tweet.id)
            print("βœ… Liked and retweeted!")
        except Exception as e:
            print("⚠️ Error:", e)

πŸ§ͺ Example:

search_and_interact("#Python", 3)

⏰ 9. Schedule Tweets Automatically

import schedule, time

def scheduled_tweet():
    post_tweet("This is a scheduled tweet sent by my Python bot ⏰ #Automation")

schedule.every(2).hours.do(scheduled_tweet)

print("πŸ€– Twitter bot running... (Press Ctrl+C to stop)")
while True:
    schedule.run_pending()
    time.sleep(60)

βœ… Automatically posts every 2 hours!


🧰 10. Interactive Menu

def main():
    print("\n🐦 Twitter Bot Menu")
    print("1. Post a Tweet")
    print("2. Reply to a Tweet")
    print("3. Like & Retweet")
    print("4. Search & Interact")
    print("5. Schedule Tweet")
    print("6. Exit")

    choice = input("Enter your choice: ")

    if choice == "1":
        msg = input("Enter tweet text: ")
        post_tweet(msg)

    elif choice == "2":
        tweet_id = input("Enter Tweet ID: ")
        reply = input("Enter reply message: ")
        reply_to_tweet(tweet_id, reply)

    elif choice == "3":
        tweet_id = input("Enter Tweet ID: ")
        like_and_retweet(tweet_id)

    elif choice == "4":
        keyword = input("Enter search keyword: ")
        search_and_interact(keyword)

    elif choice == "5":
        scheduled_tweet()
    else:
        print("πŸ‘‹ Exiting...")
if __name__ == "__main__":
    main()

βš™οΈ 11. Best Practices

βœ… Respect Twitter’s API rate limits
βœ… Avoid spamming or repetitive actions
βœ… Use scheduling instead of loops for timing
βœ… Keep API keys secret using .env files
βœ… Test in a private dev account first


πŸ’‘ 12. Enhancement Ideas

FeatureDescription
🧠 AI Auto-TweetsUse OpenAI API to generate tweets automatically
πŸ“Š AnalyticsTrack likes, retweets, engagement in CSV
🧾 LogsSave all tweets and replies to a log file
πŸ“… Smart SchedulerPost at peak times for engagement
πŸ–₯ GUIAdd Tkinter dashboard for easy bot control

βœ… Summary

FeatureDescription
🐍 AutomationTweet, reply, like, and retweet
πŸ” SearchFind tweets by keyword
⏰ SchedulePost automatically
πŸ’Ύ LoggingKeep track of actions
βš™οΈ ExpandableCan integrate AI or analytics

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *