telegram-bot

Telegram Bot (based on Telethon)

🧱 1. Project Structure

βœ” Clear separation of concerns

βœ” No circular imports

βœ” Easy to reason about

telegram-bot/
β”œβ”€β”€ bot.py
β”œβ”€β”€ requirements.txt
β”œβ”€β”€ README.md
β”œβ”€β”€ .gitignore
β”œβ”€β”€ .*.session              # ❌ not committed (server only)
β”œβ”€β”€ .env                    # ❌ not committed (server only)
β”‚
β”œβ”€β”€ config/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ env.py
β”‚   β”œβ”€β”€ forwarding.py
β”‚   └── moderation.py
β”‚
β”œβ”€β”€ core/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ client.py
β”‚   └── startup.py
β”‚
β”œβ”€β”€ handlers/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ forward.py
β”‚   └── moderation.py
β”‚
β”œβ”€β”€ utils/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ logger.py
β”‚   └── messages.py
β”‚
β”œβ”€β”€ systemd/
β”‚   β”œβ”€β”€ telegram-bot.service
β”‚   β”œβ”€β”€ telegram-bot-update.service
β”‚   β”œβ”€β”€ telegram-bot-update.timer
β”‚   └── update.sh
β”‚
└── venv/                   # ❌ not committed (server only)

πŸ” 2. Security & Secrets

βœ” .env ignored in Git

βœ” Telethon session files ignored

βœ” Dedicated Telegram account (best practice)

βœ” No hardcoded secrets

βœ” Non-root systemd execution

βš™οΈ 3. Environment & Config

config/env.py

βœ” Validates API_ID / API_HASH

βœ” Defaults handled safely

βœ” Clean env loading config/forwarding.py

βœ” Explicit channel β†’ topic mapping

βœ” Media-only channel rules

βœ” Extension whitelist config/moderation.py

βœ” Topic-specific rules

βœ” Clear permission model

πŸ€– 4. Telethon Client & Startup

core/client.py

βœ” Single shared client

βœ” Correct session usage core/startup.py

βœ” Graceful shutdown (SIGTERM / SIGINT)

βœ” systemd-friendly

βœ” Clean disconnect

βœ” Proper exit codes

πŸ” 5. Forwarding Logic

handlers/forward.py

βœ” Only listens to configured source channels

βœ” Album forwarding supported

βœ” Media filtering enforced

βœ” Edit β†’ delete & repost implemented

βœ” FloodWait-safe

βœ” Exception-isolated

βœ” Forward tracking prevents duplicates

πŸ›‘οΈ 6. Moderation Logic

handlers/moderation.py

βœ” Topic-based rules

βœ” Bot exempt

βœ” Anonymous admins exempt

βœ” Correct forum topic detection

βœ” Safe deletes

βœ” Temporary reason messages

βœ” Clean logging

πŸ’¬ 7. Messaging UX

utils/messages.py

βœ” Markdown-safe

βœ” User mention safe

βœ” Auto-delete TTL

βœ” Exception-proof

βœ” No UX regressions

🧾 8. Logging

utils/logger.py

βœ” Single named logger

βœ” No duplicate handlers

βœ” Journal-friendly output

βœ” Readable format

πŸ”„ 9. Self-Update System

systemd/update.sh

βœ” Pulls only when changes exist

βœ” No unnecessary restarts

βœ” Virtualenv safe

βœ” Clear logs

βœ” Fail-fast scripting telegram-bot-update.timer

βœ” Hourly checks (safe)

βœ” Persistent

βœ” Low wake-ups telegram-bot-update.service

βœ” Sandboxed

βœ” No system file access

βœ” Network-aware

🧠 10. systemd Bot Service

telegram-bot.service

βœ” Non-root user

βœ” Auto-restart

βœ” Crash protection

βœ” Clean shutdown integration

βœ” Journal logging

πŸ“¦ 11. Dependencies

requirements.txt

βœ” Minimal

βœ” Correct versions implied

βœ” No unused libraries

🚦 12. Load & Scale Fit

Actual usage:

~17 source channels

~5 messages/day

Bot can safely handle:

βœ” 10Γ— load (as per 17 source channels & 5 messages/day)

βœ” 24Γ—7 uptime

βœ” Long-running sessions

πŸ§ͺ 13. Failure Scenarios (All Covered)

Scenario                   Outcome
Bot crash                  systemd restart
Telegram disconnect        auto reconnect
FloodWait                  waits & resumes
Bad message                isolated
Bad album                  skipped
Edit storm                 safe repost
Update failure             no restart

Setup on Local Server - (CMD/Termux/Linux)

Setup on Cloud Server - (Oracle/AWS using Console)

1️⃣ SSH into Oracle server (or your preferred one)

ssh <PRIVATE_KEY> ubuntu@<SERVER_IP>

Update server & install dependencies:

sudo apt update && sudo apt upgrade -y
sudo apt install git python3 python3-pip python3-venv -y

2️⃣ Clone Your GitHub Repository

If repo is not cloned

cd /home/ubuntu
git clone https://github.com/DineshValor/telegram-bot.git

If already cloned

cd /home/ubuntu/telegram-bot
git pull origin master

3️⃣ Create Python virtual environment

cd /home/ubuntu/telegram-bot
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
deactivate

4️⃣ Configure variables

cp /home/ubuntu/telegram-bot/.env.example /home/ubuntu/telegram-bot/.env
nano /home/ubuntu/telegram-bot/.env

5️⃣ Make update & journal-watcher script executable

sudo chmod +x /home/ubuntu/telegram-bot/systemd/update.sh
sudo chmod +x /home/ubuntu/telegram-bot/systemd/journal-watcher.sh

Verify:

ls -l /home/ubuntu/telegram-bot/systemd/update.sh
ls -l /home/ubuntu/telegram-bot/systemd/journal-watcher.sh

You should see -rwx.

6️⃣ Start bot

cd /home/ubuntu/telegram-bot
source venv/bin/activate
python3 bot.py

Run 24Γ—7 (Auto update + restart)

1️⃣ Stop bot

CTRL+C (Key Press)

2️⃣ Install systemd service files

Systemd cannot read files from your repo directly. We must copy them.

sudo cp /home/ubuntu/telegram-bot/systemd/telegram-bot.service /etc/systemd/system/
sudo cp /home/ubuntu/telegram-bot/systemd/telegram-bot-update.service /etc/systemd/system/
sudo cp /home/ubuntu/telegram-bot/systemd/telegram-bot-update.timer /etc/systemd/system/
sudo cp /home/ubuntu/telegram-bot/systemd/telegram-bot-journal-watcher.service /etc/systemd/system/
sudo cp /home/ubuntu/telegram-bot/systemd/telegram-bot-failure.service /etc/systemd/system/

3️⃣ Reload systemd

sudo systemctl daemon-reexec
sudo systemctl daemon-reload

4️⃣ Enable services

sudo systemctl enable telegram-bot
sudo systemctl enable telegram-bot-update.timer
sudo systemctl enable telegram-bot-journal-watcher

5️⃣ Start services

sudo systemctl start telegram-bot
sudo systemctl start telegram-bot-journal-watcher
sudo systemctl start telegram-bot-update.timer

6️⃣ Verify Status (IMPORTANT)

systemctl status telegram-bot --no-pager
systemctl status telegram-bot-journal-watcher --no-pager
systemctl status telegram-bot-update.timer --no-pager

FAQ

Run update service manually:

sudo systemctl start telegram-bot-update.service

check logs

systemctl status telegram-bot-update.service --no-pager -l

Expected behavior:

β€’ If no new commit β†’ β€œNo updates found”

β€’ If new commit β†’ pull β†’ restart bot

Q. Monitoring & Debugging

journalctl -u telegram-bot -f
journalctl -u telegram-bot-update
systemctl list-timers

Q. Make update.sh executable

chmod +x /home/ubuntu/telegram-bot/systemd/update.sh

Q. Reload systemd

sudo systemctl daemon-reload

Q. If bot doesn’t start

journalctl -u telegram-bot --no-pager

Q. Overwritten by merge

git stash
git pull
git stash pop

Q. Quick Commands

Start bot

sudo systemctl start telegram-bot

Restart bot

sudo systemctl restart telegram-bot

Stop bot

sudo systemctl stop telegram-bot

View logs

journalctl -u telegram-bot -f

Q. Fatal: detected dubious ownership in repository at β€˜/home/ubuntu/telegram-bot’

sudo git config --global --add safe.directory /home/ubuntu/telegram-bot