Skip to content

telegram module

Messaging using Python Telegram Bot.


self_decorator function

self_decorator(
    func
)

Pass bot object to func command.


send_action function

send_action(
    action
)

Sends action while processing func command.

Suitable only for bound callbacks taking arguments self, update, context and optionally other.


LogHandler class

LogHandler(
    callback,
    pass_update_queue=False,
    pass_job_queue=False,
    pass_user_data=False,
    pass_chat_data=False,
    run_async=False
)

Handler to log user updates.

Superclasses

  • abc.ABC
  • telegram.ext.handler.Handler
  • typing.Generic

check_update method

LogHandler.check_update(
    update
)

This method is called to determine if an update should be handled by this handler instance. It should always be overridden.

Note

Custom updates types can be handled by the dispatcher. Therefore, an implementation of this method should always check the type of :attr:update.

Args

update (:obj:str | :class:telegram.Update): The update to be tested. Returns

Either :obj:None or :obj:False if the update should not be handled. Otherwise an object that will be passed to :meth:handle_update and :meth:collect_additional_context when the update gets handled.


TelegramBot class

TelegramBot(
    giphy_kwargs=None,
    **kwargs
)

Telegram bot.

See Extensions – Your first Bot.

**kwargs are passed to telegram.ext.updater.Updater and override settings under telegram in messaging.

Usage

Let's extend TelegramBot to track cryptocurrency prices:

import ccxt
import logging
from vectorbtpro import *

from telegram.ext import CommandHandler
from telegram import __version__ as TG_VER

try:
    from telegram import __version_info__
except ImportError:
    __version_info__ = (0, 0, 0, 0, 0)

if __version_info__ >= (20, 0, 0, "alpha", 1):
    raise RuntimeError(f"This example is not compatible with your current PTB version {TG_VER}")

# Enable logging
logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__)

class MyTelegramBot(vbt.TelegramBot):
    @property
    def custom_handlers(self):
        return (CommandHandler('get', self.get),)

    @property
    def help_message(self):
        return "Type /get [symbol] [exchange id (optional)] to get the latest price."

    def get(self, update, context):
        chat_id = update.effective_chat.id

        if len(context.args) == 1:
            symbol = context.args[0]
            exchange = 'binance'
        elif len(context.args) == 2:
            symbol = context.args[0]
            exchange = context.args[1]
        else:
            self.send_message(chat_id, "This command requires symbol and optionally exchange id.")
            return
        try:
            ticker = getattr(ccxt, exchange)().fetchTicker(symbol)
        except Exception as e:
            self.send_message(chat_id, str(e))
            return
        self.send_message(chat_id, str(ticker['last']))

if __name__ == "__main__":
    bot = MyTelegramBot(token='1628351231:AAEgvZyRRfOV4_6ZArMS_lXzZd6XkG932zg')
    bot.start()

Superclasses

Inherited members


chat_ids property

Chat ids that ever interacted with this bot. A chat id is added upon receiving the "/start" command.


chat_migration_callback method

TelegramBot.chat_migration_callback(
    update,
    context
)

Chat migration callback.


custom_handlers property

Custom handlers to add. Override to add custom handlers. Order counts.


dispatcher property

Dispatcher.


error_callback method

TelegramBot.error_callback(
    update,
    context,
    *args
)

Error callback.


help_callback method

TelegramBot.help_callback(
    update,
    context
)

Help command callback.


help_message property

Message to be sent upon "/help" command. Override to define your own message.


log_handler property

Log handler.


running property

Whether the bot is running.


send method

TelegramBot.send(
    kind,
    chat_id,
    *args,
    log_msg=None,
    **kwargs
)

Send message of any kind to chat_id.


send_giphy method

TelegramBot.send_giphy(
    chat_id,
    text,
    *args,
    giphy_kwargs=None,
    **kwargs
)

Send GIPHY from text to chat_id.


send_giphy_to_all method

TelegramBot.send_giphy_to_all(
    text,
    *args,
    giphy_kwargs=None,
    **kwargs
)

Send GIPHY from text to all in TelegramBot.chat_ids.


send_message method

TelegramBot.send_message(
    chat_id,
    text,
    *args,
    **kwargs
)

Send text message to chat_id.


send_message_to_all method

TelegramBot.send_message_to_all(
    text,
    *args,
    **kwargs
)

Send text message to all in TelegramBot.chat_ids.


send_to_all method

TelegramBot.send_to_all(
    kind,
    *args,
    **kwargs
)

Send message of any kind to all in TelegramBot.chat_ids.


start method

TelegramBot.start(
    in_background=False,
    **kwargs
)

Start the bot. **kwargs are passed to telegram.ext.updater.Updater.start_polling and override settings under telegram in messaging.


start_callback method

TelegramBot.start_callback(
    update,
    context
)

Start command callback.


start_message property

Message to be sent upon "/start" command. Override to define your own message.


started_callback method

TelegramBot.started_callback()

Callback once the bot has been started. Override to execute custom commands upon starting the bot.


stop method

TelegramBot.stop()

Stop the bot.


unknown_callback method

TelegramBot.unknown_callback(
    update,
    context
)

Unknown command callback.


updater property

Updater.