tgram package

Subpackages

Submodules

tgram.errors module

exception tgram.errors.APIException(message: str, error_code: int, description: str, parameters: dict | None = None)[source]

Bases: StrException

exception tgram.errors.BotWasBlocked(*args)[source]

Bases: StrException

exception tgram.errors.BotWasKicked(*args)[source]

Bases: StrException

exception tgram.errors.ChatNotFound(*args)[source]

Bases: StrException

exception tgram.errors.FloodWait(*args)[source]

Bases: StrException

exception tgram.errors.GroupChatMigrated(*args)[source]

Bases: StrException

exception tgram.errors.InvalidFileId(*args)[source]

Bases: StrException

exception tgram.errors.MessageNotModified(*args)[source]

Bases: StrException

exception tgram.errors.MessageTextEmpty(*args)[source]

Bases: StrException

exception tgram.errors.MessageUneditable(*args)[source]

Bases: StrException

exception tgram.errors.MutedError[source]

Bases: Exception

exception tgram.errors.StopPropagation[source]

Bases: Exception

exception tgram.errors.StrException(msg: str)[source]

Bases: Exception

exception tgram.errors.TerminatedByOtherLongPollOrWebhook(*args)[source]

Bases: StrException

exception tgram.errors.UnableSendToBots(*args)[source]

Bases: StrException

exception tgram.errors.Unauthorized(*args)[source]

Bases: StrException

exception tgram.errors.UserDeactivated(*args)[source]

Bases: StrException

exception tgram.errors.UserNotFound(*args)[source]

Bases: StrException

exception tgram.errors.WebhookIsActive(*args)[source]

Bases: StrException

exception tgram.errors.WrongParameter(*args)[source]

Bases: StrException

tgram.filters module

class tgram.filters.Filter(filter_: Callable | Coroutine)[source]

Bases: object

tgram.filters.chat(ids: str | int | List[str | int]) Filter[source]

Filter messages coming from one or more chats

tgram.filters.chat_type(types: list | str) Filter[source]

Filter updates that match a given chat type.

tgram.filters.command(commands: str | List[str], prefixes: str | List[str] = '/', case_sensitive: bool = False) Filter[source]

Filter commands, i.e.: text messages starting with “/” or any other custom prefix.

tgram.filters.regex(pattern: str | Pattern, flags: int = 0)[source]

Filter updates that match a given regular expression pattern.

tgram.filters.sender(ids: str | int | List[str | int]) Filter[source]

Filter messages coming from one or more sender chat

tgram.filters.user(ids: str | int | List[str | int]) Filter[source]

Filter messages coming from one or more users

tgram.handlers module

class tgram.handlers.Handler(callback: Callable, type: str = 'all', filters: Filter | None = None)[source]

Bases: object

class tgram.handlers.Handlers[source]

Bases: object

BUSINESS_CONNECTION = 'business_connection'
BUSINESS_MESSAGE = 'business_message'
CALLBACK_QUERY = 'callback_query'
CHANNEL_POST = 'channel_post'
CHAT_BOOST = 'chat_boost'
CHAT_JOIN_REQUEST = 'chat_join_request'
CHAT_MEMBER = 'chat_member'
CHOSEN_INLINE_RESULT = 'chosen_inline_result'
DELETED_BUSINESS_MESSAGES = 'deleted_business_messages'
EDITED_BUSINESS_MESSAGE = 'edited_business_message'
EDITED_CHANNEL_POST = 'edited_channel_post'
EDITED_MESSAGE = 'edited_message'
INLINE_QUERY = 'inline_query'
MESSAGE = 'message'
MESSAGE_REACTION = 'message_reaction'
MESSAGE_REACTION_COUNT = 'message_reaction_count'
MY_CHAT_MEMBER = 'my_chat_member'
POLL = 'poll'
POLL_ANSWER = 'poll_answer'
PRE_CHECKOUT_QUERY = 'pre_checkout_query'
PURCHASED_PAID_MEDIA = 'purchased_paid_media'
REMOVED_CHAT_BOOST = 'removed_chat_boost'
SHIPPING_QUERY = 'shipping_query'

tgram.sync module

tgram.sync.async_to_sync(obj, name)[source]
tgram.sync.wrap(source)[source]

tgram.tgbot module

tgram.utils module

class tgram.utils.AsyncProperty(f, bot: TgBot)[source]

Bases: object

class tgram.utils.Json[source]

Bases: dict

class tgram.utils.Mention(name: str, user_id: int)[source]

Bases: object

property html: str
property markdown: str
class tgram.utils.ReadableTime[source]

Bases: datetime

to_formatted_time() str[source]

Converts the datetime object into a formatted string.

Format:

‘YYYY/MM/DD - HH:MM:SS’

Returns:

A string representation of the datetime object in the specified format.

Return type:

str

to_relative_time() str[source]

Converts the datetime object into a relative time string, indicating the difference between the current time and the object’s time.

Examples

  • ‘5 minutes ago’

  • ‘2 months 3 days 4 hours 15 minutes left’

  • ‘Just now’

Returns:

A human-readable string representing the time difference.

Return type:

str

class tgram.utils.String(*args)[source]

Bases: str

property html: str
property markdown: str
put(e: List[MessageEntity] | None = None) String[source]
tgram.utils.compose(bots: List[TgBot])[source]
tgram.utils.convert_input_media(x: List[tgram.types.InputMedia | tgram.types.InputPaidMedia])[source]
tgram.utils.convert_timestamp(timestamp: int | float) ReadableTime[source]

Converts a Unix timestamp into a ReadableTime object.

Parameters:

timestamp (int | float) – A Unix timestamp.

Returns:

A datetime object with methods to get a human-readable time difference.

Return type:

ReadableTime

tgram.utils.decode_file_id(file_id: str) DecodedFileId[source]
tgram.utils.get_file_name(obj)[source]
tgram.utils.get_file_path(file)[source]
tgram.utils.get_parse_mode(bot: TgBot | None = None, parse_mode: str | None = None) str | None[source]
tgram.utils.html_unparse(text: str, entities: List[MessageEntity]) str[source]
tgram.utils.markdown_unparse(text: str, entities: List[MessageEntity])[source]
tgram.utils.message_origin_parse(d: dict | None = None, me: tgram.TgBot | None = None) tgram.types.MessageOrigin | None[source]
tgram.utils.reaction_type_parse(bot: tgram.TgBot, x: List[dict] | dict | None) tgram.types.ReactionType[source]

Module contents

exception tgram.StopPropagation[source]

Bases: Exception

class tgram.TgBot(bot_token: str, api_url: str = 'https://api.telegram.org/', allowed_updates: List[str] = [], link_preview_options: LinkPreviewOptions | None = None, parse_mode: Literal['Markdown', 'MarkdownV2', 'HTML', 'Disable'] | None = None, protect_content: bool | None = None, workers: int | None = None, retry_after: int | bool | None = None, plugins: Path | str | None = None, skip_updates: bool = True, storage_engine: KvsqliteStorage | RedisStorage | Literal['kvsqlite', 'redis'] | None = None, storage_client: Any | None = None)[source]

Bases: TelegramBotMethods, Decorators, Dispatcher

A class for creating a Telegram bot with extended functionality and support for various features like custom updates, storage engines, and more.

Inherits from:
  • TelegramBotMethods: Provides various methods to interact with Telegram Bot API.

  • Decorators: Contains decorators to modify bot behavior.

  • Dispatcher: Manages event handling and dispatching for the bot.

bot_token

The bot token provided by the BotFather.

Type:

str

api_url

The base API URL to communicate with Telegram servers.

Type:

str

allowed_updates

List of update types the bot should listen to.

Type:

List[str]

Options for link previews in messages.

Type:

tgram.types.LinkPreviewOptions

parse_mode

Default parse mode for formatting messages.

Type:

tgram.types.ParseMode

protect_content

Whether to protect content from being saved or forwarded.

Type:

bool

workers

Number of worker threads for handling updates.

Type:

int

retry_after

Time or condition for retrying failed requests.

Type:

Union[int, bool]

plugins

Path to the directory containing bot plugins.

Type:

Union[Path, str]

skip_updates

Whether to skip pending updates on bot startup.

Type:

bool

storage

Storage engine instance for persisting data.

Type:

Optional[StorageBase]

storage_client

Client for the storage engine (e.g., Redis or Kvsqlite).

Type:

Any

executor

Executor for running handler threads.

Type:

ThreadPoolExecutor

loop

Event loop used by the bot.

Type:

asyncio.AbstractEventLoop

is_running

Indicates if the bot is currently running.

Type:

bool

me

The bot’s user profile.

Type:

tgram.types.User

handler_worker_tasks

Tasks handling updates processing.

Type:

List[asyncio.Task]

locks_list

Locks used for synchronization.

Type:

List[asyncio.Lock]

updates_queue

Queue for managing incoming updates.

Type:

asyncio.Queue

groups

Groups of handlers categorized by update types.

Type:

OrderedDict

add_handler(handler: Handler, group: int = 0) None[source]
customize(old: type, new: type) Literal[True][source]
load_plugins() None[source]
property me: User
remove_handler(handler: Handler, group: int = 0) None[source]
tgram.compose(bots: List[TgBot])[source]