An automated Twitter bot that generates and posts tweets using Google Gemini's free API. This Java application allows you to create engaging social media content with custom prompts.
- Generate tweet content using Google Gemini (gemini-2.0-flash-exp) - Free Tier
- 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
- Java 17 or higher
- Maven 3.6 or higher
- Google Gemini API key (free tier available)
- Twitter Developer Account with API credentials
- Go to Google AI Studio
- Sign in with your Google account
- Click "Create API Key"
- Select or create a Google Cloud project
- Copy the API key and save it securely
Note: The free tier of Google Gemini includes:
- 15 requests per minute
- 1 million tokens per minute
- 1,500 requests per day
- More than enough for a tweet bot!
- Go to Twitter Developer Portal
- Create a new project and app (or use existing)
- Navigate to your app's "Keys and tokens" section
- Generate and save the following credentials:
- API Key (Consumer Key)
- API Secret (Consumer Secret)
- Access Token
- Access Token Secret
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"
Note: This application uses Twitter API v2 for posting tweets (compatible with Free and Basic access tiers) and v1.1 for media uploads.
-
Copy the example environment file:
cp .env.example .env
-
Edit
.envand add your API credentials:GEMINI_API_KEY=your-gemini-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 TWEET_PROMPT=Write a short, engaging tweet about technology trends IMAGE_PATH=/path/to/your/image.jpg -
Customize the
TWEET_PROMPTto match your desired content theme -
(Optional) Configure Image Attachment:
- Set
IMAGE_PATHto 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)
- Set
mvn clean packageThis will:
- Download all dependencies
- Compile the source code
- Run tests (if any)
- Create an executable JAR file in the
targetdirectory
TweetBot supports three modes of operation:
Generate a tweet and manually approve before posting:
java -jar target/tweetbot-1.0.0.jarOr using Maven:
mvn exec:java -Dexec.mainClass="com.voidcode.tweetbot.TweetBot"Run continuously and automatically post tweets every 30 minutes:
java -jar target/tweetbot-1.0.0.jar --scheduleOr with a custom prompt:
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.
Generate and post a single tweet automatically without confirmation:
java -jar target/tweetbot-1.0.0.jar --autoWith custom prompt:
java -jar target/tweetbot-1.0.0.jar --auto "Write a motivational quote about perseverance"| 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 |
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
==========================================================
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/
│ ├── GeminiService.java # Google Gemini integration
│ └── TwitterService.java # Twitter API integration
└── resources/
└── logback.xml # Logging configuration
| Variable | Required | Description |
|---|---|---|
GEMINI_API_KEY |
Yes | Your Google Gemini API key (free tier available) |
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 |
TWEET_PROMPT |
No | Default prompt for tweet generation |
IMAGE_PATH |
No | Path to image file to attach to every tweet (jpg, png, gif) |
You can customize the tweet generation by modifying the prompt. Here are some examples:
# 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"Every tweet can include a static image from your local file system:
Setup:
- Place your image file anywhere on your system
- Add the absolute path to
.env:IMAGE_PATH=/home/user/images/brand-logo.png
- 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_PATHline 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.
To run the bot continuously in the background on Linux/Mac:
# 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 tweetbotUsing systemd (Linux):
Create a service file /etc/systemd/system/tweetbot.service:
[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.targetThen enable and start:
sudo systemctl daemon-reload
sudo systemctl enable tweetbot
sudo systemctl start tweetbot
sudo systemctl status tweetbot
# View logs
sudo journalctl -u tweetbot -fThe application creates logs in two places:
- Console output: Real-time logs with timestamps
- File output:
tweetbot.login the project directory
Log levels:
- INFO: General application flow
- WARN: Warnings and non-critical issues
- ERROR: Errors and exceptions
- Never commit
.envfile - It contains sensitive API keys - Use environment variables - For production deployments
- Rotate API keys regularly - Update keys periodically
- Limit API permissions - Only grant necessary permissions
- Monitor API usage - Check for unusual activity
Ensure your .env file exists and contains all required variables.
- Check that your API keys are correct
- Verify your app has Read and Write permissions
- Regenerate access tokens if needed
This error means your Twitter API access level doesn't support v1.1 tweet posting. The code has been updated to use API v2 which is supported by all access tiers (Free, Basic, Pro). Make sure you're using the latest version of the code.
- Verify your Gemini API key is valid
- Check that you're within the free tier rate limits (15 RPM, 1500 RPD)
- Review the error message in logs
- Ensure your Google Cloud project is properly configured
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
- OkHttp (4.12.0) - HTTP client for API requests
- Jackson (2.16.1) - JSON processing
- SLF4J & Logback (2.0.9) - Logging
- Dotenv (3.0.0) - Environment variable management
Feel free to fork this project and customize it for your needs. Some ideas:
To change the posting frequency from 30 minutes to another interval, edit TweetBot.java:
private static final int SCHEDULE_INTERVAL_MINUTES = 30; // Change this value- 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
This project is open source and available for educational purposes.
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.
For issues or questions:
- Check the troubleshooting section
- Review application logs in
tweetbot.log - Verify API credentials and permissions
- Check Twitter and Google AI Studio status pages