Serverless Telegram bot built with grammY and Serverless Framework.
Everything at a glance:
How one Telegram update becomes a reply. Configuration, state and alarms are shown in the overview above:
Agent commands pass the cyber check before the main model or tools:
What the activity worker writes and how the stats page stays live:
Diagram sources are in .github/diagram. Run
bun run diagram after changing them.
The webhook in src/telegram-bot returns quickly after dispatching FIFO SQS
jobs. A Telegram chat id is the message group id, so each chat stays ordered
while different chats run in parallel.
activity-workerrecords statistics, chat events, AI history, and live UI updates.telegram-reply-workerhandles registered non-agent commands.agent-workerhandles commands fromAGENT_COMMANDS, dynamic commands, reply gating, model calls, and tools.websocketsserves authenticated live statistics.sharp-rendererrenders PNG cards and charts.video-trimmercuts and reframes Telegram videos and video notes with ffmpeg.currency-schedulerposts scheduled currency digests.admin-apiverifies Telegram OIDC logins and exposes owner-only chat configuration reads and writes.
DynamoDB chat configuration controls AI access. Ingress checks it before enqueueing agent work, and the agent worker checks it again before processing. Redis leases prevent duplicate Telegram replies when SQS redelivers a message; activity writes are independently replay-safe. Worker queues use one-message batches, partial batch responses, and separate dead-letter queues. A failed record backs off exponentially from 30 seconds instead of waiting out the queue's visibility timeout, so one failure does not hold its chat's FIFO group for an hour. If its Redis lease may still be held (a failed release, or a lease write whose response was lost), it keeps the queue timeout, which outlasts the lease, so the retry is not skipped as a duplicate. Telegram 400/403 rejections (deleted command, blocked or kicked bot) are not retried.
The shared Telegram client queues successful outgoing messages for the activity worker, including command media, agent replies and failure notices, and scheduled currency posts. These history-only jobs preserve Telegram text, captions, rich content and media file IDs without adding bot messages to user statistics. History uses the existing AI allowlist and 24-hour retention; raw history exposes full messages while recent context contains previews and media markers.
If both an agent response and its failure notice cannot be delivered, the job is retried, unless Telegram permanently rejected the notice. Once any response part has been acknowledged by Telegram, a later delivery failure does not replay the whole job, avoiding duplicate response parts. Delivery errors remain in the logs.
Permanent chat events and user statistics are retained on stack deletion or resource replacement, with DynamoDB deletion protection and point-in-time recovery enabled.
Current, replied-to, and album media is registered in structured
MESSAGE_CONTEXT and MEDIA blocks with stable media_id values and source
message metadata. Historical media remains text-only until the model selects an
exact Telegram message_id; load_chat_media then downloads only that
message's images and exposes them on the next model round. Old images are never
preloaded automatically.
The agent waits for album messages and downloads request media only after the reply gate accepts the message (or an accepted agent command bypasses it). Downloads run at most three at a time, each with a 10-second deadline covering metadata and body transfer. The 19 MiB per-file limit is checked before and during streaming; unavailable or oversized files are skipped.
Media tools use exact ids for explicit selection, omit mediaIds for current
request media, and use [] for text-only generation. Inline inputs are limited
to 14 MiB for Google media tools, and one request may produce at most one
generated media result.
Omni only edits or extends short clips, so a longer selected video or video
note is re-downloaded and cut to its first seconds by the video-trimmer
lambda once the generation slot is claimed. The clip is also centre-cropped to
the 9:16 or 16:9 frame the generation was asked for, because Omni outputs
nothing else and would otherwise re-frame a square video note on its own.
Padding is avoided on purpose: a generator copies black bars into its output.
The ffmpeg layer is built by bun run prepare:ffmpeg-layer, which build and
deploy run for you.
Delivery uses Telegram's native media methods with document fallback. Google
media calls use GEMINI_API_KEY
(GOOGLE_GENERATIVE_AI_API_KEY also works).
Voice messages use Gemini 3.8 Flash TTS through the Google Interactions API,
with Kore as the default voice. The generate_voice tool accepts a built-in
voice or reusable voice_... ID, a delivery style, and a voice_description
for a fictional character's timbre. Described voices are created for one
request and deleted after synthesis, including on failure; cleanup failures
are logged. Existing voice IDs are never deleted. Voice design and speech
generation each get a 90-second deadline, with a 240-second total tool budget
including encoding and cleanup. Audio is converted from WAV to Ogg/Opus by
the shared ffmpeg layer attached to the agent worker. The 32 MiB WAV and 8 MiB
encoded-audio bounds cover the model's full audio output budget, including
long passages spoken slowly.
The agent worker has a 13-minute deadline to accommodate model fallbacks,
data-gathering rounds and voice generation before delivery. Every model and
tool call in the tool loop is clamped to the Lambda's remaining time minus a
60-second delivery reserve, and a tool that has no time left is never started. Its Redis
processing lease lasts 14 minutes; the agent queue's visibility timeout is
78 minutes (six times the worker deadline), which only applies when the worker
is killed before it can schedule its own retry. Rate-limited (serial) tools
run one at a time, at most two per round, while other calls in the round run
in parallel. Excess serial calls return explicit tool results so the model can
combine queries or request them in a later round. If the model cannot write a
final answer, only tools marked presentable (web search) may be sent as-is;
raw tool output such as history or memory never reaches the chat.
Registered agent commands (including /q and /o) bypass engagement gating,
but first pass a text cyber-abuse check using the
OpenAI Decisions API
with Luna. A custom predicate evaluates the current request, its replied-to
text and the last 10 history lines, so a request that only points at earlier
messages ("do what was asked above") is judged against them; a cyber-abuse
probability of 0.5 or above blocks further processing.
Classification keeps the original stripped request before media instructions are
added. A registered command identity triggers the check even when a direct or
retried delivery omits the ingress bypass flag.
This is the application's classification rubric, not an official OpenAI ban-risk
score. One 429 or 5xx is retried within the same timeout; classification
refusals, invalid responses and other API errors fail closed.
Rejected requests receive a short refusal generated by the cheap safety role, without passing the original request, history or tools to that generation call. A fixed message covers refusal-generation failure; classification outages get a retry-later message. Allowed commands keep their normal chat model and reasoning. The check covers text, replied-to text and recent history, not the contents of media or URLs. It reduces abuse reaching the main model and does not guarantee account access.
Agent model calls and Decisions share a hashed, stable Telegram sender identifier across chats. Anonymous/channel messages use their sender-chat identity, with a chat identity as the last fallback. Chat IDs remain separate in logs and metrics.
bun run eval:command-safety runs a small labelled live evaluation with
OPENAI_API_KEY.
It makes classification calls only, without writing production metrics; it never
invokes Astra or executes the labelled requests. An optional output path saves
the report.
Language models, reasoning effort and fallbacks are configured in
src/agent-worker/agent/models.ts. /o runs Claude Fable 5.2 at xhigh
effort (ANTHROPIC_API_KEY) and falls back to GPT-6 Astra at medium reasoning.
Chat roles also cap the tool loop: /o may run eight tool rounds, other
messages four, and no new round starts after 150s or 90s respectively. A loop
that stops before the model reads its last tool results gets a final answer
pass without tools.
Media models belong to their services;
the shared Gemini image model is defined in src/common/utils/gemini-image.utils.ts.
Image routing and quality are configured in
src/agent-worker/services/image-generation.ts:
| Request | Model | Quality | Fallback |
|---|---|---|---|
| Ordinary image request | Gemini 3.1 Flash Lite Image | Provider default | GPT Image 2.6 Flare (low) |
/e, /ee, /gp, /de |
GPT Image 2.6 Sunburst | medium | None |
/ge |
Gemini 3.1 Flash Lite Image | Provider default | None |
GIF request, including /gif |
GPT Image 2.6 Sunburst | medium | None |
Each image model is called once. Ordinary requests reserve 55 seconds for
each provider; explicit commands allow 110 seconds for the selected model.
The tool has a 120-second total budget. tool.model_call records each actual
model, with fallbackFrom and toolCallId to connect related calls.
generate_gif creates a short looping animated GIF from text with the Images
API's gif output format. The API's own default of 9 frames at 200 ms plays at
5 fps and looks choppy, so the tool defaults to 16 frames at 80 ms (12.5 fps,
1.28 seconds). The agent sets frameCount (2-16) and frameDurationMs
(20-2000, in 10 ms steps) only when a user asks for a frame rate, speed or
length; out-of-range values are clamped to the API limits. With selected media,
the same Sunburst model uses /images/edits with gif output. Still images
are passed as references; one selected GIF or Telegram MP4 animation is rebuilt
from its first and last reference frames through the existing video trimmer.
This recreates the animation rather than preserving its exact original motion.
GIF edit requests stay with Sunburst; Omni handles explicitly requested video
output. The AI SDK does not accept the gif format yet, so these calls go to
the Images API directly. One attempt gets 160 seconds within a 170-second API
budget; the tool also reserves 60 seconds for frame extraction. The GIF is
uploaded with sendAnimation.
The API caps a GIF request by a total pixel budget it does not publish, and it
rejected 24 frames left at size: auto. The tool therefore asks for the
largest square frame, in multiples of 16 up to 1024 px, that keeps every frame
within the documented 4K image maximum: 720 px for 16 frames. If the API still
rejects the request with HTTP 400, it logs gif_gen.timing_fallback with the
API error and retries once, within the same deadline, with the API's own
timing (9 frames of 200 ms at size: auto).
Docker must be running. Start Serverless Offline and its ElasticMQ container:
bun run startOutside AWS, video trimming and voice encoding use ffmpeg on PATH;
point FFMPEG_PATH at a binary to override that.
During serverless-offline, the read-only chat authorization gates are open,
FIFO deduplication ids include a nonce, and Redis worker leases are bypassed.
This lets the same Telegram message_id run repeatedly without reading the
production chat-configuration table. The framework alone sets IS_OFFLINE;
deployed Lambdas never receive it. Configuration writes are not emulated.
The admin dashboard uses Telegram's authorization-code OIDC flow. The UI
exchanges the one-time code server-side, then this service verifies the signed
Telegram ID token and requires its user id to equal BOT_OWNER_ID. Successful
logins receive a separate 12-hour admin session; AWS credentials are never sent
to the UI.
Configure these deployment values:
- repository variable
TELEGRAM_OIDC_CLIENT_IDfrom BotFather; - repository secret
ADMIN_SESSION_SECRETwith at least 32 random characters; - repository secret
STATISTICS_ACCESS_SECRETwith at least 32 random characters, separate from the webhook secret, to sign/statslinks; - the existing repository variable
BOT_OWNER_IDwith the sole allowed Telegram user id.
The Lambda role can only scan the chat configuration/statistics tables and read or update the configuration table. It has no Redis, queue, model, or bot token access.
Stop with Ctrl+C so Serverless can remove ElasticMQ cleanly.
bun run audit
bun run biome
bun run tsc
bun test
bun run buildLambda bundles use Serverless Framework 4's built-in esbuild support. The
separate serverless-esbuild plugin and its transitive braces dependency are
not needed. bun run audit runs the full audit without advisory exclusions.
