Skip to main content

neogram

neogram — минималистичная Python-библиотека для Telegram Bot API и набора дополнительных AI/utility-клиентов.

Библиотека ориентирована на простой прямой доступ к Telegram Bot API без лишней магии Текущая версия поддерживает Telegram Bot API 10.1.


Возможности

  • Полный клиент Telegram Bot API на основе curl_cffi.
  • Синхронный клиент Bot.
  • Асинхронный клиент AsyncBot.
  • Автоматически сгенерированные методы Bot API.
  • Автоматически сгенерированные типы Telegram API.
  • Десериализация ответов Telegram в Python-объекты.
  • Сериализация объектов обратно в dict.
  • Загрузка файлов через InputFile.
  • Скачивание файлов Telegram через bot.download_file(...).
  • Декораторная система обработчиков сообщений и обновлений.
  • Polling и обработка webhook-обновлений.
  • Автоповторы при сетевых ошибках, 5xx и Flood Wait.
  • Дополнительные клиенты из ii.py: OnlySQ, Deef, Qwen, ChatGPT, OpenAI.

Установка

pip install neogram

Зависимости:

pip install curl_cffi beautifulsoup4

curl_cffi используется как основной HTTP-клиент. beautifulsoup4 нужен для некоторых функций из Deef.


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

Синхронный бот

from neogram import Bot

bot = Bot("YOUR_BOT_TOKEN", parse_mode="HTML")

@bot.message_handler(commands=["start"])
def start(message):
    bot.send_message(chat_id=message.chat.id, text="Привет! Я работаю на neogram.")

@bot.message_handler(content_types=["text"])
def text(message):
    bot.send_message(chat_id=message.chat.id, text=f"Ты написал: {message.text}")

bot.infinity_polling()

Асинхронный бот

import asyncio
from neogram import AsyncBot

bot = AsyncBot("YOUR_BOT_TOKEN", parse_mode="HTML")

@bot.message_handler(commands=["start"])
async def start(message):
    await bot.send_message(chat_id=message.chat.id, text="Привет из AsyncBot!")

async def main():
    async with bot:
        await bot.infinity_polling()

asyncio.run(main())

Bot

Bot — синхронный клиент Telegram Bot API.

from neogram import Bot

bot = Bot(token="YOUR_BOT_TOKEN", api_url="https://api.telegram.org", timeout=60, impersonate="chrome", parse_mode=None, proxies=None, max_retries=3, retry_on_flood=True)

Параметры конструктора

Параметр Тип По умолчанию Описание
token str — Токен бота от BotFather.
api_url str https://api.telegram.org Базовый URL Telegram Bot API.
timeout int 60 Таймаут HTTP-запросов в секундах.
impersonate str chrome TLS fingerprint для curl_cffi.
parse_mode Optional[str] None Форматирование по умолчанию: HTML, MarkdownV2 и т.д.
proxies Optional[dict] None Прокси для curl_cffi.
max_retries int 3 Количество повторов при сетевых/серверных ошибках.
retry_on_flood bool True Автоповтор при 429 Flood Wait.

Закрытие сессии

bot.close()

Или через context manager:

from neogram import Bot

with Bot("YOUR_BOT_TOKEN") as bot:
    print(bot.get_me())

Методы Telegram Bot API

Все методы Telegram Bot API доступны у Bot и AsyncBot в snake_case.

Примеры соответствия:

Telegram Bot API neogram
getMe bot.get_me()
sendMessage bot.send_message(...)
sendPhoto bot.send_photo(...)
getUpdates bot.get_updates(...)
setWebhook bot.set_webhook(...)
answerCallbackQuery bot.answer_callback_query(...)
sendRichMessage bot.send_rich_message(...)
sendRichMessageDraft bot.send_rich_message_draft(...)

Отправка сообщения

bot.send_message(chat_id=123456789, text="<b>Привет</b>", parse_mode="HTML")

Если parse_mode задан в Bot(...), его можно не передавать каждый раз:

bot = Bot("YOUR_BOT_TOKEN", parse_mode="HTML")
bot.send_message(chat_id=123456789, text="<b>Привет</b>")

Отправка фото

from neogram import InputFile

bot.send_photo(chat_id=123456789, photo=InputFile("photo.jpg"), caption="Фото из файла")

Можно передавать URL или уже существующий file_id:

bot.send_photo(chat_id=123456789, photo="https://example.com/photo.jpg")
bot.send_photo(chat_id=123456789, photo="AgACAgIAAxkBAA...")

Отправка документа

from neogram import InputFile

bot.send_document(chat_id=123456789, document=InputFile("report.pdf"), caption="Документ")

Новые rich message методы Bot API 10.1

from neogram import InputRichMessage

bot.send_rich_message(chat_id=123456789, rich_message=InputRichMessage(...))

Для потокового черновика rich message:

bot.send_rich_message_draft(chat_id=123456789, draft_id=1, rich_message=InputRichMessage(...))

Типы Telegram API

Все типы Telegram Bot API представлены Python-классами. Например:

from neogram import Message, User, Chat, InlineKeyboardMarkup, InlineKeyboardButton

Типы наследуются от TelegramObject и поддерживают:

  • from_dict(...) — создание объекта из словаря;
  • to_dict() — преобразование объекта обратно в словарь;
  • автоматическую обработку переименованных Python-полей (from → from_user, type → type_val).

Пример:

from neogram import Message

message = Message.from_dict(update_data["message"])
print(message.chat.id)
print(message.to_dict())

InputFile

InputFile используется для загрузки файлов в Telegram.

from neogram import InputFile

photo = InputFile("photo.jpg")
bot.send_photo(chat_id=123456789, photo=photo)

Можно передать bytes:

from neogram import InputFile

with open("photo.jpg", "rb") as f:
    data = f.read()

bot.send_photo(chat_id=123456789, photo=InputFile(data, filename="photo.jpg"))

Или file-like объект:

with open("document.pdf", "rb") as f:
    bot.send_document(chat_id=123456789, document=InputFile(f, filename="document.pdf"))

Скачивание файлов Telegram

download_file принимает file_id, вызывает getFile, получает file_path и скачивает файл.

Вернуть bytes:

data = bot.download_file(file_id="FILE_ID")

if data:
    print(len(data))

Сохранить на диск:

path = bot.download_file(file_id="FILE_ID", save_path="downloaded_file.bin")

print(path)

Пример скачивания документа из сообщения:

@bot.message_handler(content_types=["document"])
def on_document(message):
    file_id = message.document.file_id
    saved = bot.download_file(file_id, save_path=message.document.file_name)
    bot.send_message(message.chat.id, f"Файл сохранён: {saved}")

Handlers

neogram поддерживает регистрацию обработчиков через декораторы.

message_handler

@bot.message_handler(commands=["start", "help"])
def commands(message):
    bot.send_message(message.chat.id, "Команда получена")
@bot.message_handler(content_types=["text"])
def text(message):
    bot.send_message(message.chat.id, message.text)
@bot.message_handler(regexp=r"^/echo\s+(.+)")
def echo(message):
    text = message.text.split(maxsplit=1)[1]
    bot.send_message(message.chat.id, text)
@bot.message_handler(func=lambda m: m.chat.type_val == "private")
def private_only(message):
    bot.send_message(message.chat.id, "Это личный чат")

Фильтры message_handler

Фильтр Описание
commands Список команд без / или с /: ['start'], ['/start'].
content_types Список типов контента: text, photo, document, sticker, voice, rich_message и т.д.
regexp Регулярное выражение по message.text или message.caption.
func Пользовательская функция-предикат.
chat_types Ограничение по типу чата: private, group, supergroup, channel.
user_ids Белый список ID пользователей.
chat_ids Белый список ID чатов.

callback_query_handler

@bot.callback_query_handler(data="open_menu")
def open_menu(call):
    bot.answer_callback_query(call.id)
    bot.send_message(call.message.chat.id, "Меню открыто")

Можно использовать функцию:

@bot.callback_query_handler(func=lambda c: c.data.startswith("user:"))
def user_callback(call):
    user_id = call.data.split(":", 1)[1]
    bot.answer_callback_query(call.id, f"User ID: {user_id}")

Остальные обработчики

Декоратор Update field
edited_message_handler edited_message
channel_post_handler channel_post
edited_channel_post_handler edited_channel_post
callback_query_handler callback_query
inline_handler inline_query
chosen_inline_result_handler chosen_inline_result
poll_handler poll
poll_answer_handler poll_answer
my_chat_member_handler my_chat_member
chat_member_handler chat_member
chat_join_request_handler chat_join_request
pre_checkout_query_handler pre_checkout_query
shipping_query_handler shipping_query
business_message_handler business_message
edited_business_message_handler edited_business_message
deleted_business_messages_handler deleted_business_messages
message_reaction_handler message_reaction
message_reaction_count_handler message_reaction_count
chat_boost_handler chat_boost
removed_chat_boost_handler removed_chat_boost
purchased_paid_media_handler purchased_paid_media

StopPropagation

StopPropagation можно выбросить внутри обработчика, чтобы остановить дальнейшую обработку текущего update.

from neogram import StopPropagation

@bot.message_handler(commands=["stop"])
def stop(message):
    bot.send_message(message.chat.id, "Остановлено")
    raise StopPropagation

Обработчик ошибок

@bot.error_handler
def errors(update, exception):
    print("Ошибка в обработчике:", exception)

Polling

Запуск polling:

bot.polling(timeout=30, allowed_updates=None, none_stop=True, interval=0.0)

Бесконечный polling:

bot.infinity_polling()

Остановка polling:

bot.stop_polling()

allowed_updates

Можно указать список типов обновлений:

bot.infinity_polling(allowed_updates=["message", "callback_query", "my_chat_member"])

Webhook

Для webhook можно передать входящий JSON в process_update.

Пример с Flask:

from flask import Flask, request
from neogram import Bot

app = Flask(__name__)
bot = Bot("YOUR_BOT_TOKEN")

@app.post("/webhook")
def webhook():
    bot.process_update(request.json)
    return "ok"

Для AsyncBot:

await bot.process_update(update_dict)

AsyncBot

AsyncBot имеет те же API-методы, но все они являются корутинами.

from neogram import AsyncBot

async with AsyncBot("YOUR_BOT_TOKEN") as bot:
    me = await bot.get_me()
    await bot.send_message(me.id, "Проверка")

Асинхронные обработчики:

@bot.message_handler(content_types=["text"])
async def text(message):
    await bot.send_message(message.chat.id, message.text)

Синхронные обработчики в AsyncBot тоже допустимы: диспетчер проверяет результат и делает await, если обработчик вернул awaitable.


Исключения

TelegramAPIError

Выбрасывается, если Telegram API вернул ошибку.

from neogram import TelegramAPIError

try:
    bot.send_message(chat_id=123, text="test")
except TelegramAPIError as e:
    print(e.error_code)
    print(e.description)
    print(e.parameters)
    print(e.retry_after)

StopPropagation

Служебное исключение для остановки обработки update внутри handler.


Retry-логика

Bot и AsyncBot автоматически повторяют запросы:

  • при сетевых ошибках;
  • при серверных ошибках 5xx;
  • при 429 Flood Wait, если retry_on_flood=True.

Настройки:

bot = Bot("YOUR_BOT_TOKEN", max_retries=3, retry_on_flood=True)

Клавиатуры

Inline keyboard

from neogram import InlineKeyboardMarkup, InlineKeyboardButton

keyboard = InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="Открыть", callback_data="open_menu")]])

bot.send_message(chat_id=123456789, text="Выбери действие:", reply_markup=keyboard)

Reply keyboard

from neogram import ReplyKeyboardMarkup, KeyboardButton

keyboard = ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text="Профиль")]], resize_keyboard=True)

bot.send_message(chat_id=123456789, text="Меню:", reply_markup=keyboard)

Команды бота

from neogram import BotCommand

bot.set_my_commands([BotCommand(command="start", description="Запустить бота"), BotCommand(command="help", description="Помощь")])

Работа с update вручную

update = bot.get_updates(limit=1)[0]

if update.message:
    print(update.message.text)

OnlySQ

OnlySQ — клиент OnlySQ API для генерации текста и изображений.

from neogram import OnlySQ

ai = OnlySQ(key="ONLYSQ_API_KEY")

Получение моделей

models = ai.get_models(modality="text")
print(models)

Фильтрация:

models = ai.get_models(modality=["text", "image"], can_tools=True, can_stream=True, max_cost=5, hidden_models=["gpt-5.5", "claude-opus-*", "Grok 4.3"], sort_by="cost")

Вернуть полный список с данными моделей:

models = ai.get_models(return_full=True)

Генерация текста

answer = ai.generate_answer(model="gemini-3.5-flash", messages=[{"role": "user", "content": "Напиши короткое приветствие"}])

print(answer)

Генерация изображения

ok = ai.generate_image(model="flux", prompt="Кот-программист за ноутбуком", ratio="16:9", filename="cat.png")

print(ok)

Deef

Deef — набор утилит.

from neogram import Deef

deef = Deef()

Перевод текста

translated = deef.translate("Hello world", lang="ru")
print(translated)

Скачивание файла по URL

data = deef.download_file("https://example.com/file.png")

Сохранение на диск:

path = deef.download_file("https://example.com/file.png", save_path="file.png")

Сокращение ссылки

short = deef.short_url("https://example.com/very/long/url")
print(short)

Запуск функции в фоне

def work(x, y):
    print(x + y)

thread = deef.run_in_bg(work, 2, 3)

Base64

encoded = deef.encode_base64("image.png")

Perplexity

answer = deef.perplexity_ask(prompt="Что такое Python?", model="auto")

Toolbaz

answer = deef.toolchat(prompt="Напиши идею для бота", model="toolbaz-v4.5-fast")

Qwen

Qwen — клиент для chat.qwen.ai.

from neogram import Qwen

qwen = Qwen()

Получение моделей

models = qwen.fetch_models()
print(models)

Чат

result = qwen.chat(model="qwen3.7-plus", messages=[{"role": "user", "content": "Привет!"}], ctype="t2t", think=True)

print(result)

Типы чата

Поддерживаемые типы зависят от текущей реализации Qwen и доступности сервиса. Обычно используются:

  • t2t — обычный текстовый чат;
  • search — чат с поиском;
  • t2i — генерация изображения;
  • deep_research — глубокое исследование;
  • artifacts — работа с артефактами;
  • learn — обучающий режим;
  • image_edit — редактирование изображения, если доступно.

ChatGPT / OpenAI

ChatGPT — универсальный клиент для OpenAI-совместимых API. OpenAI является алиасом ChatGPT.

from neogram import ChatGPT, OpenAI

client = ChatGPT(url="https://api.openai.com/v1", headers={"Authorization": "Bearer YOUR_API_KEY"})

Chat Completions

response = client.generate_chat_completion(model="gpt-4o-mini", messages=[{"role": "user", "content": "Привет!"}])

print(response)

Images

image = client.generate_image(prompt="A small robot in cyberpunk style", n=1, size="1024x1024")

Embeddings

embedding = client.generate_embedding(model="text-embedding-3-small", input_data="Hello world")

Audio transcription

with open("audio.mp3", "rb") as f:
    result = client.generate_transcription(file=f, model="whisper-1", language="ru")

Audio translation

with open("audio.mp3", "rb") as f:
    result = client.generate_translation(file=f, model="whisper-1")

Models

models = client.get_models()

Закрытие клиента

client.close()

Или:

with ChatGPT(url="https://api.example.com/v1", headers={}) as client:
    print(client.get_models())

Именование полей

Некоторые поля Telegram имеют имена, конфликтующие с Python. neogram переименовывает их:

Telegram field Python field
from from_user
type type_val
filter filter_val
class class_val

Пример:

@bot.message_handler(content_types=["text"])
def handle(message):
    user = message.from_user
    chat_type = message.chat.type_val

Логирование

neogram использует стандартный logging.

import logging

logging.basicConfig(level=logging.INFO)
logging.getLogger("neogram").setLevel(logging.DEBUG)

Советы по использованию

  1. Для простых ботов используйте Bot и infinity_polling().
  2. Для высоконагруженных приложений используйте AsyncBot или webhook.
  3. Для файлов используйте InputFile, если нужно загрузить локальный файл.
  4. Для скачивания файлов Telegram используйте bot.download_file(file_id, save_path=...).
  5. Не храните токены и API-ключи прямо в коде — используйте переменные окружения.
  6. Для больших проектов разделяйте обработчики по файлам и регистрируйте их через функции.

Минимальный шаблон проекта

my_bot/
├── main.py
├── handlers.py
└── config.py

config.py:

import os

BOT_TOKEN = os.getenv("BOT_TOKEN")

handlers.py:

def setup_handlers(bot):
    @bot.message_handler(commands=["start"])
    def start(message):
        bot.send_message(message.chat.id, "Привет!")

main.py:

from neogram import Bot
from config import BOT_TOKEN
from handlers import setup_handlers

bot = Bot(BOT_TOKEN, parse_mode="HTML")
setup_handlers(bot)
bot.infinity_polling()

Лицензия

MIT 2026 by SiriLV

Metadata

Release files for neogram 10.1.5

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

Source distribution (sdist)

Source distribution for neogram 10.1.5
File Size Uploaded Provenance Actions
neogram-10.1.5.tar.gz 116.5 kB Without provenance Details for neogram-10.1.5.tar.gz

Built distribution (wheel)

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

Total release size: 224.5 kB

Release files / neogram-10.1.5.tar.gz

Download URL neogram-10.1.5.tar.gz
Size 116.5 kB
Tags Source
SHA-256 checksum
How to use checksums
492c7f14106a0dd5f0972e800e2822fd64a72f31e5696eff9325b1fe4025bb77
BLAKE2b-256 checksum
How to use checksums
b6bd34cd1c7b0165adef182752c60e693768170795603ac745e03a740d3b98bf
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.5

Release files / neogram-10.1.5-py3-none-any.whl

Download URL neogram-10.1.5-py3-none-any.whl
Size 108.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1fd057a1c7106fe65fd0648383d6e79368237ccbd9574cf06fdcd075416559bf
BLAKE2b-256 checksum
How to use checksums
a30927f6e90c4d0aa671d9fddf886519d5779adb94b73c7684825e8c63ed04f4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.5

Security for neogram 10.1.5

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.

Release history Release notifications | RSS feed

This release

10.1.5 This release

2 release files No provenance

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