Instagram Gemini Bot 🤖
A Python package to build intelligent Instagram DM bots powered by Google Gemini AI. Automatically respond to messages with personalized, context-aware replies.
Features ✨
- 🤖 AI-Powered Responses: Uses Google Gemini for intelligent message generation
- 💬 Context Memory: Remembers conversation history for each user
- 🔧 Easy Configuration: Simple CLI-based setup
- 🚀 Production Ready: Deploy to Azure, AWS, Heroku, or any server
- 📦 Installable Package: Install via pip, deploy anywhere
- 🎭 Customizable Personality: Define bot behavior with custom instructions
- 🔐 Secure: Environment-based configuration
- 📊 SQLite Storage: Persistent conversation storage
Quick Start 🚀
Installation
# From PyPI (when published)
pip install instachatdmbot
# Or from source
git clone https://github.com/23f2001706/insta
cd insta
pip install -e .
Setup
-
Get your credentials:
- Instagram: App ID, App Secret from Meta App Dashboard
- Gemini: API Key from Google AI Studio
-
Initialize the bot (interactive setup):
insta-bot initThis creates a
.envfile with all required configuration. -
Verify configuration:
insta-bot validate -
Run locally:
python main.py
Configuration 📋
The bot uses environment variables stored in .env:
# Instagram Configuration
INSTAGRAM_APP_ID=your_app_id
INSTAGRAM_APP_SECRET=your_app_secret
INSTAGRAM_ACCESS_TOKEN=your_access_token
VERIFY_TOKEN=your_webhook_verify_token
BOT_PAGE_ID=your_page_id
BOT_INSTAGRAM_ID=your_instagram_id
# Gemini Configuration
GEMINI_API_KEY=your_gemini_key
GEMINI_MODEL=gemini-2.5-flash-lite
# Bot Personality
BOT_NAME=MyBot
BOT_INSTRUCTIONS=You are a helpful Instagram assistant...
# Database
DB_PATH=./conversations.db
Getting Credentials
Instagram Credentials
- Go to Meta App Dashboard
- Create or select your app
- Add Instagram as a product
- Go to Settings → Basic to find App ID and App Secret
- Create a Page Access Token in Messenger settings
- In your app, go to Messenger → Settings and set webhook URL to:
https://yourdomain.com/webhook
Gemini API Key
- Visit Google AI Studio
- Click "Create API Key"
- Copy the key to your
.env
Verify Token
Create your own arbitrary token (e.g., my_super_secret_token_123) and use the same value in:
.envfile asVERIFY_TOKEN- Instagram webhook settings as "Verify Token"
Usage 📖
As a Python Package
from insta_bot import InstagramBot
# Create bot with default configurations from .env
bot = InstagramBot()
# Run on port 8000
bot.run(host="0.0.0.0", port=8000)
Custom Configuration
from insta_bot import InstagramBot
# Create with custom instructions
custom_instructions = """
You are a friendly pizza shop assistant.
You help customers order pizza and answer questions.
Keep responses under 100 characters.
"""
bot = InstagramBot(
custom_instructions=custom_instructions,
gemini_model="gemini-2.5-flash-lite"
)
bot.run()
CLI Commands
# Interactive setup
instachatdmbot init
# Validate configuration
instachatdmbot validate
# Run the bot
instachatdmbot run --host 0.0.0.0 --port 8000
Webhook Setup 🔗
Local Testing with ngrok
# Install ngrok
pip install ngrok
# In another terminal
ngrok http 8000
# Get the HTTPS URL (e.g., https://abc123.ngrok.io)
Azure Deployment
- Create Azure App Service (Python 3.10)
- Configure environment variables in Azure portal
- Set startup command:
gunicorn -w 4 -b 0.0.0.0:8000 main:bot.app - In Instagram settings, set webhook URL to your Azure domain
AWS Deployment
- Create AWS Lambda with Python 3.10 runtime
- Use AWS API Gateway to create HTTP endpoint
- Set environment variables in Lambda configuration
- Deploy using
samorserverlessframework
Project Structure 📁
insta-bot-gemini/
├── insta_bot/ # Main package
│ ├── __init__.py # Package exports
│ ├── bot.py # Main bot class
│ ├── config.py # Configuration management
│ ├── instagram_api.py # Instagram Graph API wrapper
│ ├── gemini_handler.py # Gemini AI integration
│ ├── conversation_store.py # SQLite conversation storage
│ └── cli.py # CLI commands
├── main.py # Entry point
├── setup.py # Package setup
├── pyproject.toml # Modern Python packaging
├── requirements.txt # Python dependencies
├── .env.example # Example configuration
└── README.md # This file
How It Works 🔄
Instagram DM → Webhook → Bot receives message
↓
Bot fetches conversation history from SQLite
↓
Message sent to Gemini with system prompt
↓
Gemini generates response
↓
Response saved to conversation history
↓
Response sent back via Instagram API
Example Responses 💬
Default Assistant
User: What's the weather?
Bot: I'm an Instagram assistant, not a weather bot! But I can help with other things. What else can I help with?
Custom: Pizza Shop Bot
User: Can I order pizza?
Bot: Absolutely! We have margherita, pepperoni, and more. What size would you like? 🍕
Troubleshooting 🔧
"403 Forbidden" on webhook verification
- Check
VERIFY_TOKENmatches in both.envand Instagram settings - Ensure Flask is listening on port 8000
"Gemini API error"
- Check
GEMINI_API_KEYis valid and active - Ensure API is enabled in Google Cloud Console
"No messages received"
- Check webhook URL is publicly accessible (HTTPS)
- Verify bot has permission to send messages in Meta dashboard
- Check Instagram app ID and access token
"Messages not stored"
- Check
conversations.dbfile is writable - Ensure SQLite3 is installed:
python -c "import sqlite3"
Deployment 🚀
Heroku
git push heroku main
# Set environment variables
heroku config:set GEMINI_API_KEY=your_key
heroku config:set INSTAGRAM_ACCESS_TOKEN=your_token
Azure
az webapp create --name my-bot --resource-group mygroup --plan myplan --runtime python|3.10
# Configure in Azure portal:
# 1. Go to Configuration → Application Settings
# 2. Add all variables from .env
# 3. Save
Docker
FROM python:3.10-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:8000", "main:bot.app"]
Performance Tips 🏃
- Use flash model:
GEMINI_MODEL=gemini-2.5-flash-lite(faster, cheaper) - Limit conversation history: Trim old messages in
conversation_store.py - Cache responses: Add Redis for frequently asked questions
- Batch responses: Use quick replies instead of text
Security ⚠️
- Never commit
.envfile to git (already in.gitignore) - Keep API keys secret
- Use strong
VERIFY_TOKEN - Validate webhook signatures (todo)
- Rate-limit responses to prevent abuse
Contributing 🤝
Contributions welcome! Please:
- Fork the repository
- Create a feature branch
- Commit your changes
- Push to the branch
- Open a Pull Request
License 📄
MIT License - see LICENSE file for details
Support 💬
Roadmap 🗺️
- Rate limiting
- Webhook signature validation
- Redis caching
- Multi-language support
- Image recognition
- Admin dashboard
- Analytics and metrics
Made with ❤️ for Instagram automation
An automated chatbot for Instagram Direct Messages powered by Google Gemini AI.
Features
- Instagram Integration: Automatically responds to DMs on Instagram
- Gemini AI: Leverages Google's Gemini AI for intelligent responses
- Conversation Memory: Stores conversation history with users
- Configurable: Easy-to-use configuration system
Setup
Prerequisites
- Python 3.8+
- Instagram account
- Google Gemini API key
Installation
- Clone the repository
git clone <repository-url>
cd insta
- Install dependencies
pip install -r requirements.txt
- Configure environment variables
# Edit .env file with your credentials
cp .env.example .env
# Edit .env with your Instagram and Gemini API credentials
- Run the application
python app.py
Configuration
Edit the .env file with your settings:
INSTAGRAM_USERNAME: Your Instagram usernameINSTAGRAM_PASSWORD: Your Instagram passwordGEMINI_API_KEY: Your Google Gemini API keyDEBUG: Enable debug logging (True/False)LOG_LEVEL: Logging level (INFO, DEBUG, ERROR)
Project Structure
app.py: Main application entry pointconfig.py: Configuration managementinstagram_api.py: Instagram API wrappergemini_handler.py: Gemini AI handlerconversation_store.py: Conversation storage and retrievalrequirements.txt: Python dependencies.env: Environment variables (keep this private!)
Usage
The bot will:
- Listen for incoming Instagram DMs
- Process each message with Gemini AI
- Generate personalized responses
- Store conversation history for context
License
MIT
Security Notes
- Never commit
.envfile to version control - Keep your API keys and passwords secure
- Use environment variables for sensitive data
- OAuth is recommended instead of password-based authentication
Metadata
Release files for instachatdmbot 1.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| instachatdmbot-1.0.0.tar.gz | 22.2 kB | Without provenance | Details for instachatdmbot-1.0.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| instachatdmbot-1.0.0-py3-none-any.whl | Python 3 | none | any | Details for instachatdmbot-1.0.0-py3-none-any.whl |
Total release size: 36.8 kB
Release files / instachatdmbot-1.0.0.tar.gz
| Download URL | instachatdmbot-1.0.0.tar.gz |
|---|---|
| Size | 22.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
36fd8858cea9401518976cad94954e8e9b371c4b66da362414e3f0d7ce68a493
|
|
BLAKE2b-256 checksum How to use checksums |
c8b1918ee05d403acc623a4a06a51a9578369336f43084ea7cadf2b41f31f4c8
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.13.5
|
Release files / instachatdmbot-1.0.0-py3-none-any.whl
| Download URL | instachatdmbot-1.0.0-py3-none-any.whl |
|---|---|
| Size | 14.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
4574ab93543cc1705ce426c8eba8c127278fad54b176a1058292b296de43e21f
|
|
BLAKE2b-256 checksum How to use checksums |
cf951ec991f228a8ebd995a7bc304dc28b9eaf55ab5b635867eee8c90b3990d2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.13.5
|
Security for instachatdmbot 1.0.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.