Skip to main content

Telegram Bot API library

Project description

fgram

fgram — Python-библиотека для эффективной работы с Telegram Bot API, а также с дополнительными функциями

Что внутри

  • Telegram Bot API: 10.2
  • Типов: 387
  • Методов: 185
  • Update-событий: 26
  • Message content types: 76
  • Методов с parse_mode: 17
  • Дополнительные классы: OnlySQ, Deef, ChatGPT, OpenAI

Установка зависимостей

pip install -U curl_cffi beautifulsoup4

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

from fgram import Bot, InputFile

bot = Bot('BOT_TOKEN', parse_mode='HTML')
bot.send_message(chat_id=123456789, text='Привет')
bot.send_photo(chat_id=123456789, photo=InputFile('photo.jpg'))
bot.send_document(chat_id=123456789, document=InputFile('file.zip'))

Handlers и polling

from fgram import Bot

bot = Bot('BOT_TOKEN')

@bot.message_handler(commands='start')
def start(message):
    bot.send_message(message.chat.id, 'Привет')

@bot.message_handler(content_types='photo')
def photo(message):
    bot.send_message(message.chat.id, 'Фото получил')

bot.infinity_polling(skip_pending=True)

AsyncBot

import asyncio
from fgram import AsyncBot

async def main():
    async with AsyncBot('BOT_TOKEN') as bot:
        me = await bot.get_me()
        print(me)

asyncio.run(main())

Загрузка и скачивание файлов

from fgram import Bot, InputFile

bot = Bot('BOT_TOKEN')

bot.send_document(chat_id=123456789, document=InputFile('archive.zip'))

# Можно скачать по file_id или уже готовому file_path
data = bot.download_file('FILE_ID')
bot.download_file('photos/file_123.jpg', save_path='photo.jpg')

Имена методов

Методы Telegram Bot API переводятся в snake_case:

bot.send_message(...) # sendMessage
bot.get_updates(...) # getUpdates
bot.set_my_commands(...) # setMyCommands

Исключение: Telegram-метод close называется close_bot(), чтобы не конфликтовать с bot.close() для закрытия HTTP-сессии.

Типы и объекты

Все типы Telegram Bot API представлены dataclass-объектами и умеют:

obj = SomeTelegramType.from_dict(data)
data = obj.to_dict()

Union-helper-ы: BackgroundFill_from_dict, BackgroundType_from_dict, BotCommandScope_from_dict, ChatBoostSource_from_dict, ChatMember_from_dict, InlineQueryResult_from_dict, InputMedia_from_dict, InputMessageContent_from_dict, InputPaidMedia_from_dict, InputPollMedia_from_dict, InputPollOptionMedia_from_dict, InputProfilePhoto_from_dict, InputRichBlock_from_dict, InputStoryContent_from_dict, MaybeInaccessibleMessage_from_dict, MenuButton_from_dict, MessageOrigin_from_dict, OwnedGift_from_dict, PaidMedia_from_dict, PassportElementError_from_dict, … +6.

Update kinds

message, edited_message, channel_post, edited_channel_post, business_connection, business_message, edited_business_message, deleted_business_messages, guest_message, message_reaction, message_reaction_count, inline_query, chosen_inline_result, callback_query, shipping_query, pre_checkout_query, purchased_paid_media, poll, poll_answer, my_chat_member, chat_member, chat_join_request, chat_boost, removed_chat_boost, managed_bot, subscription

Message content types

receiver_user, ephemeral_message_id, text, rich_message, animation, audio, document, live_photo, paid_media, photo, sticker, story, video, video_note, voice, checklist, contact, dice, game, poll, venue, location, new_chat_members, left_chat_member, chat_owner_left, chat_owner_changed, new_chat_title, new_chat_photo, delete_chat_photo, group_chat_created, supergroup_chat_created, channel_chat_created, message_auto_delete_timer_changed, pinned_message, invoice, successful_payment, refunded_payment, users_shared, chat_shared, gift, unique_gift, gift_upgrade_sent, write_access_allowed, passport_data, proximity_alert_triggered, … +31

Частые методы

Python Telegram API Return Описание
get_me getMe "User" A simple method for testing your bot's authentication token. Requires no parameters. Returns basic information about th…
get_updates getUpdates List["Update"] Use this method to receive incoming updates using long polling ( wiki ). Returns an Array of Update objects.
send_message sendMessage "Message" Use this method to send text messages. On success, the sent Message is returned.
send_photo sendPhoto "Message" Use this method to send photos. On success, the sent Message is returned.
send_document sendDocument "Message" Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any t…
send_media_group sendMediaGroup List["Message"] Use this method to send a group of photos, live photos, videos, documents or audios as an album. Documents and audio fi…
edit_message_text editMessageText Union["Message", bool] Use this method to edit text, rich and game messages. On success, if the edited message is not an inline message, the e…
answer_callback_query answerCallbackQuery bool Use this method to send answers to callback queries sent from inline keyboards . The answer will be displayed to the us…
get_file getFile "File" Use this method to get basic information about a file and prepare it for downloading. For the moment, bots can download…
set_my_commands setMyCommands bool Use this method to change the list of the bot's commands. See this manual for more details about bot commands. Returns…
delete_webhook deleteWebhook bool Use this method to remove webhook integration if you decide to switch back to getUpdates . Returns True on success.
set_webhook setWebhook bool Use this method to specify a URL and receive incoming updates via an outgoing webhook. Whenever there is an update for…
close_bot close bool Use this method to close the bot instance before moving it from one local server to another. You need to delete the web…
log_out logOut bool Use this method to log out from the cloud Bot API server before launching the bot locally. You must log out the bot bef…
get_webhook_info getWebhookInfo "WebhookInfo" Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the…
forward_message forwardMessage "Message" Use this method to forward messages of any kind. Service messages and messages with protected content can't be forwarde…
forward_messages forwardMessages List["MessageId"] Use this method to forward multiple messages of any kind. If some of the specified messages can't be found or forwarded…
copy_message copyMessage "MessageId" Use this method to copy messages of any kind. Service messages, paid media messages, giveaway messages, giveaway winner…
copy_messages copyMessages List["MessageId"] Use this method to copy messages of any kind. If some of the specified messages can't be found or copied, they are skip…
send_live_photo sendLivePhoto "Message" Use this method to send live photos. On success, the sent Message is returned.
send_audio sendAudio "Message" Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must…
send_video sendVideo "Message" Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as Document ). On…
send_animation sendAnimation "Message" Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is…
send_voice sendVoice "Message" Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For…
send_video_note sendVideoNote "Message" As of v.4.0 , Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send vide…
send_paid_media sendPaidMedia "Message" Use this method to send paid media. On success, the sent Message is returned.
send_location sendLocation "Message" Use this method to send point on the map. On success, the sent Message is returned.
send_venue sendVenue "Message" Use this method to send information about a venue. On success, the sent Message is returned.
send_contact sendContact "Message" Use this method to send phone contacts. On success, the sent Message is returned.
send_poll sendPoll "Message" Use this method to send a native poll. On success, the sent Message is returned.
send_checklist sendChecklist "Message" Use this method to send a checklist on behalf of a connected business account. On success, the sent Message is returned.
send_dice sendDice "Message" Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned.
send_message_draft sendMessageDraft bool Use this method to stream a partial message to a user while the message is being generated. Note that the streamed draf…
send_chat_action sendChatAction bool Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 s…
set_message_reaction setMessageReaction bool Use this method to change the chosen reactions on a message. Service messages of some types can't be reacted to. Automa…

Дополнительные возможности

from fgram import OnlySQ

ai = OnlySQ('ONLYSQ_KEY')
models = ai.get_models(modality='text', hidden_models=['gpt-*'])

Ошибки Telegram API

При ошибке Telegram выбрасывается TelegramAPIError:

from fgram import Bot, TelegramAPIError

bot = Bot('BOT_TOKEN')

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

Лицензия

MIT 2026 by SiriLV(Siright)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fgram-10.2.tar.gz (105.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fgram-10.2-py3-none-any.whl (102.6 kB view details)

Uploaded Python 3

File details

Details for the file fgram-10.2.tar.gz.

File metadata

  • Download URL: fgram-10.2.tar.gz
  • Upload date:
  • Size: 105.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.6

File hashes

Hashes for fgram-10.2.tar.gz
Algorithm Hash digest
SHA256 1a1b46e7d29078d6c065b7c01294c95da4f21afa886f0bbc3ec4b596242c3484
MD5 14114b54cd1e4fc97bd2c07cc74f4494
BLAKE2b-256 4e16273b8d33e70db23dcb1a09acd6553cb2da4c5ff4682938473f6ef7a9f7df

See more details on using hashes here.

File details

Details for the file fgram-10.2-py3-none-any.whl.

File metadata

  • Download URL: fgram-10.2-py3-none-any.whl
  • Upload date:
  • Size: 102.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.6

File hashes

Hashes for fgram-10.2-py3-none-any.whl
Algorithm Hash digest
SHA256 c5eebaecd1d5680645cebe788cb20de3223d807ec162a74bb4373b87d99efa94
MD5 dd66c499899f05598995916857488343
BLAKE2b-256 5b1ca6f508b43c2beb1293e5b859d3306c5ab1953df9b0ca4f4d721953059295

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page