Run a pyfect.chat bot on Telegram with the Bot API adapter: a webhook checked by its secret token or long polling, commands, buttons and tests.
pyfect.chat.telegram is Effect's @effect/chat-telegram, the Telegram Bot API adapter for
Chat. telegram_chat.layer(token=...) registers it for one bot and needs only
an HttpClient. It calls the Bot API over HTTP, with no SDK, and keeps the token out of
spans, logs and errors. A thread is telegram_chat.thread(chat_id), or
telegram_chat.thread(chat_id, message_thread_id) for a forum topic.
Posts, edits, deletes, replies, downloads, get_thread and get_user work through Chat as
on any adapter. Posts and edits go out as rich messages, and the Markdown is escaped first so
that text a user typed reaches Telegram as text: no raw HTML, image, math, spoiler or link
other than http, https and mailto, with nesting, tables and inline nodes kept within
Telegram's limits. Files, buttons and commands are off until you turn them on with
unverified_files, unverified_buttons and unverified_commands. There is no private
(ephemeral) reply: one is refused through chat_interaction.Handler.refused as Unsupported
with detail ephemeral, and never posted. chat_interaction.respond and defer answer
privately unless told otherwise, so a Telegram bot passes visibility="public".
That escaping keeps your own Markdown safe to send, but text a user wrote still forms syntax
inside it: a display name of [x](https://evil.example) is a live link. Put such text
through telegram_chat.escape_markdown first, as in
f"Approved by {telegram_chat.escape_markdown(name)}", and it shows as typed.
The webhook#
telegram_chat.layer_webhook(path=..., secret_token=...) adds a POST route to an
HttpRouter. Every request is untrusted until its X-Telegram-Bot-Api-Secret-Token header
equals secret_token, compared in constant time; without it the answer is 401 and the body
is never read. The secret must be 32 to 256 characters of A-Za-z0-9_-. A body over
max_body_bytes (1 MiB) is answered 413, and one that is not JSON, nests past 64 levels or
is not an update, 400.
Messages go to the ChatHandler, and clicks and commands to the
chat_interaction.Handler, both read from the layer's context when it is built, as for
polling. When the handler fails NotAccepted or passes its deadline (10
seconds), the route answers 503 and Telegram sends the update again. Delivery is at least
once: claim telegram_chat.delivery_key before work that must not run twice.
import json
from typing import Never
import pyfect as fx
from pyfect import layer
from pyfect.chat import chat, chat_handler, chat_markdown
from pyfect.chat.chat import Chat
from pyfect.chat.chat_event import ChatEvent, MessageCreated
from pyfect.chat.telegram import telegram_chat
from pyfect.http import body as http_body
from pyfect.http import client, router
from pyfect.http import request as http_request
from pyfect.http import response as http_response
from pyfect.http.request import HttpClientRequest
from pyfect.redacted import make as redacted
SECRET = "Xq3_k9-ZpT7wLm2vRb8nYc4dHf6sJg1a"
# Answers every message that mentions the bot with **bold** Markdown.
def on_event(event: ChatEvent) -> fx.Effect[None, Never, Chat]:
if not isinstance(event, MessageCreated) or not event.message.mentions:
return fx.void
reply = chat_markdown.post(event.thread, "Deploying **docs** now")
return reply.as_void().or_die()
# The Telegram app: the webhook, the adapter and the handler.
app = (
telegram_chat.layer_webhook(path="/telegram", secret_token=redacted(SECRET))
.pipe(layer.provide(chat_handler.layer(on_event)))
.pipe(layer.provide_merge(telegram_chat.layer(token=redacted("123456789:AAH-example"))))
.pipe(layer.provide_merge(chat.layer))
)
# Stands in for the Bot API here, printing what the bot sends.
def bot_api(request: HttpClientRequest) -> fx.Effect[http_response.HttpClientResponse]:
method = request.url.rsplit("/", 1)[-1]
assert isinstance(request.body, http_body.Bytes)
sent = json.loads(request.body.body)
if method == "getMe":
result: object = {"id": 123456789, "is_bot": True, "username": "deploy_bot"}
else:
print(method, sent["chat_id"], repr(sent["rich_message"]["markdown"]))
result = {"message_id": 2, "date": 1794600001}
body = json.dumps({"ok": True, "result": result})
return fx.succeed(http_response.make(request, body))
# What Telegram would send when someone mentions the bot in a group.
update = {
"update_id": 900001,
"message": {
"message_id": 1,
"date": 1794600000,
"chat": {"id": -1001234567890, "type": "supergroup", "title": "Ops"},
"from": {"id": 4242, "is_bot": False, "first_name": "Ada"},
"text": "@deploy_bot ship the docs",
"entities": [{"type": "mention", "offset": 0, "length": 11}],
},
}
@fx.gen
def program():
http = yield from router.in_memory_client(app)
body = http_request.post("http://x").body_text(json.dumps(update), "application/json").body
headers = {telegram_chat.SECRET_HEADER: SECRET}
answered = yield from http.post("http://localhost/telegram", body=body, headers=headers)
print("answered", answered.status)
unsigned = yield from http.post("http://localhost/telegram", body=body)
print("without the secret", unsigned.status)
fx.run_blocking(fx.scoped(program).pipe(fx.provide(client.layer_test(bot_api))).or_die())telegram_chat.set_webhook(url=..., secret_token=...) registers the webhook with the update
types the adapter reads; the adapter never calls it itself. An app that records request
headers adds telegram_chat.SECRET_HEADER to its redacted header names.
Long polling#
telegram_chat.layer_polling() reads updates with getUpdates instead, for a process that
runs without a public URL. Updates run one at a time, in order, and each is confirmed only
after it ran. An update the handler does not accept is retried three times and then logged
and skipped, so one bad update cannot stall the bot. Each getUpdates gets the long poll
(timeout, 30 seconds) plus 3 seconds to answer, so a connection that died without a reset
cannot stall it either: the call is given up and retried with a backoff.
A call Telegram answers 429 is retried after its retry_after, however long. Pass
max_retry_after to telegram_chat.layer, such as "1 minute", and a longer wait fails
the op at once with RateLimited, its retry_after the wait Telegram asked for. The layer fails with detail conflict
when a webhook is set or another process polls.
Commands and buttons#
With unverified_commands=True, a message starting with /name goes to the handler's
command. telegram_chat.set_commands(group) registers a group's commands with Telegram;
an id must be [a-z0-9_]{1,32}, as Telegram allows no -. A command gets its answer in
public, as a reply.
With unverified_buttons=True, actions become an inline keyboard. A click reaches the
handler only when its data matches a button in Telegram's own copy of the message, and every
click is answered within click_deadline (2.5 seconds) so the user's client stops waiting.
Testing#
telegram_chat.normalize(update, NormalizeContext(bot_id=...)) is a pure function from an
update's JSON to events, so captured payloads test it directly, and
TelegramChatService.receive runs one update for your own transport. For writes, provide an
HttpClient from pyfect.http.client.layer_test that answers like the Bot API, as the
example above does. Effect's conformance suite runs against the adapter this way in pyfect's
own tests.
Reference: telegram_chat,
telegram_bot_api.