LLM-powered Telegram bot (OpenAI + Anthropic)
Project description
TeLLMgramBot
The basic goal of this project is to create a bridge between a Telegram Bot and a Large Language Model (LLM), supporting both OpenAI's GPT models and Anthropic's Claude models.
- To use this library, you must have a Telegram account with a user name, not just a phone number. If you don't have one, create one online.
- If added to a Telegram group, the bot must be administrator in order to respond to a user calling out its name, initials, or nickname.
Telegram Bot + LLM Encapsulation
- The Telegram interface handles special commands and basic "chatty" responses that don't require an LLM, like "Hello". Dynamic conversations are handed off to the LLM while Telegram acts as the interaction broker.
- Pass URLs in [square brackets] and mention how the bot should interpret them.
- Example: "What do you think of this article? [https://some_site/article]"
- Uses a separate model (configurable via
url_model) to handle larger URL content.
- Ask questions about message history across all your chats using natural language; the bot will search, attribute messages to speakers, and include messages from other bots.
- Example: "Who said thanks for the breakdown?" or "What did George say about the project?" or "Show me the last few messages."
- All search filters (speaker, chat, date) are optional. Results are ordered most-recent-first. Configure
search_limitto control how many results to return (default: 30). - Search automatically finds users and chats by their current or past names, so you can reference them however you remember them.
- Token limits measure conversation length and determine when to prune oldest messages to stay within model limits.
- The bot loads the user's full history across all chats up to 50% of the token budget. In private chats, shared group context fills the remaining budget, enabling the bot to reference group conversations from a private context.
- This eliminates amnesia when switching between private and group chats.
- Conversation archive preserves long-term context without consuming token budget.
- Older messages are automatically distilled into concise daily summaries (Tier 1), then progressively compressed into monthly digests (Tier 2). Raw messages are never deleted; archive rows surface seamlessly in search results and context loading.
- Configurable via
archive_days(default 60 days before Tier 1 triggers; Tier 2 triggers at 2x this value).
- Users can manage privacy via two commands:
/forget- In private chats, clears your full conversation and resets all active sessions. In group chats, removes only your messages and cleans up paired bot replies./private- Toggle private mode (private chats only). When ON, your messages in private chats are excluded from group conversation contexts, enabling selective privacy even in shared groups.
Why Telegram?
Using Telegram as the interface not only solves "exposing" the interface, but gives you boatloads of interactivity over a standard Command Line interface, or trying to create a website with input boxes and submit buttons to try to handle everything:
- Telegram already lets you paste in verbose, multiline messages.
- Telegram already lets you paste in pictures, videos, links, etc.
- Telegram already lets you react with emojis, stickers, etc.
- Telegram message reactions (👀) provide a lightweight read receipt without breaking conversation flow.
Supported LLM Providers
TeLLMgramBot selects the LLM provider automatically based on the model name:
| Model prefix | Provider | Example models |
|---|---|---|
gpt- |
OpenAI | gpt-4o, gpt-4o-mini, gpt-5-mini |
claude- |
Anthropic | claude-sonnet-4-6, claude-haiku-4-5 |
Simply set chat_model (and optionally url_model) in your config.yaml to any supported model and supply the corresponding API key - no other changes needed.
Directories
TeLLMgramBot creates the following directories:
configs- Bot configuration and model parametersconfig.yaml- Bot settings: owner, model names, token limits, search limits, nickname/initials, database namemodels.yaml- Token limits for each LLM model (pre-populated on first run)
prompts- Bot personas and URL analysis templatestest_personality.prmpt- Sample bot personality (multi-provider, can be renamed)url_analysis.prmpt- URL summarization prompt template- A system appendix is automatically appended to every persona at runtime, teaching the LLM about cross-chat memory and search behavior. User messages include speaker annotations with chat context and timestamps so the LLM always knows who is speaking, in which chat, and when.
logs- Bot instance logs (one per startup, named after the bot's Telegram username orlog_nameconfig, e.g.my_bot_2026-03-29_10-30-45.log)- Logs include anonymized Telegram IDs for privacy. Console shows INFO-level TeLLMgramBot messages only, prefixed with an
[identity label](the bot's Telegram username by default, orlog_namewhen configured). - Bot keeps the 10 most recent logs per bot instance, automatically pruning older ones.
- Pass
-vor--verboseon startup for DEBUG-level logging.
- Logs include anonymized Telegram IDs for privacy. Console shows INFO-level TeLLMgramBot messages only, prefixed with an
data- SQLite database (defaultconversations.db, customizable viadb_nameconfig) storing all messages, users, and chats- Users manage their data via
/forgetand/privatecommands.
- Users manage their data via
Environment Variables for Paths
Override default directory locations by setting these environment variables (useful for containerized deployments):
| Variable | Purpose | Default |
|---|---|---|
TELLMGRAMBOT_CONFIGS_PATH |
Directory containing config.yaml and models.yaml |
{exec_dir}/configs |
TELLMGRAMBOT_PROMPTS_PATH |
Directory containing prompt files | {exec_dir}/prompts |
TELLMGRAMBOT_LOGS_PATH |
Directory for log files | {exec_dir}/logs |
TELLMGRAMBOT_DATA_PATH |
Directory containing conversations.db |
{exec_dir}/data |
If unset, all paths default to subdirectories of the execution directory (the directory containing your entry-point script).
API Keys
TeLLMgramBot supports four API keys, each loadable from environment variables or .key files:
| Key | Env Var | File | When required |
|---|---|---|---|
| OpenAI | TELLMGRAMBOT_OPENAI_API_KEY |
openai.key |
For gpt-* models |
| Anthropic | TELLMGRAMBOT_ANTHROPIC_API_KEY |
anthropic.key |
For claude-* models |
| Telegram | TELLMGRAMBOT_TELEGRAM_API_KEY |
telegram.key |
Always required |
| VirusTotal | TELLMGRAMBOT_VIRUSTOTAL_API_KEY |
virustotal.key |
For URL analysis |
Missing provider keys (OpenAI or Anthropic) disable chat and URL analysis but allow the bot to start. Missing VirusTotal disables URL analysis. Telegram key is required - the bot will not start without it.
Key files are created in the execution directory (or TELLMGRAMBOT_KEYS_PATH for legacy deployments). Alternatively, set environment variables before launching, e.g.:
os.environ['TELLMGRAMBOT_OPENAI_API_KEY'] = my_vault.get('openai_key')
os.environ['TELLMGRAMBOT_ANTHROPIC_API_KEY'] = my_vault.get('anthropic_key')
os.environ['TELLMGRAMBOT_TELEGRAM_API_KEY'] = my_vault.get('telegram_key')
os.environ['TELLMGRAMBOT_VIRUSTOTAL_API_KEY'] = my_vault.get('virustotal_key')
Commands and Interactions
Available Commands
/nick <name>- Set your nickname (for bot use in group chats)./forget- Clear your conversation history. Shows a confirmation prompt before deletion. In private chats, clears everything and resets all active sessions. In group chats, removes only your messages./private- Toggle private mode (private chats only). When ON, your messages are excluded from group context loading./tools- List all registered tools available to this bot instance (admin-only, private chat only). Shows the built-in search_messages tool and any webhook or MCP tools defined in config.yaml./help- Display available commands and usage information. In private chats, if you are a bot owner, also shows administrator-only commands (/start,/stop,/wipe,/tools).
Group Chat Triggers
The bot responds in groups when you:
- Mention the bot by username (e.g.,
@botname) - Mention the bot by nickname or initials (configured via
config.yaml) - Reply directly to one of the bot's messages
If a message explicitly @mentions another account, the bot defers with "Looks like that's for @OtherBot!" instead.
Private Chat Behavior
In private chats, the bot responds to all your messages. If you reply to an earlier message in the conversation that is not already in the bot's context window, that message is automatically surfaced as inline context so the bot can understand the full conversation thread.
Read Receipt (Group Chats Only)
When the bot is triggered in a group and about to respond (not deferring to another bot), it immediately sends a 👀 emoji reaction on your message as a read receipt acknowledgement (falls back to "Got it!" text reply on older Telegram clients). This confirmation arrives before the full LLM response, providing quick feedback that the bot received your message.
Bot Setup
- Ensure API keys are set up and your Telegram bot is created via BotFather.
- Install TeLLMgramBot:
pip install TeLLMgramBot - Configure the bot via
config.yaml(created on first run):bot_owner: Telegram username(s) with admin access (required, no@). Accepts a single string or a YAML list of usernames.chat_model: LLM model for conversation (e.g.gpt-4o-miniorclaude-sonnet-4-6)url_model: LLM model for URL analysis (e.g.gpt-4oorclaude-haiku-4-5)bot_nickname/bot_initials: Names the bot responds to in groupsdb_name: Optional custom database filename without extension (e.g.MyBotcreatesMyBot.db); omit for defaultconversations.db. Use distinct names when running multiple bot instances in the same directory.log_name: Optional label used for the console prefix and log filename (e.g.MyBotproduces[MyBot] INFO: ...on the console andMyBot_{timestamp}.log); omit to use the bot's Telegram username. Useful for multi-platform deployments sharing the same config.token_limit: Max tokens (optional; defaults to model's maximum)search_limit: Max search results (optional; defaults to 30)archive_days: Days before messages are eligible for archival (optional; default 60, minimum 1). Older messages are distilled into daily summaries, then progressively compressed into monthly digests. Once archived their respective raw messages do not return to the LLM context any more, only when searching messages.allow_local_webhooks: Set totrueto permit webhook/MCP URLs targeting loopback or link-local addresses (optional; defaultfalse). Useful when tools like Home Assistant run on the same host.tools: Optional list of webhook and MCP tool definitions (admin-only, private chat only). See docs/tools.md for schema and examples.
- Disable group privacy mode in BotFather:
With privacy mode enabled (default), the bot won't receive group messages that don't mention it, so it can't index other bots or load cross-chat context./setprivacy -> select your bot -> Disable - Run the bot:
from TeLLMgramBot import TelegramBot telegram_bot = TelegramBot.set() telegram_bot.start_polling()
Once you seeTeLLMgramBot polling..., the bot is online. - Type
/helpin Telegram to see all available commands.
Resources
- GitHub repository python-telegram-bot has guides to create a Telegram bot.
- For more information on OpenAI models and token limits:
- For more information on Anthropic Claude models:
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file tellmgrambot-3.13.2.tar.gz.
File metadata
- Download URL: tellmgrambot-3.13.2.tar.gz
- Upload date:
- Size: 71.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.9.25
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
72a15109970f2d80e07ab9f1d47d60bb0143626a40c073aa953d3c0a1d7b360c
|
|
| MD5 |
bf63657b902c114443de9cc93d44a1fc
|
|
| BLAKE2b-256 |
743fd7586a85a6634957b5796472d55e4b6b51e3d4d000e7e355a00ba50e8cba
|
File details
Details for the file tellmgrambot-3.13.2-py3-none-any.whl.
File metadata
- Download URL: tellmgrambot-3.13.2-py3-none-any.whl
- Upload date:
- Size: 73.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.9.25
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6257e9b6a4f6cbcdeec34f8f40ed769cc1dbffd9be42496d24b3e67b25010d82
|
|
| MD5 |
5b97634df576a3216dfe05423a989faf
|
|
| BLAKE2b-256 |
e3eeba4ccb9ac01040511da745351bfd9eb238dfce2abd9155aa6f34d722c2a9
|