Skip to content

Instantly share code, notes, and snippets.

@emaballarin
Created July 17, 2024 22:35
Show Gist options
  • Save emaballarin/dabf09612824aac806b48cbbf612469d to your computer and use it in GitHub Desktop.
Save emaballarin/dabf09612824aac806b48cbbf612469d to your computer and use it in GitHub Desktop.
Modern Python implementation of a Telegram bot that only delivers messages
from os import environ
from typing import Dict
from typing import Optional
from typing import Tuple
from httpx import Client
from safe_assert import safe_assert as sassert
def _isnn(c):
return c is not None
def emplace_kv(dictionary: dict, k, v) -> dict:
return {**dictionary, k: v}
class TelegramBotEcho: # NOSONAR
__slots__: Tuple[str, str, str] = ("_url", "_jdata", "_client")
def __init__(
self,
tok_var: Optional[str] = None,
chid_var: Optional[str] = None,
*,
tok: Optional[str] = None,
chid: Optional[str] = None,
) -> None:
sassert(
(_isnn(tok) ^ _isnn(tok_var)) and (_isnn(chid) ^ _isnn(chid_var)),
"Exactly one among `tok` and `tok_var`, and exactly one among `chid` and `chid_var` must be defined.",
)
_tok: str = tok if _isnn(tok) else environ.get(tok_var)
_chid: str = chid if _isnn(tok) else environ.get(chid_var)
self._url: str = f"https://api.telegram.org/bot{_tok}/sendMessage"
self._jdata: Dict[str, str] = {
"chat_id": _chid,
"text": "",
}
self._client = Client(http2=True)
def send(self, msg: str) -> None:
_ = self._client.post(url=self._url, json=emplace_kv(self._jdata, "text", msg))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment