The Bot API client, with the bot's token.
callpostsparamsto a method and succeeds with itsresult. Objects inparamsare sent as JSON; withfilesthe body is multipart and each object is a JSON string part. Awriteis never repeated once the request left, and a failure that may have landed isuncertain;retry(default true) retriesretryfailures aschat_adapter.retry_safedoes, waiting out a 429'sretry_afterunless it passesmax_retry_after: then the call failsRateLimitedat once.timeout, when given, bounds each request: one without an answer by then failsTransportwith detailtimeout,uncertainfor a write.- An answer with
ok: falsefails with the reason for itserror_codeandparameters. Itsdetailis a fixed string, never Telegram's description, which can quote the message. Amigrate_to_chat_idgivesNotFoundwith detailchat_migratedand aTelegramChatMigratedcause. filestreams a file by itsfile_pathfromgetFile, failingTooLargeonce more thanmax_bytesarrive.bot_idis the numeric id in front of the token's colon.- The error's
opis the method.
Attributes#
| Attribute | Type | Description |
|---|---|---|
bot_id | str | The numeric id in front of the token's colon. |
environment | Environment |
|
Functions#
__init__#
__init__(*, http, token, bot_id, environment, api_url, max_retry_after=None) -> None| Parameter | Type | Description |
|---|---|---|
http | HttpClientService[HttpClientError, Never] | |
token | Redacted[str] | |
bot_id | str | |
environment | Environment | |
api_url | str | |
max_retry_after | Duration | 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.
| Parameter | Type | Description |
|---|---|---|
method | str | |
params | Mapping[str, object] | None = None | |
write | bool = False | |
files | Sequence[Upload] = () | |
retry | bool = True | |
timeout | DurationInput | 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 oncefile#
file(file_path, *, max_bytes) -> Stream[bytes, ChatError]Streams the file at file_path; see the class.
| Parameter | Type | Description |
|---|---|---|
file_path | str | |
max_bytes | int |
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>"},
)
)