Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Latest commit

Β 

History

41 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🐦 Twitter Sentiment Analysis & Bot Detection

A production-ready Python pipeline that analyzes tweet sentiment and detects bot accounts using machine learning, with real-time Discord bot integration.

Python 3.8+ License: MIT


🎯 Project Overview

This end-to-end NLP system combines sentiment analysis, bot detection, and cryptographic model verification into a production-ready application. It demonstrates expertise in:

  • Machine Learning β€” Training and deploying XGBoost classifiers for binary classification (bot/human)
  • NLP β€” Text processing with NLTK, TextBlob for sentiment scoring, and feature engineering
  • API Integration β€” Twitter API v2 (Tweepy), Discord.py for real-time bot interaction
  • Security β€” RSA cryptographic signatures for model integrity verification
  • Software Engineering β€” Modular architecture, data pipelines, configuration management

Key Capabilities

Feature Description
Sentiment Classification Analyzes tweet polarity (positive/negative/neutral) using TextBlob and trained ML models
Bot Detection Identifies automated Twitter accounts with 13-feature XGBoost classifier
Model Verification Cryptographic RSA signatures ensure model integrity and prevent tampering
Discord Integration Real-time sentiment queries through interactive Discord commands
Data Pipeline Automated workflow: data collection β†’ feature engineering β†’ model training β†’ deployment

The Bot in Action

The Discord bot posting live results in a channel: each embed reports tweet sentiment plus a probability distribution over bot-likelihood categories for the tweet's author

Scheduled task output in Discord: each embed pairs the tweet's sentiment classification with the author's bot-probability breakdown from the XGBoost classifier.


πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Twitter API    β”‚ (Tweepy - API v2)
β”‚  (Real tweets)  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚
         β–Ό
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚ GenerateExpandedTwitterDataset.py      β”‚ Extract user metrics & tweet data
    β”‚ (13 features: followers, verified, etc)β”‚
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
             β”‚
             β–Ό
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚ GenerateModel.ipynb                β”‚ Train XGBoost classifier
    β”‚ (Amazon Reviews + Twitter data)    β”‚ Test with multiple algorithms
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
             β”‚
             β–Ό
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚ SignPickle.py / VerifyPickle.py   β”‚ RSA-sign model.pickle
    β”‚ (Cryptography - model security)    β”‚ Prevent unauthorized modifications
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
             β”‚
             β–Ό
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚ TweetSentimentAnalysis.py          β”‚ Load & verify signed model
    β”‚ (Production inference)             β”‚ Classify new tweets/users
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
             β”‚
             β–Ό
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚ Discord Bot (discord.py)           β”‚ User-facing CLI interface
    β”‚ (Real-time predictions)            β”‚ Real-time sentiment queries
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ“ˆ Model Performance

Evaluated on 35,874 Twitter accounts (11,923 bots / 23,951 humans) with a 70/30 held-out test split. Class imbalance is handled with XGBoost's scale_pos_weight, trading some precision for higher bot recall β€” preferable for a screening tool.

Metric Held-out test (n = 10,763)
ROC AUC 0.890
Accuracy 81.8%
Precision (bot) 71.6%
Recall (bot) 76.6%
F1 Score 74.0%
5-fold CV AUC 0.891 Β± 0.003
ROC curves for each of 5 cross-validation folds with mean AUC 0.891 Confusion matrix on the held-out test set: 6,024 true humans, 2,785 true bots, 1,102 false positives, 852 false negatives Feature importance of the deployed XGBoost model β€” the network metric (log followers times log following) dominates

The engineered network feature (log(followers) Γ— log(following)) carries the most signal by a wide margin β€” bots tend to follow aggressively while attracting few followers, and the log-product separates that pattern better than either raw count. Feature importances are read from the deployed Resources/model.pickle; curves and metrics reproduce the evaluation protocol in Scripts/GenerateModel.ipynb. Regenerate all figures with:

python Scripts/GenerateEvalFigures.py

πŸ› οΈ Tech Stack

Category Technologies
Language Python 3.8+
ML & NLP XGBoost, Scikit-learn, TensorFlow, NLTK, TextBlob
Data Processing pandas, NumPy, Matplotlib, Seaborn, Plotly, WordCloud
APIs & Integration Tweepy (Twitter API v2), discord.py, aiohttp
Security & Cryptography cryptography (RSA), PyYAML
Utilities pytz (timezone handling), pickle (model serialization)

πŸš€ Getting Started

Prerequisites

Installation

  1. Clone the repository:

    git clone https://github.com/vondraysanford/TwitterSentimentAnalysisBot.git
    cd TwitterSentimentAnalysisBot
  2. Create and activate a virtual environment (recommended):

    python -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
  3. Install dependencies:

    pip install -r requirements.txt
  4. Configure API Credentials:

    # Copy the example config
    cp Resources/Config.example.yaml Resources/Config.yaml

    Edit Resources/Config.yaml and add your credentials:

    discord_api:
      client: "YOUR_DISCORD_BOT_TOKEN_HERE"
    
    search_tweets_api:
      bearer_token: "YOUR_TWITTER_BEARER_TOKEN_HERE"

    ⚠️ Security:

    • Never commit Config.yaml to version control
    • It's already listed in .gitignore to prevent accidental credential leaks
    • Generate new tokens if this repo was ever public with real credentials

πŸ“– Usage Guide

1. Generate Training Dataset

Extract user metrics and tweet data from Twitter:

python Scripts/GenerateExpandedTwitterDataset.py

Output: Resources/twitter_human_bots_dataset.csv with 17 engineered features:

  • Account age, verification status, follower/following counts
  • Tweet frequency, network metrics, acquisition rates

2. Train the Model

Open and run the notebook:

jupyter notebook Scripts/GenerateModel.ipynb

What it does:

  • Loads Amazon Fine Food Reviews (sentiment labels) and Twitter bot dataset
  • Tests multiple ML algorithms (XGBoost, TensorFlow LSTM, etc.)
  • Evaluates using accuracy, precision, recall, F1-score
  • Saves best model as Resources/model.pickle

3. Secure the Model with Cryptography

Sign the serialized model using RSA:

python Scripts/SignPickle.py      # Generates signature.sig
python Scripts/VerifyPickle.py    # Validates signature

Purpose: Ensures model hasn't been tampered with before deployment.

4. Run Sentiment Analysis

Analyze tweets and user accounts:

python Scripts/TweetSentimentAnalysis.py

5. Launch Discord Bot

Start the bot for real-time interaction:

python sentimentbot.py

Discord Commands:

  • !sentiment <query> β€” Analyze tweet sentiment
  • !analyze <user_id> β€” Detect if a user is likely a bot

πŸ“Š Key Features Deep Dive

Sentiment Analysis

  • TextBlob: Quick polarity & subjectivity scoring
  • Custom Model: Trained on Amazon reviews + Twitter data
  • Output: Positive/Negative/Neutral classification with confidence

Bot Detection

13 Feature Engineering:

  • Account age, verification status, default profile image
  • Follower/following counts, tweet frequency
  • Network metrics: log(followers) * log(following)
  • Acquisition rates: log(followers / account_age_days)

Model: XGBoost binary classifier with 200 boosted trees

Model Security

  • RSA Signatures: Signs model.pickle with private key
  • Verification: Public key verification on model load
  • Purpose: Prevents model poisoning/tampering attacks

Discord Integration

  • Real-time queries without restarting
  • Async operations using discord.py tasks
  • Rate limiting: Respects Twitter API rate limits with automatic backoff

πŸ“ Project Structure

TwitterSentimentAnalysisBot/
β”œβ”€β”€ Resources/
β”‚   β”œβ”€β”€ Config.example.yaml           # Template for API credentials
β”‚   β”œβ”€β”€ Config.yaml                   # (gitignored) Your actual credentials
β”‚   β”œβ”€β”€ model.pickle                  # Trained XGBoost classifier
β”‚   β”œβ”€β”€ signature.sig                 # RSA signature for model
β”‚   β”œβ”€β”€ pubkey.cer                    # Public key for verification
β”‚   └── twitter_human_bots_dataset.csv # Training data
β”œβ”€β”€ Scripts/
β”‚   β”œβ”€β”€ GenerateExpandedTwitterDataset.py  # Data collection & feature engineering
β”‚   β”œβ”€β”€ GenerateModel.ipynb                # Model training notebook
β”‚   β”œβ”€β”€ GenerateEvalFigures.py             # Regenerate README evaluation figures
β”‚   β”œβ”€β”€ SignPickle.py                      # Sign model with RSA
β”‚   β”œβ”€β”€ VerifyPickle.py                    # Verify model signature
β”‚   └── TweetSentimentAnalysis.py          # Inference pipeline
β”œβ”€β”€ Examples/
β”‚   β”œβ”€β”€ TwitterAPIExample.py               # Twitter API usage
β”‚   β”œβ”€β”€ TweetSentimentAnalysisExample.py   # Sentiment analysis demo
β”‚   └── SentimentAnalysisExample2.ipynb    # LSTM training notebook
β”œβ”€β”€ sentimentbot.py                        # Discord bot main file
β”œβ”€β”€ requirements.txt                       # Python dependencies
β”œβ”€β”€ .gitignore                             # Security: excludes Config.yaml
└── README.md                              # This file

πŸ”¬ Technical Highlights

Machine Learning Pipeline

  • Dataset: 50K+ Amazon reviews + 35K+ Twitter accounts
  • Feature Engineering: 13 computed features from API responses
  • Model Selection: Tested XGBoost, TensorFlow LSTM, Scikit-learn classifiers
  • Hyperparameter Tuning: Grid search for optimal XGBoost parameters
  • Evaluation: Stratified k-fold cross-validation, ROC-AUC curves

Cryptographic Security

# Model integrity verification
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes

public_key.verify(
    signature=signature,
    data=model_bytes,
    padding=padding.PSS(
        mgf=padding.MGF1(hashes.SHA256()),
        salt_length=padding.PSS.MAX_LENGTH
    ),
    algorithm=hashes.SHA256()
)

API Integration

  • Tweepy v2: Async-ready for high-volume data collection
  • Rate Limiting: Automatic backoff with wait_on_rate_limit=True
  • Discord.py v2: Modern async/await syntax, task scheduling

πŸ“š Datasets Used

Dataset Source Purpose
Amazon Fine Food Reviews (50K+) Kaggle Sentiment labels for model training
Twitter Bots Accounts (35K+) Kaggle Bot detection training & validation
Real Twitter Data Twitter API v2 Live inference on current tweets

πŸ” Security Considerations

  • API Keys: Use environment variables or config files (never hardcode)
  • Model Integrity: RSA signatures verify model hasn't been poisoned
  • Rate Limiting: Twitter API enforces limits; code handles gracefully
  • Data Privacy: Only collect public tweets/user metrics

πŸ’‘ Learning Outcomes

This project demonstrates:

βœ… Machine Learning: Model training, feature engineering, hyperparameter tuning
βœ… NLP: Sentiment analysis, text preprocessing, tokenization
βœ… API Integration: RESTful APIs (Twitter v2), webhook patterns (Discord)
βœ… Cryptography: RSA signatures, key management, model verification
βœ… Software Engineering: Modular code, error handling, async programming
βœ… Data Engineering: ETL pipelines, feature computation, data validation
βœ… DevOps: Environment configuration, secrets management, CI/CD ready


πŸ› Troubleshooting

Issue Solution
Config.yaml not found Run cp Resources/Config.example.yaml Resources/Config.yaml and add credentials
InvalidSignature on model load Regenerate signature: python Scripts/SignPickle.py
Twitter API rate limit exceeded Wait 15 minutes or upgrade to Academic Research track
Discord bot offline Check bot token is valid and has correct permissions

πŸ“ References & Resources

Click to expand references

πŸ“„ License

This project is licensed under the MIT License β€” see LICENSE file for details.


πŸ“§ Contact & Questions

For questions about this project or to discuss its implementation:


Built with Python, machine learning, and a healthy skepticism of Twitter bots. πŸ€–

Last Updated: June 2024

About

Python NLP pipeline that classifies tweet sentiment and detects Twitter bot accounts with an XGBoost model (0.89 ROC AUC on 35K+ accounts), served through a real-time Discord bot. Includes feature engineering from Twitter API v2 data, RSA-signed model verification, and a full train-to-deploy workflow.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages