◈ Overview
Amin's Smart Assistant is an intelligent Telegram bot that connects Gmail, Google Drive, Google Sheets, and multiple AI models into a single unified command interface. Built on n8n automation with Docker on WSL2, the system routes incoming messages through dual specialized AI agents — each equipped with distinct tools, memory, and reasoning models — transforming any Telegram conversation into a full-featured productivity hub.
The bot targets power users, developers, and teams who need a portable, self-hosted automation layer over their Google Workspace. It supports natural language email composition, spreadsheet queries, Drive browsing, Python code execution, persistent conversation memory via PostgreSQL, and bilingual interaction in English and Persian — all delivered through a single Telegram interface.
◈ Features
▶ Feature |
Description | Status |
|---|---|---|
| Dual AI Agents | Email Agent and Data Agent — each with specialized tools and Gemini 2.0 Flash reasoning | ✅ |
| Gmail Integration | Send and retrieve emails through natural language commands via Telegram | ✅ |
| Google Sheets | Read, analyze, and display spreadsheet data with row/column targeting | ✅ |
| Google Drive | Search files, browse folder structures, and retrieve storage analytics | ✅ |
| Memory System | PostgreSQL-backed persistent conversation memory with cross-session context | ✅ |
| Python Execution | Detect and execute Python code snippets with intelligent keyword routing | ✅ |
| Smart Routing | Automatic message classification — email, data, or code — before agent dispatch | ✅ |
| Multi-Language | Full English and Persian (فارسی) support with context-aware responses | ✅ |
| Ollama Local AI | Qwen 3:4B running locally via Docker with GPU acceleration | ✅ |
| Webhook Tunneling | ngrok secure tunneling for Telegram webhook on local WSL2 deployment | ✅ |
| Rich Media Support | Images, documents, and voice message handling | ⏳ |
| Analytics Dashboard | Usage metrics and performance monitoring panel | ⏳ |
◈ Architecture
graph TD
A[Telegram Input] --> B{Message Type Detection}
B -->|Email Related| C[AI Agent — Email]
B -->|Data/Drive Related| D[AI Agent — Data]
C --> E[Gmail Tools]
C --> F[Gemini AI Model]
D --> G[Google Sheets]
D --> H[Google Drive]
D --> I[Gemini AI Model]
E --> J{Response Processing}
G --> J
H --> J
J -->|Contains Python| K[Code Execution]
J -->|Regular Response| L[Direct Output]
K --> M[Telegram Output]
L --> M
F --> N[PostgreSQL Memory]
I --> N
◈ Tech Stack
| Layer | Technologies |
|---|---|
| Automation Engine | n8n — self-hosted workflow orchestration |
| AI Models | Gemini 2.0 Flash · Qwen 3:4B via Ollama |
| Messaging | Telegram Bot API — webhook-based real-time updates |
| Google Workspace | Gmail API · Google Sheets API · Google Drive API |
| Infrastructure | Docker · WSL2 (Ubuntu) · ngrok tunneling |
| Memory & Storage | PostgreSQL — persistent session and context storage |
| Language | Python 3 — code execution and backend logic |
| Auth | OAuth2 — Google services authentication |
◈ Project Structure
smart-telegram-bot/
│
├── n8n_amin_workflow.json ← Main n8n workflow export (import this)
├── requirements.txt ← Python dependencies
├── .env.example ← Environment variable template
│
├── Image/
│ ├── n8n_1.png ← n8n workflow UI preview
│ └── ...
│
├── docs/
│ └── setup.md ← Extended configuration notes
│
└── LICENSE
◈ Installation
Install WSL2 with Ubuntu and Docker.
# Install WSL2 with Ubuntu
wsl --install -d Ubuntu
# Install Docker in WSL2
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
# Start Docker service
sudo service docker start
Run Ollama container and pull the Qwen model.
# Pull and run Ollama with GPU support
docker run -d --gpus=all -v ollama:/root/.ollama -p 11434:11434 --name ollama ollama/ollama
# Install Qwen 3:4B model
docker exec -it ollama ollama pull qwen3:4b
Install and configure ngrok for Telegram webhook tunneling.
# Install ngrok
curl -s https://ngrok-agent.s3.amazonaws.com/ngrok.asc | sudo tee /etc/apt/trusted.gpg.d/ngrok.asc >/dev/null
echo "deb https://ngrok-agent.s3.amazonaws.com buster main" | sudo tee /etc/apt/sources.list.d/ngrok.list
sudo apt update && sudo apt install ngrok
# Authenticate and expose n8n
ngrok authtoken YOUR_NGROK_TOKEN
ngrok http 5678
Launch n8n with PostgreSQL via Docker.
docker run -d \
--name n8n \
-p 5678:5678 \
-e DB_TYPE=postgresdb \
-e DB_POSTGRESDB_HOST=postgres \
-e DB_POSTGRESDB_DATABASE=n8n \
-v n8n_data:/home/node/.n8n \
--link postgres:postgres \
n8nio/n8n
Import the n8n workflow JSON.
curl -X POST "your-ngrok-url.ngrok.io/api/v1/workflows/import" \
-H "Content-Type: application/json" \
-d @n8n_amin_workflow.json
Set up all service credentials inside n8n.
- Telegram Bot API token with ngrok webhook URL
- Google OAuth2 for Gmail, Sheets, and Drive
- PostgreSQL connection string
- Ollama API endpoint:
http://localhost:11434
Connect all containers to a shared Docker network.
docker network create n8n-network
docker network connect n8n-network ollama
docker network connect n8n-network postgres
docker network connect n8n-network n8n
◈ Configuration
Telegram Bot
{
"telegramApi": {
"accessToken": "YOUR_BOT_TOKEN",
"baseURL": "https://api.telegram.org"
}
}
Ollama Local AI
{
"ollamaApi": {
"baseURL": "http://localhost:11434",
"model": "qwen3:4b"
}
}
ngrok Webhook
{
"webhookUrl": "https://your-tunnel.ngrok.io/webhook/telegram",
"allowedUpdates": ["message"]
}
◈ Usage Examples
Email Operations
User → "Send an email to [email protected] about tomorrow's meeting"
Bot → Email composed and dispatched via Gmail API.
Subject auto-generated. Sender attribution applied.
✅ Delivered to [email protected]
Spreadsheet Query
User → "Show me the latest data from my spreadsheet"
Bot → Fetched 25 rows from active sheet.
Columns parsed and formatted for Telegram output.
✅ Data retrieved successfully
Python Execution
User → "Write a Python script to calculate fibonacci"
Bot → Code generated, sandboxed, and executed.
Output returned with performance note.
✅ Script ran successfully
◈ Advanced Features
Smart Message Detection — The routing layer classifies every incoming message before dispatching it. Email keywords (message, پیام, messag), Python keywords (python, پایتون, pyton), and context from prior messages all influence which agent receives the task.
Response Enhancement — Every reply is post-processed: thinking tokens are stripped, emoji are placed meaningfully, the user's first name is injected, and the signature 𝑨𝒎𝒊𝒏 💛 𝑴𝒐𝒏𝒊𝒓𝒚 is appended automatically.
Memory Architecture — PostgreSQL stores full session history. Each agent reads from and writes to the same memory pool, enabling coherent multi-turn conversations across separate sessions without repeated context.
Model Selection — Gemini 2.0 Flash handles reasoning-heavy tasks; Qwen 3:4B serves fast local completions via Ollama. The routing logic selects the appropriate model based on task complexity and latency requirements.
◈ Performance
| Component | Response Time | Accuracy | Uptime | Environment |
|---|---|---|---|---|
| Telegram Webhook (ngrok) | <100ms | 99.9% | 99.9% | WSL2 Docker |
| AI Agent Processing | <2s | 95% | 99.5% | Ollama Local |
| Gmail Operations | <3s | 98% | 99.8% | Google API |
| Google Drive Access | <1s | 99% | 99.9% | Google API |
| Memory Retrieval | <200ms | 100% | 99.9% | PostgreSQL |
◈ Troubleshooting
Bot not responding
# Verify webhook is registered
curl -X GET "https://api.telegram.org/bot{TOKEN}/getWebhookInfo"
# Confirm n8n workflow is active and Telegram trigger node is connected
Gmail authentication errors
# Refresh OAuth2 tokens in n8n credentials
# Verify all required scopes in Google Cloud Console
# Check credential expiration date
ngrok tunnel disconnected
# Restart with stable connection
ngrok http 5678 --region=us --log=stdout
# Re-register Telegram webhook with new URL
curl -X POST "https://api.telegram.org/bot{TOKEN}/setWebhook" \
-H "Content-Type: application/json" \
-d '{"url":"https://new-tunnel.ngrok.io/webhook/telegram"}'
Ollama not responding
# Check container status
docker ps | grep ollama
# Restart and verify model
docker restart ollama
curl http://localhost:11434/api/generate -d '{"model":"qwen3:4b","prompt":"test"}'
WSL2 Docker issues
sudo service docker restart
docker --version
wsl --list --verbose
◈ Roadmap
- [ ] Rich media handling — images, documents, and voice messages
- [ ] Multi-language expansion — Arabic, Turkish, and more
- [ ] GPT-4 integration as an optional reasoning backend
- [ ] Analytics dashboard for usage metrics and agent performance
- [ ] Additional service integrations — Notion, Slack, Trello
- [ ] Mobile-facing webhook layer for third-party app triggers
◈ Contributing
- Fork the repository via the Fork button on GitHub.
- Create a feature branch:
git checkout -b feature/your-feature-name - Commit with a descriptive message:
git commit -m "Add: brief description" - Push to your fork:
git push origin feature/your-feature-name - Open a Pull Request against the
masterbranch of this repository.
◈ License
This project is licensed under the MIT License.
Any forks or distributions must retain credit to Amin Moniry (AminTivanix2) as the original author. See LICENSE for complete terms.
© 2025 Amin Moniry (AminTivanix2) — All Rights Reserved
◈ Screenshots
▶ n8n workflow — dual agent routing with Gmail, Sheets, Drive, and memory nodes