# TweetBot - AI-Powered Twitter Bot An automated Twitter bot that generates and posts tweets using OpenAI's ChatGPT API. This Java application allows you to create engaging social media content with custom prompts. ## Features - Generate tweet content using ChatGPT (GPT-3.5-turbo) - **Three operation modes:** - Interactive mode with manual approval - Auto-post mode for one-time tweets - Scheduled mode (posts every 30 minutes) - **Attach images to tweets** - Include a static image from local file system with every tweet - Automatic tweet posting at regular intervals - Customizable prompts for different content types - Character limit validation (280 characters) - Graceful error handling with automatic retry - Comprehensive logging (console and file) - Environment-based configuration - Background service support ## Prerequisites - Java 17 or higher - Maven 3.6 or higher - OpenAI API key - Twitter Developer Account with API credentials ## Setup Instructions ### 1. Get OpenAI API Key 1. Go to [OpenAI Platform](https://platform.openai.com/) 2. Sign up or log in to your account 3. Navigate to API keys section 4. Create a new API key and save it securely ### 2. Get Twitter API Credentials 1. Go to [Twitter Developer Portal](https://developer.twitter.com/en/portal/dashboard) 2. Create a new project and app (or use existing) 3. Navigate to your app's "Keys and tokens" section 4. Generate and save the following credentials: - API Key (Consumer Key) - API Secret (Consumer Secret) - Access Token - Access Token Secret - Bearer Token **Important:** Ensure your Twitter app has **Read and Write** permissions: - Go to your app settings - Navigate to "User authentication settings" - Set app permissions to "Read and Write" ### 3. Configure the Application 1. Copy the example environment file: ```bash cp .env.example .env ``` 2. Edit `.env` and add your API credentials: ``` OPENAI_API_KEY=sk-your-openai-api-key-here TWITTER_API_KEY=your-twitter-api-key TWITTER_API_SECRET=your-twitter-api-secret TWITTER_ACCESS_TOKEN=your-twitter-access-token TWITTER_ACCESS_TOKEN_SECRET=your-twitter-access-token-secret TWITTER_BEARER_TOKEN=your-twitter-bearer-token TWEET_PROMPT=Write a short, engaging tweet about technology trends IMAGE_PATH=/path/to/your/image.jpg ``` 3. Customize the `TWEET_PROMPT` to match your desired content theme 4. **(Optional) Configure Image Attachment:** - Set `IMAGE_PATH` to the absolute path of an image file (jpg, png, gif) - This image will be attached to every tweet - Leave empty or comment out to post text-only tweets - Example: `IMAGE_PATH=/home/user/images/logo.png` - Supported formats: JPEG, PNG, GIF - Maximum file size: 5MB (Twitter limit) ### 5. Build the Project ```bash mvn clean package ``` This will: - Download all dependencies - Compile the source code - Run tests (if any) - Create an executable JAR file in the `target` directory ## Usage TweetBot supports three modes of operation: ### 1. Interactive Mode (Default) Generate a tweet and manually approve before posting: ```bash java -jar target/tweetbot-1.0.0.jar ``` Or using Maven: ```bash mvn exec:java -Dexec.mainClass="com.voidcode.tweetbot.TweetBot" ``` ### 2. Scheduled Mode (Auto-post every 30 minutes) Run continuously and automatically post tweets every 30 minutes: ```bash java -jar target/tweetbot-1.0.0.jar --schedule ``` Or with a custom prompt: ```bash java -jar target/tweetbot-1.0.0.jar --schedule "Write daily tech tips" ``` The bot will: - Post immediately when started - Post a new tweet every 30 minutes - Run continuously until stopped with Ctrl+C - Automatically recover from errors and retry at the next interval **Note:** In scheduled mode, tweets are posted automatically without manual confirmation. ### 3. Auto-Post Mode (One-time) Generate and post a single tweet automatically without confirmation: ```bash java -jar target/tweetbot-1.0.0.jar --auto ``` With custom prompt: ```bash java -jar target/tweetbot-1.0.0.jar --auto "Write a motivational quote about perseverance" ``` ### Command-Line Options | Option | Short | Description | |--------|-------|-------------| | `--schedule` | `-s` | Run in scheduled mode (posts every 30 minutes) | | `--auto` | `-a` | Auto-post without confirmation (one-time) | | `--help` | `-h` | Show help message | ### Example Output **Interactive Mode:** ``` ========================================================== Generated Tweet: ========================================================== The future of AI is not about replacing humans, but augmenting our capabilities. Together, we can achieve what neither could alone. ========================================================== Character count: 145/280 ========================================================== Do you want to post this tweet? (yes/no): yes ========================================================== SUCCESS! Tweet posted successfully! Tweet ID: 1234567890123456789 View at: https://twitter.com/user/status/1234567890123456789 ========================================================== ``` **Scheduled Mode:** ``` ========================================================== TweetBot - SCHEDULED MODE ========================================================== Tweet will be posted every 30 minutes Press Ctrl+C to stop ========================================================== ========================================================== [2025-10-24 14:30:00] Tweet Posted Successfully! ========================================================== AI is transforming how we work, learn, and create. The future is collaborative intelligence. ========================================================== Tweet ID: 1234567890123456789 View at: https://twitter.com/user/status/1234567890123456789 Next tweet in 30 minutes ========================================================== ``` ## Project Structure ``` tweetbot/ ├── pom.xml # Maven configuration ├── .env # Environment variables (not in git) ├── .env.example # Example environment file ├── README.md # This file └── src/ └── main/ ├── java/ │ └── com/ │ └── voidcode/ │ └── tweetbot/ │ ├── TweetBot.java # Main application │ ├── config/ │ │ └── Config.java # Configuration loader │ └── service/ │ ├── OpenAIService.java # ChatGPT integration │ └── TwitterService.java # Twitter API integration └── resources/ └── logback.xml # Logging configuration ``` ## Configuration Options ### Environment Variables | Variable | Required | Description | |----------|----------|-------------| | `OPENAI_API_KEY` | Yes | Your OpenAI API key | | `TWITTER_API_KEY` | Yes | Twitter API Key (Consumer Key) | | `TWITTER_API_SECRET` | Yes | Twitter API Secret (Consumer Secret) | | `TWITTER_ACCESS_TOKEN` | Yes | Twitter Access Token | | `TWITTER_ACCESS_TOKEN_SECRET` | Yes | Twitter Access Token Secret | | `TWITTER_BEARER_TOKEN` | Yes | Twitter Bearer Token | | `TWEET_PROMPT` | No | Default prompt for tweet generation | | `IMAGE_PATH` | No | Path to image file to attach to every tweet (jpg, png, gif) | ### Customizing Tweet Generation You can customize the tweet generation by modifying the prompt. Here are some examples: ```bash # Technology news (interactive mode) java -jar target/tweetbot-1.0.0.jar "Write a tweet about the latest AI breakthrough" # Motivational content (auto-post) java -jar target/tweetbot-1.0.0.jar --auto "Write an inspiring quote about success" # Product updates (scheduled) java -jar target/tweetbot-1.0.0.jar --schedule "Announce a new feature for a productivity app" # Educational content (scheduled) java -jar target/tweetbot-1.0.0.jar --schedule "Share an interesting fact about space exploration" ``` ### Attaching Images to Tweets Every tweet can include a static image from your local file system: **Setup:** 1. Place your image file anywhere on your system 2. Add the absolute path to `.env`: ```bash IMAGE_PATH=/home/user/images/brand-logo.png ``` 3. Run the bot normally - the image will be automatically attached to every tweet **Image Requirements:** - Supported formats: JPEG (.jpg, .jpeg), PNG (.png), GIF (.gif) - Maximum file size: 5MB (Twitter API limit) - Recommended dimensions: 1200x675 pixels for optimal display - The image must exist at the specified path when the bot runs **Example Use Cases:** - Brand logo or watermark on every tweet - Product image for promotional content - Infographic or visual content - Profile or avatar image **To disable images:** - Comment out or remove the `IMAGE_PATH` line in `.env` - Or set it to an empty value: `IMAGE_PATH=` **Note:** If the image file is not found or fails to upload, the tweet will still be posted without the image, and an error will be logged. ### Running as a Background Service To run the bot continuously in the background on Linux/Mac: ```bash # Run in background nohup java -jar target/tweetbot-1.0.0.jar --schedule > tweetbot.out 2>&1 & # Check if it's running ps aux | grep tweetbot # View output tail -f tweetbot.out # Stop the bot pkill -f tweetbot ``` **Using systemd (Linux):** Create a service file `/etc/systemd/system/tweetbot.service`: ```ini [Unit] Description=TweetBot - Automated Twitter Posting After=network.target [Service] Type=simple User=your-username WorkingDirectory=/path/to/tweetbot ExecStart=/usr/bin/java -jar /path/to/tweetbot/target/tweetbot-1.0.0.jar --schedule Restart=always RestartSec=60 StandardOutput=journal StandardError=journal [Install] WantedBy=multi-user.target ``` Then enable and start: ```bash sudo systemctl daemon-reload sudo systemctl enable tweetbot sudo systemctl start tweetbot sudo systemctl status tweetbot # View logs sudo journalctl -u tweetbot -f ``` ## Logging The application creates logs in two places: - **Console output**: Real-time logs with timestamps - **File output**: `tweetbot.log` in the project directory Log levels: - INFO: General application flow - WARN: Warnings and non-critical issues - ERROR: Errors and exceptions ## Security Best Practices 1. **Never commit `.env` file** - It contains sensitive API keys 2. **Use environment variables** - For production deployments 3. **Rotate API keys regularly** - Update keys periodically 4. **Limit API permissions** - Only grant necessary permissions 5. **Monitor API usage** - Check for unusual activity ## Troubleshooting ### "Missing required environment variable" Ensure your `.env` file exists and contains all required variables. ### "Failed to verify Twitter credentials" 1. Check that your API keys are correct 2. Verify your app has Read and Write permissions 3. Regenerate access tokens if needed ### "Failed to generate tweet" 1. Verify your OpenAI API key is valid 2. Check that you have sufficient API credits 3. Review the error message in logs ### Twitter API Rate Limits Twitter API has rate limits: - Tweet creation: 300 tweets per 3 hours (100 per hour average) - The default 30-minute interval allows for 6 tweets per 3 hours, well within limits - Monitor your usage to avoid hitting limits - If you modify the schedule interval, ensure you stay within rate limits ## Dependencies - **Twitter API Java SDK** (2.0.3) - Twitter API client - **OpenAI GPT-3 Java** (0.18.2) - OpenAI API client - **OkHttp** (4.12.0) - HTTP client - **Jackson** (2.16.1) - JSON processing - **SLF4J & Logback** (2.0.9) - Logging - **Dotenv** (3.0.0) - Environment variable management ## Contributing Feel free to fork this project and customize it for your needs. Some ideas: ### Customizing the Schedule Interval To change the posting frequency from 30 minutes to another interval, edit `TweetBot.java`: ```java private static final int SCHEDULE_INTERVAL_MINUTES = 30; // Change this value ``` ### Other Enhancement Ideas - Add support for images and media attachments - Implement tweet threading for longer content - Add sentiment analysis before posting - Create multiple prompt templates with rotation - Store tweet history in a database - Add analytics and engagement tracking - Support for multiple Twitter accounts - Implement tweet approval queue/review system ## License This project is open source and available for educational purposes. ## Disclaimer Use this bot responsibly and in accordance with Twitter's Terms of Service and Automation Rules. Ensure you comply with rate limits and don't spam or post misleading content. ## Support For issues or questions: 1. Check the troubleshooting section 2. Review application logs in `tweetbot.log` 3. Verify API credentials and permissions 4. Check Twitter and OpenAI API status pages