telegramlib

Easiest Python package to create Telegram bots.

Version:

0.1.3

Authors:

Daniele Lanciotti (daniele9001@gmail.com) (https://illancio.github.io)

Changelog:

License:

MIT License

https://github.com/ilLancio/telegramlib/blob/master/LICENSE

Third party licenses:

Modules

config

Telegram Bot Configuration Module

core

Telegram Bot Main Functionality Module

data

Data Management Module

commands

Telegram Bot Command Module

jobs

Daily Jobs Management Module

telegram_exceptions

Telegram Bot Library Exceptions Module

telegram_warnings

Warnings Module for Telegram Bot Library

utils

Utility Module

text_to_speech

Text-to-Speech Conversion Module

translator

Translation and Language Detection Module

Exported Functions

start_bot(token, admin, commands[, ...])

Most important function needed to start the bot.

command_args()

Get command's arguments.

bot_reply_text(message[, text_to_audio, ...])

Makes the bot respond to a message from the user.

send(message[, chat_id, save, token, parse_mode])

Sends a text message to a specified user.

delete(chat_id, message_id[, token])

Deletes a text message of a user.

context()

Get python-telegram-bot context object.

update()

Get python-telegram-bot update object.

bot_name()

Get name of the bot.

set_param(key, value)

Set the value of a user custom parameter.

get_param(key)

Get the value of a user custom parameter.

get_chat([user, last, last_message, ...])

Get the chat history of a user.

admin_command(func)

Decorator to restrict command execution to the bot's admin.

controllers_command(func)

Decorator to restrict command execution to users listed as controllers.

terminal()

Executes terminal commands as the admin.

follow()

Adds users to the admin's list of followed users.

unfollow()

Removes users from the admin's list of followed users.

write()

Sends a message to a specified user from the admin.

ban()

Bans specified users from the bot.

sban()

Unbans all or specified users from the bot.

creator()

Initiates a direct conversation with the bot's creator.

closecreator()

Ends the conversation with the bot's creator.

new_daily_job_from_args(function[, reset])

Schedules a new user's daily job from Telegram command argument with hh:mm format.

get_command_args_daily_job_time_format([n_arg])

Get (hour, minute) from Telegram command argument with hh:mm format.

is_daily_job_scheduled(function, hour, minute)

Tells whether a given user's daily job is scheduled or not.

daily_jobs_scheduled_times_to_string([mex, ...])

Get the user's daily jobs formatted into a string.

remove_all_daily_jobs()

Removes all saved user's daily jobs from both the job queue and the user's data.

new_daily_job(function, hour, minute[, reset])

Schedules and saves a new user's daily job.

Installation

You can install the package from PyPI using pip:

pip install telegramlib

Usage Examples

Setting up your bot:

  1. Obtain a Telegram bot token from https://t.me/BotFather.

  2. Obtain your Telegram user ID from https://t.me/raw_info_bot.

  3. Replace placeholders with your actual bot token and user ID in the examples below.

Usage Example 1: Starting the Bot

Define a start function that performs what you want to happen when a user types the /start command. Then remember to add the command in the start_bot function along with your token and user id.

from telegramlib import *

TOKEN = 'your Telegram bot token'
ADMIN = 'your user ID'

# Define a start command function
async def start():
    await bot_reply_text('Bot started!')

# Bot configuration and start
start_bot(
    token=TOKEN,
    admin=ADMIN,
    commands=start
)
User: /start
Bot:  Bot started!

Disable user privacy:

If you want to save user information, you must explicitly specify it as a parameter in the start_bot function by setting privacy=False, like so: start_bot(token=TOKEN, …, privacy=False). User information will be saved in the database.json file.

Legal Disclaimer: User Privacy and Data Handling:

Please note that you are solely responsible for complying with all applicable data protection and privacy laws. This includes, but is not limited to, obtaining user consent where required, securely storing the data, and providing users with necessary disclosures regarding how their data will be used. The author of this library assumes no liability for any legal consequences arising from the use or misuse of this functionality.

Disable user updates:

Disabling user privacy and being an admin yourself, you will receive informative messages from the bot about the activities of your bot’s users. To disable or enable it, send it the /usersupdates command.

Usage Example 2: Other Commands and Message Handler

Define another command function that makes the bot respond by giving you the command arguments and a message handler that gives the user the name of the bot after being asked for it. Always remember to add the functions in start_bot.

from telegramlib import *

TOKEN = 'your Telegram bot token'
ADMIN = 'your user ID'

# Define a start command function
async def start():
    await bot_reply_text('Bot started!')

# Define another command function
async def yourcommand():
    args = str( command_args() )
    response = 'You sent me your command with these arguments: ' + args
    await bot_reply_text(response)

# Define a message handler function
async def message():
    if user_message() == "What's your name?":
        await bot_reply_text('My name is ' + bot_name())

# Bot configuration and start
start_bot(
    token=TOKEN,
    admin=ADMIN,
    commands=[start, yourcommand],
    messages=message
)
User: /yourcommand Hello Bot!
Bot:  You sent me your command with these arguments: ['Hello', 'Bot!']
User: What's your name
Bot:  My name is <bot-name>

Usage Example 3: Scheduling Future Messages

Define the start function so that it schedules a daily task at 6 p.m., so, typing the start command, every day at 6 p.m. will be executed the contents of the scheduled_task function defined under, also to be added to the start_bot function. Additionally define a command that removes all user tasks.

from telegramlib import *

TOKEN = 'your Telegram bot token'
ADMIN = 'your user ID'

# Define a start command function
async def start():
    # Task scheduling. reset=True to remove old scheduled tasks
    new_daily_job(scheduled_task, 18, 0, reset=True)
    await bot_reply_text('Scheduled task every day at 6 p.m.')

# Define another command
async def removetasks():
    remove_all_daily_jobs()
    await bot_reply_text('Tasks all deleted')

# Define a scheduled function
async def scheduled_task():
    await bot_reply_text('This is a scheduled task!')

# Bot configuration and start
start_bot(
    token=TOKEN,
    admin=ADMIN,
    commands=[start, removetasks],
    scheduled=scheduled_task
)
User: /start
Bot:  Scheduled task every day at 6 p.m.

(at 6:00 PM)
Bot:  This is a scheduled task!

User: /removetasks
Bot:  Tasks all deleted

Usage Example 4: Users Parameters, Admin and Controllers

Specify in the start_bot function a dictionary representative of the users’ default parameters. That done, you can access and modify those parameters with get_param and set_param. In the example we use within the start command and commands with access restricted to the admin and controllers, which are also specified in the start_bot function.

from telegramlib import *

TOKEN = 'your Telegram bot token'
ADMIN = 'your user ID'

# Define a start command function
async def start():
    set_param('parameter 2', False)
    await bot_reply_text('Your parameter 2 is been set to False')

# Admin restricted access command
@admin_command
async def admincommand():
    p = get_param('parameter 1')
    await bot_reply_text(f'I am answering you because you are the admin and your parameter 1 is {p}')

# Controllers restricted access command
@controllers_command
async def controllercommand():
    p = get_param('parameter 1')
    await bot_reply_text(f'I am responding to you because you are an admin and an admin is always a controller. Your parameter 1 is {p}')

# Bot configuration and start
start_bot(
    token=TOKEN,
    admin=ADMIN,
    commands=[start, admincommand, controllercommand],
    controllers=[<user_id_1>, <user_id_2>],
    params={'parameter 1': 42, 'parameter 2': True}
)
User: /start
Bot:  Your parameter 2 is been set to False
User: /admincommand
Bot:  I am answering you because you are the admin and your parameter 1 is 42
User: /controllercommand
Bot:  I am responding to you because you are an admin and an admin is always controller. Your parameter 1 is 42

telegramlib.admin_command(func)[source]

Decorator to restrict command execution to the bot’s admin.

This decorator checks if the current user is the admin before executing the decorated function. It ensures that only the admin can perform certain sensitive actions, such as managing users or executing system commands.

Parameters:

func (function) – The function to be wrapped and executed only by the admin.

Returns:

wrapper – The wrapped function with admin check applied.

Return type:

function

telegramlib.ban()[source]

Bans specified users from the bot.

This function sets a ‘ban’ flag for each specified user, preventing them from interacting with the bot.

Example

/ban <user_id_1> <user_id_2>

telegramlib.bot_name()[source]

Get name of the bot.

Returns:

Name of the bot.

Return type:

str

telegramlib.bot_reply_text(message, text_to_audio=False, translate_to=None, talking_about_latex=False)[source]

Makes the bot respond to a message from the user. Must be executed with await in front.

Parameters:
  • message (str) – Bot response message.

  • text_to_audio (bool, optional) – True to send the text as audio (default is False).

  • translate_to (str or None, optional) – The language in which you want the message to arrive translated (default is None).

  • talking_about_latex (bool, optional) – True if the message mentions latex formulas that do not need to be converted (default is False).

telegramlib.closecreator()[source]

Ends the conversation with the bot’s creator.

This function removes the user from the list of users having a direct conversation with the bot’s creator and provides a message indicating that the conversation is closed.

telegramlib.command_args()[source]

Get command’s arguments.

Returns:

Command’s arguments.

Return type:

list of str or None

telegramlib.context()[source]

Get python-telegram-bot context object.

Returns:

python-telegram-bot context object.

Return type:

telegram.Context

telegramlib.controllers_command(func)[source]

Decorator to restrict command execution to users listed as controllers.

This decorator allows only users identified as controllers in the bot’s configuration to execute the decorated function. Controllers have a higher level of access compared to regular users but less than the admin.

Parameters:

func (function) – The function to be wrapped and executed only by controllers.

Returns:

wrapper – The wrapped function with controller check applied.

Return type:

function

telegramlib.creator()[source]

Initiates a direct conversation with the bot’s creator.

This function notifies the admin that a user wants to initiate a conversation. It adds the user to the list of users to send messages to the admin and provides a prompt indicating that they are now talking to the bot’s creator.

telegramlib.daily_jobs_scheduled_times_to_string(mex='', if_empty_mex='')[source]

Get the user’s daily jobs formatted into a string.

Parameters:
  • mex (str, optional) – Text that comes before the list of daily jobs (default is ‘’).

  • if_empty_mex (str, optional) – Text returned in case of no daily jobs (default is ‘’).

Returns:

Text with daily jobs list.

Return type:

str

telegramlib.delete(chat_id, message_id, token=None)[source]

Deletes a text message of a user.

Parameters:
  • chat_id (int or str) – user_id of the recipient.

  • message_id (int or str) – message_id of the message to be deleted.

  • token (str or None, optional) – Telegram bot token or None (default) to use token set during bot startup.

Returns:

Response of api requests.

Return type:

dict

telegramlib.follow()[source]

Adds users to the admin’s list of followed users.

This function allows the admin to follow specific users, meaning he will receive messages sent from these users to the bot. It adds the specified users to the config._users_to_send_to_admin list and provides recent chat history.

Example

/follow <user_id_1> <user_id_2>

telegramlib.get_chat(user=None, last=None, last_message=None, max_char=None, to_string=False, to_list=False, only_name_keys=False, without_keys=False)[source]

Get the chat history of a user.

Parameters:
  • user (int or str or None, optional) – user_id of the user whose chat to get or None (default) to use config._user_id.

  • last (int or str or None, optional) – Number of last messages or last “day”, “month”, or “year” time frame (default is None).

  • last_message (str, optional) – Last message of which you want to get the next ones (default is None).

  • max_char (int, optional) – Maximum number of characters to be obtained (default is None).

  • to_string (bool, optional) – True to return the chat in string format (default is False).

  • to_list (bool, optional) – True to return the chat in list format (default is False).

  • only_name_keys (bool, optional) – True to return chat with keys containing only names (default is False).

  • without_keys (bool, optional) – True to return the chat with only message contents (default is False).

Returns:

The user’s chat in the specified format.

Return type:

dict or str or list

telegramlib.get_command_args_daily_job_time_format(n_arg=0)[source]

Get (hour, minute) from Telegram command argument with hh:mm format.

Parameters:

n_arg (int, optional) – Numerical argument index (default is 0).

Returns:

A tuple containing hour (int) and minute (int).

Return type:

tuple

telegramlib.get_param(key)[source]

Get the value of a user custom parameter.

Parameters:

key (any) – The key name of the parameter whose value you want to get. It must be one of the keys in the default parameter dictionary.

Returns:

The value associated with the key name parameter.

Return type:

any

telegramlib.is_daily_job_scheduled(function, hour, minute)[source]

Tells whether a given user’s daily job is scheduled or not.

Parameters:
  • function (Callable) – Scheduled function of daily job.

  • hour (int) – Scheduled hour of daily job.

  • minute (int) – Scheduled minute of daily job.

Returns:

True if the function is scheduled at the given hour and minute, False otherwise.

Return type:

bool

telegramlib.new_daily_job(function, hour, minute, reset=False)[source]

Schedules and saves a new user’s daily job.

Parameters:
  • function (Callable) – Scheduled function of daily job.

  • hour (int) – Scheduled hour of daily job.

  • minute (int) – Scheduled minute of daily job.

  • reset (bool, optional) – True to remove all previous saved user’s daily jobs (default is False).

telegramlib.new_daily_job_from_args(function, reset=False)[source]

Schedules a new user’s daily job from Telegram command argument with hh:mm format.

Parameters:
  • function (Callable) – Scheduled function of daily job.

  • reset (bool, optional) – True to remove all previously scheduled daily jobs of the user (defalut is False).

Returns:

Successful or unsuccessful message: ‘job created’, ‘wrong args’ or ‘empty args’.

Return type:

str

telegramlib.remove_all_daily_jobs()[source]

Removes all saved user’s daily jobs from both the job queue and the user’s data.

telegramlib.sban()[source]

Unbans all or specified users from the bot.

This function removes the ‘ban’ flag from all users if no arguments are provided, or from the specified users if arguments are given.

Example

/sban <user_id_1> <user_id_2>

telegramlib.send(message, chat_id=None, save=True, token=None, parse_mode=<ParseMode.HTML>)[source]

Sends a text message to a specified user.

Parameters:
  • message (str) – Text message to send.

  • chat_id (int or str or None, optional) – user_id of the recipient, ‘all’ to send to all users in the database or None (default) to send to the admin.

  • save (bool, optional) – False if you don’t want to save the message in the database (default is True).

  • token (str or None, optional) – Telegram bot token

  • parse_mode (ParseMode, optional) – Text message parse mode (default is ParseMode.HTML).

Returns:

Response/responses of api requests.

Return type:

dict or list of dict

telegramlib.set_param(key, value)[source]

Set the value of a user custom parameter.

Parameters:
  • key (any) – The key name of the parameter to be set. It must be one of the keys in the default parameter dictionary.

  • value (any) – The value to be associated with the key.

telegramlib.start_bot(token, admin, commands, messages=None, scheduled=None, error=None, controllers=None, params=None, privacy=True)[source]

Most important function needed to start the bot.

Parameters:
  • token (str) – Telegram bot token.

  • admin (int or str) – Admin user_id.

  • commands (Callable or list of Callable) – start function or list of command handler functions.

  • messages (Callable or list of Callable or None, optional) – Message handler function or list of [function, telegram filter] (default is None).

  • scheduled (Callable or list of Callable or None, optional) – Scheduled function/functions (default is None).

  • error (Callable or None, optional) – Error handler function or None (default) to use default _error handler function.

  • controllers (str or list of str or None, optional) – Controller user_id/user_ids (default is None).

  • params (dict or None, optional) – Users’ default parameters (default is None).

  • privacy (bool, optional) – False to enable user tracking (default is True).

Raises:

MissingStartCommandError – If the function is executed before the bot starts.

telegramlib.terminal()[source]

Executes terminal commands as the admin.

This function allows the admin to execute system-level commands directly from the chat. It filters out the initial bot command and ‘sudo’ keyword for security reasons. The output of the command is sent back to the chat.

Example

/command ls -la

telegramlib.unfollow()[source]

Removes users from the admin’s list of followed users.

This function removes the specified users from the list of followed users. If no users are specified, it clears the entire list.

Example

/unfollow <user_id_1> <user_id_2>

telegramlib.update()[source]

Get python-telegram-bot update object.

Returns:

python-telegram-bot update object.

Return type:

telegram.Update

telegramlib.user_message()[source]

Get message sent by the user.

Returns:

The message sent by the user.

Return type:

str

telegramlib.write()[source]

Sends a message to a specified user from the admin.

This function allows the admin to send a custom message to any user. It takes the user ID (or ‘all’) and the message text as arguments.

Example

/write <user_id> Hello! How are you?