Examples
Complete bots in Python and Node.js without third-party libraries, with commands, buttons and answers to presses.
Both examples do the same: set commands, answer /start with a message with buttons, answer
presses and echo any other text. They get updates by long polling and need nothing but the
standard library.
export COMON_API='https://comon.chat/bot/v1' # your federation's address
export COMON_TOKEN='cbt_...'Python 3.9 or newer.
import json
import os
import time
import urllib.error
import urllib.request
API = os.environ["COMON_API"]
TOKEN = os.environ["COMON_TOKEN"]
def call(method, **params):
request = urllib.request.Request(
f"{API}/{method}",
data=json.dumps(params).encode(),
headers={"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(request, timeout=60) as response:
return json.load(response)["result"]
except urllib.error.HTTPError as error:
body = json.load(error)
retry = body.get("parameters", {}).get("retry_after")
if retry:
time.sleep(retry)
return call(method, **params)
raise RuntimeError(f"{method}: {body['error_code']} {body['description']}")
def on_message(message):
chat = message["chat"]["id"]
text = message.get("text", "")
if text.startswith("/start"):
call("sendMessage", chat_id=chat, text="Hi! Press a button.",
buttons=[[{"text": "Toss a coin", "callback_data": "coin"}],
[{"text": "Comon website", "url": "https://comon.chat"}]])
elif text:
call("sendMessage", chat_id=chat, text=text, reply_to_message_id=message["message_id"])
def on_callback(query):
if query["data"] == "coin":
side = "Heads" if time.time_ns() % 2 else "Tails"
call("answerCallbackQuery", callback_query_id=query["id"], text=side)
else:
call("answerCallbackQuery", callback_query_id=query["id"])
def main():
call("setMyCommands", commands=[{"command": "start", "description": "Start"}])
offset = None
while True:
params = {"timeout": 50, "allowed_updates": ["message", "callback_query"]}
if offset is not None:
params["offset"] = offset
for update in call("getUpdates", **params):
offset = update["update_id"] + 1
if "message" in update:
on_message(update["message"])
elif "callback_query" in update:
on_callback(update["callback_query"])
if __name__ == "__main__":
main()What next
- Move to a webhook and verify the signature: updates.
- Commands with options and suggestions: commands.
- Answers only the presser sees: ephemeral messages.
- Never send twice after a network failure:
idempotency_key.