This repository contains an advanced Telegram bot script integrated with Mistral AI's large language models. Unlike traditional LLM bots that process text linearly and in isolation, this project implements an architecture capable of mapping the "social geometry" of a group chat, dynamically adapting its behavior based on the actors involved and semantic triggers.
This project started with a very simple and lighthearted goal: creating a sarcastic chatbot to roast and entertain my group of friends in our Telegram chat using an LLM.
However, as the bot started interacting in a lively group environment, I ran into several LLM behavior challenges. What began as a weekend joke turned into a fascinating engineering exercise in social context awareness and prompt hardening.
Below are the main architectural and technical problems I encountered and how this bot solves them.
Standard LLM integration into Telegram group chats typically suffers from several technical and behavioral limitations. This script introduces targeted solutions for the following challenges:
Traditional bots only receive the raw text of the latest message. They lack awareness of who is speaking to whom, whether a message is a direct reply to a specific user, or if it mentions third parties.
- Solution: The bot extracts Telegram metadata (
reply_to_message,entities) and reconstructs a "Social Scene" that describes the relational dynamics (e.g., "User A is replying to User B while mentioning User C"), enabling the LLM to generate contextually aware responses.
When an LLM receives structured prompts containing logs or usernames (e.g., User: text), it tends to interpret the input as if it was the beginning of a theatrical script or a fictional story. Consequently, it responds by simulating subsequent dialogues for other users instead of participating as a single chat member.
- Solution: Implementation of a strict "anti-scriptwriting" prompt engineering framework with explicit negative instructions and defined semantic boundaries within the user prompt (
CONTEXTvsPREVIOUS MESSAGEvsREPLY NOW).
As mentioned above this started as a weekend joke, so every choice was made in relation of the usage of free API keys given from Mistral AI. This makes the idea of parsing every message exchanged in the chat into the LLM to keep track of the conversation context a nightmare for credit consumption.
Maintaining a complex personality by passing hundreds of lines of behavioral rules (e.g., "if X is mentioned do Y, if Z writes respond like this") in every single API call quickly saturates the model's context window and increases computational costs.
- Solution: A modular and conditional approach. Specific rules for users (
USER_RULES) and topics (DYNAMIC_RULES) are loaded into memory and injected into thesystem promptdynamically, exclusively when their respective IDs or keywords are detected in the current interaction.
Generic bots maintain the exact same tone with every user, resulting in a flat or predictable user experience.
- Solution: Introduction of a cross-configuration matrix. The bot can simultaneously combine its core personality (
SYSTEM_CORE), specific rules for the sender, rules for the user being replied to, and rules for the topic being discussed.
The bot's execution flow consists of five sequential phases handled within the asynchronous reply_logic function:
- Ingestion and Whitelisting: The incoming message is intercepted. A strict boolean check is performed against the authorized ID arrays (
AUTHORIZED_IDS). If the chat or user is not whitelisted, execution terminates immediately to preserve resources and security. - Identity Resolution (
PEOPLE_MAP): Native numerical Telegram IDs and textual@usernamesare mapped to logical string identifiers ("Logical Names") to ensure consistency across downstream conditional checks. - Semantic Analysis and Normalization: The text of the current message and any replied-to message is concatenated, normalized to lowercase (
.lower()), and scanned via pattern matching to detect triggers defined in the dynamic rules. - Dynamic Prompt Assembly:
- The
system promptis initialized with the core personality guidelines. - Specific
USER_RULESare appended for every entity detected within the Social Scene. DYNAMIC_RULESmodules are appended for each intercepted topic trigger.
- The
- Payload Execution: The bot sends a
typingchat action to Telegram to optimize user experience, and the finalized structured payload is forwarded to the Mistral chat completion API.
The bot is developed in Python 3.8+ and uses official libraries for asynchronous interaction with Telegram and Mistral AI.
pip install python-telegram-bot mistralai