Skip to main content

pykodaribot

Python SDK для создания ботов в Kodari Messenger.

Документация: docs.kodari.ru

Установка

pip install pykodaribot

Требования: Python 3.9+

Быстрый старт

import asyncio
from pykodaribot import Bot, Dispatcher, filters

bot = Bot("bot_ВАШ_ТОКЕН")
dp = Dispatcher()

@dp.message(filters.command("start"))
async def start(msg):
    await msg.answer("Привет!")

@dp.message()
async def echo(msg):
    if msg.text:
        await msg.reply(msg.text)

asyncio.run(dp.start_polling(bot))

Токен

Напишите @BotFather в мессенджере, введите /newbot и следуйте инструкциям.

API

Bot

Метод Описание
get_me() Информация о боте
send_message(chat_id, text, reply_to_message_id, reply_markup, message_thread_id) Отправить текст
send_photo(chat_id, media, caption, reply_to_message_id, message_thread_id) Отправить фото
send_document(chat_id, media, caption, reply_to_message_id, message_thread_id) Отправить файл
send_video(chat_id, media, caption, reply_to_message_id, message_thread_id) Отправить видео
send_audio(chat_id, media, caption, reply_to_message_id, message_thread_id) Отправить аудио
edit_message_text(chat_id, message_id, text, reply_markup) Редактировать сообщение
delete_message(chat_id, message_id) Удалить сообщение
get_updates(offset, timeout, limit) Получить апдейты
answer_callback_query(callback_query_id) Ответить на callback
set_my_commands(commands) Установить команды меню
get_my_commands() Получить команды меню
set_my_name(name) Изменить имя бота
set_my_description(description) Изменить описание
set_my_short_description(short_description) Изменить краткое описание
get_chat(chat_id) Информация о чате
get_forum_topics(chat_id) Получить топики группы
get_forum_topic(chat_id, message_thread_id) Получить топик
create_forum_topic(chat_id, name, icon_color, icon_emoji) Создать топик
edit_forum_topic(chat_id, message_thread_id, name, icon_color, icon_emoji) Изменить топик
close_forum_topic(chat_id, message_thread_id) Закрыть топик
reopen_forum_topic(chat_id, message_thread_id) Открыть топик заново
delete_forum_topic(chat_id, message_thread_id) Удалить топик

Топики

topic = await bot.create_forum_topic(
    chat_id,
    "Поддержка",
    icon_color="#6C8CFF",
    icon_emoji="🛠",
)

await bot.send_message(
    chat_id,
    "Новая заявка",
    message_thread_id=topic.message_thread_id,
)

topics = await bot.get_forum_topics(chat_id)
await bot.close_forum_topic(chat_id, topic.message_thread_id)

У входящего сообщения из топика заполнены message_thread_id и is_topic_message. Методы msg.answer() и msg.reply() автоматически отвечают в тот же топик.

Dispatcher

dp = Dispatcher()

@dp.message(*filters)          # новое сообщение
@dp.edited_message(*filters)   # изменённое сообщение
@dp.callback_query(*filters)   # нажатие inline-кнопки
@dp.forum_topic(*filters)
@dp.forum_status(*filters)

Фильтры

from pykodaribot import filters

filters.command("start", "help")        # команды /start или /help
filters.text(r"привет|hello")           # regex по тексту
filters.callback_data("yes")            # точное совпадение callback_data
filters.callback_data_prefix("action:") # callback_data начинается с префикса

Inline-клавиатура

from pykodaribot import InlineKeyboardMarkup, InlineKeyboardButton

keyboard = InlineKeyboardMarkup(inline_keyboard=[
    [
        InlineKeyboardButton(text="Да", callback_data="yes"),
        InlineKeyboardButton(text="Нет", callback_data="no"),
    ],
    [
        InlineKeyboardButton(text="Открыть сайт", url="https://kodari.ru"),
    ],
])

await msg.answer("Выберите:", reply_markup=keyboard)

Отправка медиа

media принимает путь к файлу, Path, bytes или file-like объект:

await bot.send_photo(chat_id, "photo.jpg", caption="Смотри!")
await bot.send_photo(chat_id, Path("/tmp/image.png"))
await bot.send_document(chat_id, open("report.pdf", "rb"))

with open("clip.mp4", "rb") as f:
    await bot.send_video(chat_id, f, caption="Видео")

Примеры

Metadata

Release files for pykodaribot 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pykodaribot 0.4.0
File Size Uploaded Provenance Actions
pykodaribot-0.4.0.tar.gz 13.8 kB Without provenance Details for pykodaribot-0.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pykodaribot 0.4.0
File Interpreter ABI Platform Actions
pykodaribot-0.4.0-py3-none-any.whl Python 3 none any Details for pykodaribot-0.4.0-py3-none-any.whl

Total release size: 27.0 kB

Release files / pykodaribot-0.4.0.tar.gz

Download URL pykodaribot-0.4.0.tar.gz
Size 13.8 kB
Tags Source
SHA-256 checksum
How to use checksums
c674cc62cb27460b08cd9a9bb24a9fc9a43bc5214effcdc317c276d51090c3a1
BLAKE2b-256 checksum
How to use checksums
c00aec3da1ca48cd32c667a5dfe77235eb795a96b283138248d9a2b08a0aa623
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.9

Release files / pykodaribot-0.4.0-py3-none-any.whl

Download URL pykodaribot-0.4.0-py3-none-any.whl
Size 13.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cd658df319597c36c16096e37e2797b1799a90d445c0b7674e6761d4d1915897
BLAKE2b-256 checksum
How to use checksums
983bbb6fc2645c3c030ca4a586055a938fc3db9fef4b45fc31bc4a07c98dd5f1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.9

Security for pykodaribot 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page