Skip to main content

daskgram — библиотека для ботов DaskGram

Адрес Bot API зашит внутри, поэтому бот начинается с одной строки:

from daskgram import Bot

bot = Bot("1780243212:secret")
bot.send_message(chat_id, "привет")

Никаких base_url, api_server и переменных окружения с адресом.

Установка

pip install daskgram --extra-index-url https://daskgram.xyz/pypi/simple/

или прямо из репозитория:

pip install git+https://github.com/voidtime66-svg/daskgram-bot-python

Зависимостей нет — только стандартная библиотека Python 3.9+.

Чтобы ставить без флагов

pip install daskgram без --extra-index-url ищет пакет только на PyPI. Два способа это получить:

На своей машине — один раз указать наш индекс, дальше команда обычная:

pip config set global.extra-index-url https://daskgram.xyz/pypi/simple/
pip install daskgram

Для всех — опубликовать пакет на PyPI (имя daskgram там свободно):

TWINE_PASSWORD=pypi-XXXXXXXX ./release.sh

Токен берётся на https://pypi.org/manage/account/token/, логин для него — __token__. После загрузки pip install daskgram работает у любого человека без настройки.

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

from daskgram import Bot

bot = Bot("1780243212:secret")


@bot.message_handler
def on_message(message):
    if message.content:
        bot.send_message(message.chat.id, message.content)


if __name__ == "__main__":
    print(bot.get_me()["username"])
    bot.run_polling(allowed_updates=["message"])

message — это объект с полями message_id, chat, from_user, text, caption, reply_to_message, users_shared, chat_shared, forward_origin и raw (сырой JSON целиком — если сервер отдал поле, которого библиотека ещё не знает, оно всё равно доступно).

Клавиатуры

from daskgram import InlineKeyboard, ReplyKeyboard

markup = (
    InlineKeyboard()
    .button("Да", "yes")
    .button("Нет", "no")
    .row()
    .button("Сайт", url="https://daskgram.xyz")
    .build()
)
bot.send_message(chat_id, "Подтверждаете?", reply_markup=markup)

# reply-клавиатура с системными пикерами
keyboard = (
    ReplyKeyboard()
    .request_chat("Выбрать канал", 1, is_channel=True)
    .request_chat("Выбрать группу", 2, is_channel=False)
    .row()
    .request_users("Выбрать бота", 3, is_bot=True)
    .build()
)

Ответ на нажатие кнопки:

@bot.callback_handler
def on_callback(query):
    bot.answer_callback_query(query.id, "ок")
    print(query.data)

Файлы

bot.send_photo(chat_id, files={"photo": open("cat.jpg", "rb")}, caption="кот")
bot.send_document(chat_id, files={"document": ("report.pdf", pdf_bytes)})

Любой метод Bot API

Методы вызываются в snake_case и превращаются в имена API автоматически:

bot.send_message(...)          # sendMessage
bot.edit_message_text(...)     # editMessageText
bot.answer_callback_query(...) # answerCallbackQuery
bot.send_video_note(...)       # sendVideoNote

Если нужен явный вызов (или метод появился на сервере позже этой версии):

bot.call("sendMessage", chat_id=1, text="hi")

Асинхронный вариант

import asyncio
from daskgram import AsyncBot

bot = AsyncBot("1780243212:secret")


async def main():
    async for update in bot.polling(allowed_updates=["message"]):
        if update.message:
            await bot.send_message(update.message.chat.id, "привет")

asyncio.run(main())

Ошибки

from daskgram import BotError, NetworkError

try:
    bot.send_message(chat_id, "текст")
except BotError as exc:          # сервер ответил ok: false
    print(exc.error_code, exc.description)
    if exc.is_rate_limit:        # 429
        ...
except NetworkError:             # не достучались: DNS, TLS, таймаут
    ...

Свой сервер

Для self-hosted DaskGram адрес можно переопределить, но для публичного он не нужен:

bot = Bot(token, api_url="http://127.0.0.1:2402")

Разработка

PYTHONPATH=src python -m unittest discover -s tests -v
python -m pip wheel . -w dist --no-deps

Лицензия

MIT

Metadata

Release files for daskgram 0.1.3

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

Source distribution (sdist)

Source distribution for daskgram 0.1.3
File Size Uploaded Provenance Actions
daskgram-0.1.3.tar.gz 14.9 kB Without provenance Details for daskgram-0.1.3.tar.gz

Built distribution (wheel)

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

Total release size: 26.6 kB

Release files / daskgram-0.1.3.tar.gz

Download URL daskgram-0.1.3.tar.gz
Size 14.9 kB
Tags Source
SHA-256 checksum
How to use checksums
c53031a854fbd159f09dddb6e49b5ff6d4b17b9080e297cf65c6777e100430df
BLAKE2b-256 checksum
How to use checksums
cdcdd20d8c43ee668d9867e99e97d779254962763b48de3805cf3ad17cd87f2a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release files / daskgram-0.1.3-py3-none-any.whl

Download URL daskgram-0.1.3-py3-none-any.whl
Size 11.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e3af137cfca2d2336b081f83c15e012c2b4b407eb31ae51cacd65ee0e6071e58
BLAKE2b-256 checksum
How to use checksums
127c5156e79ead6ad2b271eb0949881de3119f27ff898c14ad3a645312e9d95a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Security for daskgram 0.1.3

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