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.2

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.2
File Size Uploaded Provenance Actions
daskgram-0.1.2.tar.gz 14.9 kB Without provenance Details for daskgram-0.1.2.tar.gz

Built distribution (wheel)

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

Total release size: 26.6 kB

Release files / daskgram-0.1.2.tar.gz

Download URL daskgram-0.1.2.tar.gz
Size 14.9 kB
Tags Source
SHA-256 checksum
How to use checksums
7024553d5def88add3d9a7fb58fea9cb1e1c4c786cc0b83319f5724a806568f5
BLAKE2b-256 checksum
How to use checksums
d9a29209b3d97a25d4315e47b89037a088c487700314b65b30426126357d0580
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.2-py3-none-any.whl

Download URL daskgram-0.1.2-py3-none-any.whl
Size 11.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
df191f1f128c178f0a9d7bccd5c3f3df59638dbce22b3a26f5aee55aa7e69222
BLAKE2b-256 checksum
How to use checksums
e2bbd4a48a8a63e47380aa4bd7e816b1bec45d9161114d77da047cf3fb49f13b
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.2

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