🌙

Пример без SDK

Пример бота без SDK

Минимальный бот на requests и long polling — если по каким-то причинам pykodaribot не подходит.

import time
import requests

TOKEN = "bot_ВАШ_ТОКЕН"
API = "https://api.kodari.ru/msg/bot.php"
HEADERS = {"Authorization": f"Bearer {TOKEN}"}


def call(method, **params):
    r = requests.post(API, params={"method": method}, json=params, headers=HEADERS, timeout=60)
    data = r.json()
    if not data.get("ok"):
        raise RuntimeError(f"{data.get('error_code')}: {data.get('description')}")
    return data["result"]


def poll(offset):
    r = requests.get(API, params={"method": "getUpdates", "offset": offset, "timeout": 20},
                     headers=HEADERS, timeout=40)
    return r.json().get("result", [])


offset = 0
while True:
    try:
        updates = poll(offset)
    except requests.RequestException:
        time.sleep(3)
        continue

    for upd in updates:
        offset = upd["update_id"] + 1

        msg = upd.get("message")
        if msg:
            chat_id = msg["chat"]["id"]
            text = msg.get("text") or ""
            if text.startswith("/start"):
                call("sendMessage", chat_id=chat_id, text="Привет! Я бот Kodari.", reply_markup={
                    "inline_keyboard": [[{"text": "Нажми меня", "callback_data": "clicked"}]]
                })
            elif text:
                call("sendMessage", chat_id=chat_id, text=f"Вы написали: {text}",
                     reply_to_message_id=msg["message_id"])

        cb = upd.get("callback_query")
        if cb:
            call("answerCallbackQuery", callback_query_id=cb["id"])
            call("sendMessage", chat_id=cb["message"]["chat"]["id"], text="Кнопка нажата!")

    if not updates:
        time.sleep(1)

Отправка файла

with open("photo.jpg", "rb") as f:
    r = requests.post(API, params={"method": "sendPhoto"}, headers=HEADERS,
                      data={"chat_id": 123, "caption": "Смотри!"}, files={"media": f})
print(r.json())

Тот же бот на pykodaribot занимает 10 строк — см. раздел Python SDK → Быстрый старт.

66 просмотров