WeMAIdeStart a project ↗

WEMAIDE / INSIGHTS / ENGINEERING

Telegram bot AI integration: connect a model without handing it the product rules

A practical architecture for AI in a Telegram bot: approved context, bounded model tasks, validated responses, stored state and recovery, illustrated by Leela and Horoscope.

Engineering8 min read
A Telegram bot backend validates a model result before an application action

Telegram bot AI integration is a backend responsibility. Telegram receives the conversation; your application prepares the permitted context, asks a model to perform a bounded task, validates the answer and decides what the bot should send or change. The model is one component of that path.

Before choosing a model, describe the result. Is the bot explaining a known rule, interpreting a user’s situation, classifying a request or drafting content for review? These tasks need different context and different failure boundaries. A bot that answers questions is not automatically authorised to change account records or make commitments.

Keep the conversation state outside the model

The backend should know the current user state, permissions and next valid actions. A model response may propose an interpretation, but it should not silently decide that a user has paid, that an approval is current or that an irreversible operation is permitted. Represent those facts in application state and check them before acting.

Telegram update → user and state checks → selected context
→ bounded AI request → response validation
→ approved application action → stored result → Telegram reply

Treat incoming updates as events that may be repeated

Telegram supports webhooks and long polling as alternatives for receiving updates. Keep a record of the update or action identity so a repeated event does not create a second model task or duplicate an application transition. A webhook acknowledgement and a completed AI task are separate concerns; long work needs its own processing state.

Send the context the task needs

Separate trusted product instructions from user text and retrieved material. Decide which facts can leave your application and which should remain local. A small task-specific context is easier to review than an entire unfiltered chat history. User messages and external documents are inputs to interpret, not new permission to run tools or change rules.

  • Use stable product rules and a versioned instruction set.
  • Include only the user state and source facts needed for the current task.
  • Set output and usage limits appropriate to the operation.
  • Avoid logging secrets or unnecessary personal message content.
  • Make unsupported or conflicting information a visible unknown rather than a fabricated fact.

Validate meaning as well as structure

A valid JSON response can still be wrong. Check required fields and permitted values, then apply the product’s semantic rules: does a referenced record exist, is this transition allowed, and does the answer rely on an approved source? For an external action, the application must enforce permissions even if the model requested a tool call.

If quality cannot be established, stop or ask for review. Do not turn an output parser into an automatic retry loop that spends indefinitely. Define an attempt limit, a time budget and an operator path for work that remains unresolved.

Leela: rules define the experience, AI interprets context

Our Leela Telegram product combines canonical game rules with contextual AI interpretation and compact memory. The transferable boundary is straightforward: code protects the allowed progression, while the model helps interpret the situation within that progression. A fluent response is not permission to invent a new game rule.

Horoscope: generate ahead of the delivery request

Horoscope uses a prepared content pool stored in PostgreSQL, then selects and delivers content according to the subscriber’s preferences. It demonstrates that an AI-enabled bot does not need a live generation call for every interaction. When content can be prepared and reused, delivery can remain a separate deterministic task.

This design does not apply to every conversation. If a response depends on unique current information, the model task may need to run at request time. Choose the boundary from the product need and verify that cached or prepared material remains appropriate.

Handle provider and delivery failures separately

A failed model request and a failed Telegram send are different states. Store the validated answer before delivery where appropriate, so a send retry does not automatically regenerate it. Respect Telegram’s retry_after when flood control applies. A timeout with an uncertain send result needs a deliberate duplicate-versus-missed-message policy; a local database record alone does not guarantee exactly-once delivery.

Check the boundaries before launch

  • Repeat the same update and confirm it cannot repeat a consequential action.
  • Supply a request that conflicts with the product rules and verify that the rules still win.
  • Test missing facts, malformed output and a plausible but unsupported answer.
  • Make the model provider unavailable and verify a bounded failure path.
  • Change a record after a draft was approved and verify that stale approval cannot authorise the changed action.
  • Test Telegram send failure without forcing a new generation request.

The useful first release is one complete and inspectable task. Once that boundary works, add integrations or a richer interface where the user journey needs them. More autonomous behaviour should follow evidence about the task, not simply the availability of a more capable model.

Built from the work.WeMAIde designs and ships AI software, apps, Telegram products and automation systems.

FROM THINKING TO PRODUCT

Need something like this built?

Tell us what needs to work. We will come back with the clearest next step.

Discuss it in Telegram ↗