GitHub

TelegramBotApiService

API reference for TelegramBotApiService.

The Bot API client, with the bot's token.

  • call posts params to a method and succeeds with its result. Objects in params are sent as JSON; with files the body is multipart and each object is a JSON string part. A write is never repeated once the request left, and a failure that may have landed is uncertain; retry (default true) retries retry failures as chat_adapter.retry_safe does, waiting out a 429's retry_after unless it passes max_retry_after: then the call fails RateLimited at once. timeout, when given, bounds each request: one without an answer by then fails Transport with detail timeout, uncertain for a write.
  • An answer with ok: false fails with the reason for its error_code and parameters. Its detail is a fixed string, never Telegram's description, which can quote the message. A migrate_to_chat_id gives NotFound with detail chat_migrated and a TelegramChatMigrated cause.
  • file streams a file by its file_path from getFile, failing TooLarge once more than max_bytes arrive.
  • bot_id is the numeric id in front of the token's colon.
  • The error's op is the method.

Attributes

AttributeTypeDescription
bot_idstr

The numeric id in front of the token's colon.

environmentEnvironment

"production", or "test" for Telegram's test environment.

Functions

__init__

__init__(*, http, token, bot_id, environment, api_url, max_retry_after=None) -> None
ParameterTypeDescription
httpHttpClientService[HttpClientError, Never]
tokenRedacted[str]
bot_idstr
environmentEnvironment
api_urlstr
max_retry_afterDuration | None = None
def __init__(
    self,
    *,
    http: HttpClientService[HttpClientError, Never],
    token: Redacted[str],
    bot_id: str,
    environment: Environment,
    api_url: str,
    max_retry_after: Duration | None = None,
) -> None:
    self._max_retry_after = max_retry_after
    self._http = http
    self._token = token
    self._bot_id = bot_id
    self._environment: Environment = environment
    self._api_url = api_url
    self._suffix = "/test" if environment == "test" else ""

call

call(method, params=None, *, write=False, files=(), retry=True, timeout=None) -> Effect[Json, ChatError]

Posts params to method and succeeds with its result; see the class. A None value is left out, as JavaScript's undefined is.

ParameterTypeDescription
methodstr
paramsMapping[str, object] | None = None
writebool = False
filesSequence[Upload] = ()
retrybool = True
timeoutDurationInput | None = None

Returns Effect[Json, ChatError]

def call(
    self,
    method: str,
    params: Mapping[str, object] | None = None,
    *,
    write: bool = False,
    files: Sequence[Upload] = (),
    retry: bool = True,
    timeout: DurationInput | None = None,
) -> Effect[Json, ChatError]:
    """Posts ``params`` to ``method`` and succeeds with its ``result``;
    see the class. A ``None`` value is left out, as JavaScript's
    ``undefined`` is."""
    if _METHOD_NAME.fullmatch(method) is None:
        return fx.fail(_errors.chat_error(method, _errors.invalid_request("invalid_method")))
    deadline = None if timeout is None else from_input_unsafe(timeout)
    once = self._once(method, params or {}, write, files, deadline)
    return retry_safe(once, max_retry_after=self._max_retry_after) if retry else once

file

file(file_path, *, max_bytes) -> Stream[bytes, ChatError]

Streams the file at file_path; see the class.

ParameterTypeDescription
file_pathstr
max_bytesint

Returns Stream[bytes, ChatError]

def file(self, file_path: str, *, max_bytes: int) -> Stream[bytes, ChatError]:
    """Streams the file at ``file_path``; see the class."""
    op = "download"

    def fail(reason: _errors.AnyReason) -> Effect[Never, ChatError]:
        return fx.fail(_errors.chat_error(op, reason))

    @fx.gen
    def make() -> Generator[Effect[Any, ChatError, Any], Any, Stream[bytes, ChatError]]:
        if _FILE_PATH.fullmatch(file_path) is None or any(
            segment in (".", "..") for segment in file_path.split("/")
        ):
            yield from fail(_errors.invalid_response(False, "untrusted_file_path"))
        response = yield from self._send(http_request.get(self._file_url(file_path)), op, False)
        if 300 <= response.status < 400:
            yield from fail(_errors.invalid_response(False, "redirect"))
        if not 200 <= response.status < 300:
            yield from fail(
                _errors.reason_for_api_error(
                    _errors.ApiError(code=response.status), write=False
                )
            )
        too_large = _errors.chat_error(op, _errors.too_large("files", "max_bytes"))
        length = response.headers.get("content-length")
        declared = None if length is None else parse_digits(length)
        if declared is not None and declared > max_bytes:
            yield from fx.fail(too_large)
        received = 0

        def counted(chunk: bytes) -> Effect[bytes, ChatError]:
            nonlocal received
            received += len(chunk)
            return fx.fail(too_large) if received > max_bytes else fx.succeed(chunk)

        return response.stream.map_error(
            lambda error: _errors.chat_error(
                op, _errors.transport(False, type(error.reason).__name__)
            )
        ).map_effect(counted)

    return _stream.unwrap(
        make.with_span(
            "TelegramBotApi.file",
            kind="client",
            attributes={"http.request.method": "GET", "url.path": "/file/bot<redacted>"},
        )
    )