### Install ptbcontrib with SQLAlchemy support Source: https://github.com/python-telegram-bot/ptbcontrib/blob/main/ptbcontrib/ptb_jobstores/README.md This shell command installs the ptbcontrib library with specific support for SQLAlchemy job stores. It fetches the package directly from the main branch of the GitHub repository. ```shell pip install "ptbcontrib[ptb_jobstores_sqlalchemy] @ git+https://github.com/python-telegram-bot/ptbcontrib.git@main" ``` -------------------------------- ### Install ptbcontrib with MongoDB support Source: https://github.com/python-telegram-bot/ptbcontrib/blob/main/ptbcontrib/ptb_jobstores/README.md This shell command installs the ptbcontrib library with specific support for MongoDB job stores. It fetches the package directly from the main branch of the GitHub repository. ```shell pip install "ptbcontrib[ptb_jobstores_mongodb] @ git+https://github.com/python-telegram-bot/ptbcontrib.git@main" ``` -------------------------------- ### Initialize PostgresPersistence with Database URL Source: https://github.com/python-telegram-bot/ptbcontrib/blob/main/ptbcontrib/postgres_persistence/README.md Demonstrates how to configure the bot application using a direct PostgreSQL connection string. This approach is suitable for simple setups where the library manages the database connection. ```python from ptbcontrib.postgres_persistence import PostgresPersistence DB_URI = "postgresql://username:pw@hostname:port/db_name" application = Application.builder().token(...).persistence(PostgresPersistence(url=DB_URI)).build() ``` -------------------------------- ### Configure AiohttpRequest in an ApplicationBuilder Source: https://github.com/python-telegram-bot/ptbcontrib/blob/main/ptbcontrib/aiohttp_request/README.md Shows how to integrate AiohttpRequest into an ApplicationBuilder instance. This example includes custom connection pool sizing and basic command handler setup. ```python import logging from telegram import Update from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler from ptbcontrib.aiohttp_request import AiohttpRequest logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO ) async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): await context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!") if __name__ == '__main__': application = ApplicationBuilder().request(AiohttpRequest(connection_pool_size=256)).get_updates_request(AiohttpRequest()).token('TOKEN').build() start_handler = CommandHandler('start', start) application.add_handler(start_handler) application.run_polling() ``` -------------------------------- ### Python Telegram Bot Role-Based Access Control Setup Source: https://github.com/python-telegram-bot/ptbcontrib/blob/main/ptbcontrib/roles/README.md Demonstrates the setup and configuration of role-based access control for a Telegram bot using ptbcontrib.roles. It includes initializing roles, adding roles and admins, establishing role hierarchies, and attaching handlers with specific role restrictions. ```python from telegram import Update from telegram.ext import TypeHandler, ApplicationBuilder, MessageHandler, SomeHandler, filters from ptbcontrib.roles import setup_roles, RolesHandler, Role async def add_to_my_role_2(update, context): user = update.effective_user # 'roles' is stored in context.bot_data[BOT_DATA_KEY] context.roles['my_role_2'].add_member(user.id) async def add_to_my_role_1(update, context): user_id = int(update.message.text) context.roles['my_role_1'].add_member(user_id) async def post_init(application): # This is called after the application has been initialized # and before the polling starts. # This ensures that the roles are initialized *after* the # persistence has been loaded, if persistence is used. # See also the wiki page at # https://github.com/python-telegram-bot/python-telegram-bot/wiki/Making-your-bot-persistent roles = setup_roles(application) if 'my_role_1' not in roles: roles.add_role(name='my_role_1') my_role_1 = roles['my_role_1'] if 'my_role_2' not in roles: roles.add_role(name='my_role_2') roles.add_admin(123) my_role_2 = roles['my_role_2'] my_role_1.add_child_role(my_role_2) # Anyone can add themself to my_role_2 application.add_handler(RolesHandler(TypeHandler(Update, add_to_my_role_2), roles=None)) # Only the admin can add users to my_role_1 application.add_handler( RolesHandler(MessageHandler(filters.TEXT, add_to_my_role_1), roles=roles.admins) ) # This will be accessible by my_role_2, my_role_1 and the admin application.add_handler(RolesHandler(SomeHandler(...), roles=my_role_2)) # This will be accessible by my_role_1 and the admin application.add_handler(RolesHandler(SomeHandler(...), roles=my_role_1)) # This will be accessible by anyone except my_role_1 and my_role_2 application.add_handler(RolesHandler(SomeHandler(...), roles=~my_role_1)) # You can compare the roles regarding hierarchy: roles['my_role_1'] >= roles['my_role_2'] # True roles['my_role_1'] < roles['my_role_2'] # False roles.admins >= Role(...) # False, since neither of those is a parent of the other application = ApplicationBuilder().token('TOKEN').post_init(post_init).build() ``` -------------------------------- ### Enable PostgreSQL Persistence for Telegram Bot Data Source: https://context7.com/python-telegram-bot/ptbcontrib/llms.txt This snippet illustrates how to use `PostgresPersistence` from PTBContrib to store bot data, user data, chat data, and conversations in a PostgreSQL database. It supports direct database URL configuration or integration with an existing SQLAlchemy session. The example also shows how to set up persistence with `on_flush=True` for batch updates, requiring manual flushing. ```python from telegram import Update from telegram.ext import Application, CommandHandler, ContextTypes from ptbcontrib.postgres_persistence import PostgresPersistence from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session # Method 1: Using database URL directly DB_URI = "postgresql://username:password@localhost:5432/telegram_bot" application = ( Application.builder() .token("YOUR_BOT_TOKEN") .persistence(PostgresPersistence(url=DB_URI)) .build() ) # Method 2: Using existing SQLAlchemy session def create_session() -> scoped_session: engine = create_engine(DB_URI, client_encoding="utf8") return scoped_session(sessionmaker(bind=engine, autoflush=False)) application_with_session = ( Application.builder() .token("YOUR_BOT_TOKEN") .persistence(PostgresPersistence(session=create_session())) .build() ) # Example handler using persistent data async def counter(update: Update, context: ContextTypes.DEFAULT_TYPE): # Data is automatically persisted to PostgreSQL context.user_data.setdefault('count', 0) context.user_data['count'] += 1 await update.message.reply_text(f"Count: {context.user_data['count']}") # With on_flush=True for batch updates persistence = PostgresPersistence(url=DB_URI, on_flush=True) # Call await persistence.flush() manually to save data ``` -------------------------------- ### Apply Filters to ReplyToMessage Source: https://github.com/python-telegram-bot/ptbcontrib/blob/main/ptbcontrib/reply_to_message_filter/README.md Demonstrates how to use ReplyToMessageFilter to create MessageHandlers that accept specific types of replies. It shows examples for replying to text messages, non-sticker messages, and document messages. ```python from telegram.ext import Filters, MessageHandler from ptbcontrib.reply_to_message_filter import ReplyToMessageFilter # accepts only messages that are replies to text messages replies_to_text = MessageHandler( ReplyToMessageFilter(Filters.text), callback ) # accepts only messages that are replies to non-sticker messages replies_to_anything_but_stickers = MessageHandler( ~ReplyToMessageFilter(Filters.sticker), callback ) # accepts only messages containing documents that are replies to # a message containing a document documents_as_reply_to_documents = MessageHandler( Filters.document & ReplyToMessageFilter(Filters.document), callback ) ``` -------------------------------- ### GET /chat/joinable-link Source: https://github.com/python-telegram-bot/ptbcontrib/blob/main/ptbcontrib/get_chat_link/README.md Retrieves a valid joinable link for a specified Telegram chat by attempting to resolve it through various chat properties and API calls. ```APIDOC ## GET /chat/joinable-link ### Description Retrieves a joinable link for a telegram.Chat object. The method prioritizes existing chat links, then invite links, and finally attempts to export a new link if permissions allow. ### Method GET ### Endpoint /chat/joinable-link ### Parameters #### Query Parameters - **chat_id** (integer/string) - Required - The unique identifier of the target chat. ### Request Example GET /chat/joinable-link?chat_id=123456789 ### Response #### Success Response (200) - **link** (string) - The resolved joinable URL for the chat. #### Response Example { "link": "https://t.me/+AbCdEfGhIjKlMnOp" } ``` -------------------------------- ### Add MongoDB Job Store to Python Telegram Bot Application Source: https://github.com/python-telegram-bot/ptbcontrib/blob/main/ptbcontrib/ptb_jobstores/README.md This snippet demonstrates how to integrate the PTBMongoDBJobStore into a python-telegram-bot application. It configures the job store with a MongoDB connection URI and adds it to the application's scheduler. Ensure you have the necessary PyMongo package installed. ```python from telegram.ext import Application from ptbcontrib.ptb_jobstores.mongodb import PTBMongoDBJobStore DB_URI = "mongodb://botuser:botpassword@localhost:27017/admin?retryWrites=true&w=majority" application = Application.builder().token("TOKEN").build() application.job_queue.scheduler.add_jobstore( PTBMongoDBJobStore( application=application, host=DB_URI, ) ) application.run_polling() ``` -------------------------------- ### Implement Role-Based Access Control with ptbcontrib Source: https://context7.com/python-telegram-bot/ptbcontrib/llms.txt Demonstrates how to initialize roles, define admin/moderator permissions, and restrict command access using the RolesHandler. It supports hierarchical roles and bitwise negation for exclusion. ```python from telegram import Update from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, TypeHandler from ptbcontrib.roles import setup_roles, RolesHandler, Role async def admin_only_action(update: Update, context): await update.message.reply_text("Admin action executed!") async def moderator_action(update: Update, context): await update.message.reply_text("Moderator action executed!") async def add_moderator(update: Update, context): user_id = int(update.message.text.split()[1]) context.roles['moderators'].add_member(user_id) await update.message.reply_text(f"User {user_id} is now a moderator!") async def post_init(application): roles = setup_roles(application) roles.add_admin(123456789) if 'moderators' not in roles: roles.add_role(name='moderators') if 'banned' not in roles: roles.add_role(name='banned') moderators = roles['moderators'] banned = roles['banned'] application.add_handler(RolesHandler(CommandHandler('admin', admin_only_action), roles=roles.admins)) application.add_handler(RolesHandler(CommandHandler('moderate', moderator_action), roles=moderators)) application.add_handler(RolesHandler(CommandHandler('add_mod', add_moderator), roles=roles.admins)) application.add_handler(RolesHandler(CommandHandler('public', public_action), roles=~banned)) application = ApplicationBuilder().token('YOUR_BOT_TOKEN').post_init(post_init).build() application.run_polling() ``` -------------------------------- ### Initialize PostgresPersistence with SQLAlchemy Session Source: https://github.com/python-telegram-bot/ptbcontrib/blob/main/ptbcontrib/postgres_persistence/README.md Shows how to integrate PostgresPersistence with an existing SQLAlchemy scoped session. This is useful for applications that already utilize SQLAlchemy for other database operations. ```python from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session from ptbcontrib.postgres_persistence import PostgresPersistence DB_URI = "postgresql://username:pw@hostname:port/db_name" def start_session() -> scoped_session: engine = create_engine(DB_URI, client_encoding="utf8") return scoped_session(sessionmaker(bind=engine, autoflush=False)) application = Application.builder().token(...).persistence(PostgresPersistence(session=start_session())).build() ``` -------------------------------- ### Implement Help Command Handler Source: https://context7.com/python-telegram-bot/ptbcontrib/llms.txt This function iterates through the defined BOT_COMMANDS list to generate a formatted string containing all command details. It is intended to be used as a handler for the /help command. ```python async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE): help_text = "Bot Commands:\n\n" for cmd in BOT_COMMANDS: help_text += f"/{cmd.command}\n{cmd.long_description}\n\n" await update.message.reply_text(help_text) ``` -------------------------------- ### Implementing LongBotCommand in python-telegram-bot Source: https://github.com/python-telegram-bot/ptbcontrib/blob/main/ptbcontrib/longbotcommand/README.md This snippet demonstrates how to define commands using the LongBotCommand class and register them with the bot dispatcher. It shows the initialization of commands with both short and long descriptions and how to access the long description during command execution. ```python from typing import List from telegram import Update from telegram.ext import Updater, CommandHandler, CallbackContext from ptbcontrib.longbotcommand import LongBotCommand updater = Updater("TOKEN", use_context=True) dp = updater.dispatcher lorem_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." lorem_desc = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s." BOT_COMMANDS: List[LongBotCommand] = [ LongBotCommand("help", "Prints out a list of available commands"), LongBotCommand("lorem", "Prints Lorem Ipsum", long_description=lorem_desc), ] def help(update: Update, context: CallbackContext) -> None: for command in context.bot.commands: update.message.reply_text(f"/{command.command}\n\n{command.long_description}") def lorem(update: Update, context: CallbackContext) -> None: update.message.reply_text(lorem_text) dp.add_handler(CommandHandler("help", help)) dp.add_handler(CommandHandler("lorem", lorem)) dp.bot.set_my_commands(BOT_COMMANDS) updater.start_polling() updater.idle() ``` -------------------------------- ### Initialize AiohttpRequest in a Bot Instance Source: https://github.com/python-telegram-bot/ptbcontrib/blob/main/ptbcontrib/aiohttp_request/README.md Demonstrates how to instantiate a telegram.Bot object using AiohttpRequest for both standard requests and get_updates requests. This approach is suitable for direct bot interactions. ```python import asyncio import telegram from ptbcontrib.aiohttp_request import AiohttpRequest async def main(): bot = telegram.Bot("TOKEN", request=AiohttpRequest(), get_updates_request=AiohttpRequest()) async with bot: print(await bot.get_me()) if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Define and Register Telegram Bot Commands Source: https://context7.com/python-telegram-bot/ptbcontrib/llms.txt This snippet shows how to define a list of commands with long descriptions and register them with the Telegram bot menu using the post_init hook. It ensures that the bot's command menu is correctly initialized upon startup. ```python BOT_COMMANDS: List[LongBotCommand] = [ LongBotCommand( command="start", description="Start the bot", long_description="Welcome! This bot helps you manage your tasks." ), LongBotCommand( command="help", description="Show available commands", long_description="Available commands:\n/start - Initialize the bot\n/help - Show this detailed help message" ) ] async def post_init(application): await application.bot.set_my_commands(BOT_COMMANDS) application = ApplicationBuilder().token('YOUR_BOT_TOKEN').post_init(post_init).build() ``` -------------------------------- ### AiohttpRequest Initialization Source: https://github.com/python-telegram-bot/ptbcontrib/blob/main/ptbcontrib/aiohttp_request/README.md Configuring the AiohttpRequest class for use with a Telegram Bot instance or ApplicationBuilder. ```APIDOC ## AiohttpRequest Initialization ### Description Initializes the AiohttpRequest class to be used as the request handler for Telegram Bot operations. It can be injected into the Bot instance or the ApplicationBuilder. ### Method N/A (Class Constructor) ### Endpoint ptbcontrib.aiohttp_request.AiohttpRequest ### Parameters #### Path Parameters - **connection_pool_size** (int) - Optional - The maximum number of connections to keep in the pool. ### Request Example ```python from ptbcontrib.aiohttp_request import AiohttpRequest request = AiohttpRequest(connection_pool_size=256) ``` ### Response #### Success Response (Object) - **instance** (AiohttpRequest) - An initialized request handler object ready to be passed to the telegram.Bot or ApplicationBuilder. ``` -------------------------------- ### Roles Management API Source: https://github.com/python-telegram-bot/ptbcontrib/blob/main/ptbcontrib/roles/README.md Methods for initializing roles, managing role hierarchy, and assigning users to roles within the application context. ```APIDOC ## POST /roles/setup ### Description Initializes the role management system within the bot application context. This should be called during the post_init phase of the application. ### Method POST ### Parameters #### Request Body - **application** (Application) - Required - The current python-telegram-bot Application instance. ### Request Example { "application": "" } ### Response #### Success Response (200) - **roles** (RolesManager) - The initialized roles manager instance. --- ## POST /roles/add_member ### Description Adds a specific user to a defined role. ### Method POST ### Parameters #### Request Body - **user_id** (int) - Required - The Telegram user ID to add. - **role_name** (string) - Required - The name of the role to assign the user to. ### Request Example { "user_id": 123456789, "role_name": "my_role_1" } --- ## POST /roles/add_child ### Description Establishes a hierarchical relationship where one role inherits permissions from another. ### Method POST ### Parameters #### Request Body - **parent_role** (string) - Required - The role that will act as the parent. - **child_role** (string) - Required - The role that will act as the child. ### Request Example { "parent_role": "my_role_1", "child_role": "my_role_2" } ``` -------------------------------- ### Integrating UsernameToChatAPI with PTB Custom Context Source: https://github.com/python-telegram-bot/ptbcontrib/blob/main/ptbcontrib/username_to_chat_api/README.md Shows how to integrate the UsernameToChatAPI wrapper into a python-telegram-bot application using a custom context class. This allows for cleaner access to the wrapper's functionality within handlers. ```python import logging import asyncio from telegram import Update, Chat from telegram.ext import ApplicationBuilder, CallbackContext, CommandHandler, ContextTypes, Application from ptbcontrib.username_to_chat_api import UsernameToChatAPI logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO ) class CustomContext(CallbackContext): @property def wrapper(self) -> UsernameToChatAPI: return self.bot_data["wrapper"] async def resolve_username(self, username: str) -> Chat: return await self.wrapper.resolve(username) async def start(update: Update, context: CustomContext): chat = await context.resolve_username("PoolTalks") if __name__ == '__main__': context_types = ContextTypes(context=CustomContext) application = ApplicationBuilder().token('TOKEN').context_types(context_types).build() wrapper = UsernameToChatAPI("https://localhost:1234/", "RationalGymsGripOverseas", application.bot) application.bot_data["wrapper"] = wrapper start_handler = CommandHandler('start', start) application.add_handler(start_handler) application.run_polling() # shutting down the Username API AsyncClient. Very much optional but why not. asyncio.run(application.bot_data["wrapper"].shutdown()) ``` -------------------------------- ### Retrieve Chat Links with get_chat_link Source: https://context7.com/python-telegram-bot/ptbcontrib/llms.txt Retrieves a joinable invite link for a chat using multiple fallback strategies. It attempts to use existing links before falling back to API-based creation if permissions allow. ```python from telegram import Update, Chat from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes from ptbcontrib.get_chat_link import get_chat_link async def share_chat_link(update: Update, context: ContextTypes.DEFAULT_TYPE): chat: Chat = update.effective_chat link = await get_chat_link(chat) if link: await update.message.reply_text(f"Join this chat: {link}") else: await update.message.reply_text("Could not retrieve chat link.") ``` -------------------------------- ### Implement AiohttpRequest for Telegram Bot Requests Source: https://context7.com/python-telegram-bot/ptbcontrib/llms.txt This snippet demonstrates how to use `AiohttpRequest` from PTBContrib to replace the default HTTPX request implementation in `python-telegram-bot`. It shows basic usage with a `Bot` instance and advanced configuration with an `ApplicationBuilder`, including connection pooling, timeouts, and proxy settings. This allows for more efficient and configurable network operations. ```python import asyncio import logging from telegram import Update, Bot from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler from ptbcontrib.aiohttp_request import AiohttpRequest # Basic usage with Bot instance async def basic_bot_example(): bot = Bot( "YOUR_BOT_TOKEN", request=AiohttpRequest(), get_updates_request=AiohttpRequest() ) async with bot: me = await bot.get_me() print(f"Bot: {me.first_name}") # Advanced usage with Application and custom settings logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO ) async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): await context.bot.send_message( chat_id=update.effective_chat.id, text="Hello! I'm using aiohttp for requests." ) if __name__ == '__main__': # Configure with connection pool size and proxy application = ( ApplicationBuilder() .request(AiohttpRequest( connection_pool_size=256, media_total_timeout=60.0, proxy="http://proxy.example.com:8080" )) .get_updates_request(AiohttpRequest()) .token('YOUR_BOT_TOKEN') .build() ) application.add_handler(CommandHandler('start', start)) application.run_polling() ``` -------------------------------- ### Initialize LogForwarder in python-telegram-bot Source: https://github.com/python-telegram-bot/ptbcontrib/blob/main/ptbcontrib/log_forwarder/README.md This snippet shows how to initialize the `LogForwarder` class, which extends `logging.Handler`, to send logs to a Telegram chat. It requires the bot instance, a list of chat IDs, and optionally specifies the log levels to forward. The handler is added to the root logger to capture all application logs. ```python async def on_startup(app: Application): error_forwarder = LogForwarder( app.bot, [CHAT_ID], log_levels=["ERROR", "WARNING"] ) # Add handler to the root logger to apply to all other loggers logging.getLogger().addHandler(error_forwarder) application: Application = ( ApplicationBuilder() .token("BOT_TOKEN") .post_init(on_startup) .build() ) ``` -------------------------------- ### Configure Log Forwarding with LogForwarder Source: https://context7.com/python-telegram-bot/ptbcontrib/llms.txt Demonstrates how to forward application logs to a specific Telegram chat. It uses the LogForwarder utility to capture logs based on severity levels and attach them to the root or specific loggers. ```python import logging from telegram.ext import Application, ApplicationBuilder, CommandHandler, ContextTypes from ptbcontrib.log_forwarder import LogForwarder ADMIN_CHAT_ID = 123456789 async def on_startup(app: Application): error_forwarder = LogForwarder( bot=app.bot, chat_ids=[ADMIN_CHAT_ID], log_levels=["ERROR", "WARNING", "CRITICAL"] ) logging.getLogger().addHandler(error_forwarder) application = ApplicationBuilder().token("YOUR_BOT_TOKEN").post_init(on_startup).build() application.run_polling() ``` -------------------------------- ### PTBJobStores - Persistent Job Storage for APScheduler Source: https://context7.com/python-telegram-bot/ptbcontrib/llms.txt The ptb_jobstores module offers adapters for APScheduler, enabling the persistence of `telegram.ext.Job` instances across bot restarts using MongoDB or SQLAlchemy. This ensures scheduled tasks are not lost when the bot goes offline. Dependencies include `telegram.ext` and APScheduler. ```python from telegram import Update from telegram.ext import Application, CommandHandler, ContextTypes from ptbcontrib.ptb_jobstores.mongodb import PTBMongoDBJobStore from ptbcontrib.ptb_jobstores.sqlalchemy import PTBSQLAlchemyJobStore # MongoDB job store setup MONGO_URI = "mongodb://user:password@localhost:27017/admin?retryWrites=true&w=majority" application = Application.builder().token("YOUR_BOT_TOKEN").build() application.job_queue.scheduler.add_jobstore( PTBMongoDBJobStore( application=application, host=MONGO_URI, ) ) # SQLAlchemy job store setup (alternative) SQLITE_URI = "sqlite:///jobs.db" # application.job_queue.scheduler.add_jobstore( # PTBSQLAlchemyJobStore( # application=application, # url=SQLITE_URI, # ) # ) async def reminder_callback(context: ContextTypes.DEFAULT_TYPE): """Callback executed by the scheduled job.""" await context.bot.send_message( chat_id=context.job.chat_id, text=f"Reminder: {context.job.data}" ) async def set_reminder(update: Update, context: ContextTypes.DEFAULT_TYPE): """Schedule a persistent reminder.""" chat_id = update.effective_chat.id text = ' '.join(context.args) if context.args else "Default reminder" # IMPORTANT: Use explicit ID and replace_existing to avoid duplicates on restart context.job_queue.run_once( reminder_callback, when=60, # 60 seconds from now data=text, chat_id=chat_id, name=f"reminder_{chat_id}", job_kwargs={ "id": f"reminder_{chat_id}_{text[:10]}", "replace_existing": True } ) await update.message.reply_text(f"Reminder set: {text}") application.add_handler(CommandHandler("remind", set_reminder)) application.run_polling() ``` -------------------------------- ### Resolve Username to Chat API (Python) Source: https://context7.com/python-telegram-bot/ptbcontrib/llms.txt Demonstrates how to use the UsernameToChatAPI to resolve usernames to chat IDs. It shows both basic standalone usage and integration with the python-telegram-bot application using a custom context. This API requires an external service to perform the actual username resolution. ```Python from telegram import Bot from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes from telegram.ext.callbackcontext import CallbackContext from telegram.ext.application import Application from telegram import Update, Chat from ptbcontrib.username_to_chat_api import UsernameToChatAPI # Basic standalone usage async def resolve_username_basic(): bot = Bot("YOUR_BOT_TOKEN") wrapper = UsernameToChatAPI( api_url="https://api.example.com/", api_key="YOUR_API_KEY", bot=bot ) try: # Both formats work: @username or username chat = await wrapper.resolve("@telegram") print(f"Chat ID: {chat.id}, Title: {chat.title}") except Exception as e: print(f"Error: {e}") finally: await wrapper.shutdown() # Integration with Application using custom context class CustomContext(CallbackContext): @property def wrapper(self) -> UsernameToChatAPI: return self.bot_data["wrapper"] async def resolve_username(self, username: str) -> Chat: return await self.wrapper.resolve(username) async def lookup_user(update: Update, context: CustomContext): """Look up a user by username.""" if not context.args: await update.message.reply_text("Usage: /lookup @username") return username = context.args[0] try: chat = await context.resolve_username(username) await update.message.reply_text( f"Found: {chat.first_name or chat.title} (ID: {chat.id})" ) except Exception as e: await update.message.reply_text(f"Error: {e}") context_types = ContextTypes(context=CustomContext) application: Application = ApplicationBuilder().token('TOKEN').context_types(context_types).build() wrapper = UsernameToChatAPI("https://api.example.com/", "API_KEY", application.bot) application.bot_data["wrapper"] = wrapper application.add_handler(CommandHandler("lookup", lookup_user)) application.run_polling() ``` -------------------------------- ### Basic Username to Chat Resolution with UsernameToChatAPI Source: https://github.com/python-telegram-bot/ptbcontrib/blob/main/ptbcontrib/username_to_chat_api/README.md Demonstrates the fundamental usage of the UsernameToChatAPI wrapper to resolve a username into a telegram.Chat object. It handles potential RetryAfter errors from the API. ```python import asyncio from ptbcontrib.username_to_chat_api import UsernameToChatAPI from telegram import Bot, error import time bot = Bot("BOT_TOKEN") wrapper = UsernameToChatAPI("https://localhost:1234/", "RationalGymsGripOverseas", bot) try: chat = asyncio.run(wrapper.resolve("@poolitzer")) except error.RetryAfter as e: time.sleep(e.retry_after) # both variants work chat = asyncio.run(wrapper.resolve("poolitzer")) ``` -------------------------------- ### LongBotCommand - Extended Command Descriptions (Python) Source: https://context7.com/python-telegram-bot/ptbcontrib/llms.txt The LongBotCommand class is an extension of the standard BotCommand, designed to accommodate command descriptions that exceed Telegram's 256-character limit. This is particularly useful for providing detailed help information directly within the bot's command list. ```Python from typing import List from telegram import Update from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes from ptbcontrib.longbotcommand import LongBotCommand # Example usage would typically involve creating LongBotCommand instances # and adding them as handlers to the application, similar to standard BotCommands. # For instance: # my_command = LongBotCommand( # command="help", # description="This is a very long description for the help command that goes beyond the standard 256 character limit imposed by Telegram.", # help_text="Use /help for detailed information." # ) # application.add_handler(CommandHandler(my_command.command, my_command.callback, description=my_command.description)) ``` -------------------------------- ### Send Telegram Messages with Keyword Arguments using send_by_kwargs Source: https://github.com/python-telegram-bot/ptbcontrib/blob/main/ptbcontrib/send_by_kwargs/README.md This function allows sending various types of Telegram messages by providing a dictionary of keyword arguments. It intelligently selects the appropriate send_* method from the bot object. If the selected method fails, it provides an informative error. Note that if only 'chat_id' is provided, 'send_dice' will be used by default. ```python from ptbcontrib.send_by_kwargs import send_by_kwargs kwargs = {'text': 'Hello there', 'caption': 'General Kenobi'} # Sends using send_message await send_by_kwargs(bot, kwargs, chat_id=123) # Sends using send_photo with a caption and ignores the text kwarg with open('photo.jpg', 'rb') as file: await send_by_kwargs(bot, kwargs, photo=file, chat_id=123) ``` -------------------------------- ### Role-Based Access Control (RBAC) Source: https://context7.com/python-telegram-bot/ptbcontrib/llms.txt The RolesHandler allows for granular access control by restricting command handlers based on user roles, supporting hierarchical permissions and bitwise operations. ```APIDOC ## Role-Based Access Control (RBAC) ### Description Restrict access to specific command handlers based on user roles defined in the application context. Roles support hierarchical inheritance and negation. ### Method N/A (Library Class) ### Endpoint ptbcontrib.roles.RolesHandler ### Parameters #### Constructor Parameters - **handler** (Handler) - Required - The telegram.ext handler to protect. - **roles** (Role/Roles) - Required - The role or set of roles permitted to access the handler. ### Request Example ```python application.add_handler(RolesHandler(CommandHandler('admin', admin_only_action), roles=roles.admins)) ``` ### Response #### Success Response - **Execution** (void) - The handler is executed only if the user satisfies the role requirements. ``` -------------------------------- ### Send Dynamic Messages with send_by_kwargs Source: https://context7.com/python-telegram-bot/ptbcontrib/llms.txt Simplifies message sending by automatically selecting the correct Telegram API method based on the provided keyword arguments. This reduces boilerplate code when handling different message types like locations, contacts, or media. ```python from ptbcontrib.send_by_kwargs import send_by_kwargs async def dynamic_send(update, context): bot = context.bot chat_id = update.effective_chat.id # Automatically detects send_message await send_by_kwargs(bot, {'text': 'Hello!'}, chat_id=chat_id) # Automatically detects send_location await send_by_kwargs(bot, {'latitude': 51.5, 'longitude': -0.1}, chat_id=chat_id) ``` -------------------------------- ### LogForwarder - Forward Application Logs to Telegram Source: https://context7.com/python-telegram-bot/ptbcontrib/llms.txt The LogForwarder class is a custom logging handler that redirects application logs to specified Telegram chats. This is useful for real-time monitoring of bot errors, warnings, and other log messages directly within Telegram. Dependencies include `logging` and `telegram.ext`. ```python import logging from telegram.ext import Application, ApplicationBuilder, CommandHandler, ContextTypes from ptbcontrib.log_forwarder import LogForwarder ``` -------------------------------- ### Extract User via Shared Users Source: https://github.com/python-telegram-bot/ptbcontrib/blob/main/ptbcontrib/extract_passed_user/README.md Demonstrates extracting the first user from the users_shared tuple within a message object. This method is useful when a user shares another user's profile via Telegram's native sharing feature. ```python shared_user = extract_passed_user(message=message) ``` -------------------------------- ### Extract User via Username Source: https://github.com/python-telegram-bot/ptbcontrib/blob/main/ptbcontrib/extract_passed_user/README.md Resolves a Telegram @username to a user ID using a provided username_resolver. This requires an instance of UsernameToChatAPI or a custom async function. ```python shared_user = extract_passed_user(message=message, username_resolver=UsernameToChatAPI(...)) ``` -------------------------------- ### get_num_from_text Function Source: https://github.com/python-telegram-bot/ptbcontrib/blob/main/ptbcontrib/extract_passed_user/README.md A helper function that extracts the first numerical string found within a given text. ```APIDOC ## get_num_from_text Function ### Description Helper function to extract the first numerical string found in a given text. ### Method N/A (This is a Python function, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Function Parameters - **text** (str) - Required - The input string to search for numbers. ### Request Example ```python number_str = get_num_from_text(text='Here my fried id - 123456, only numbers will be extracted.') # number_str will be '123456' ``` ### Response #### Success Response - **str** - The first found numerical string in the text, or an empty string if none is found. #### Response Example ```json { "extracted_number": "123456" } ``` ``` -------------------------------- ### Extract User Reference from Message (Python) Source: https://context7.com/python-telegram-bot/ptbcontrib/llms.txt The extract_passed_user function helps in extracting user information from various message formats, including shared users, contacts, user IDs in text, and @usernames. It optionally uses a username resolver for @username lookups. The get_num_from_text is a helper for extracting numeric IDs. ```Python from telegram import Update, SharedUser from telegram.ext import ApplicationBuilder, MessageHandler, filters, ContextTypes from ptbcontrib.extract_passed_user import extract_passed_user, get_num_from_text from ptbcontrib.username_to_chat_api import UsernameToChatAPI # Setup username resolver (optional, needed for @username resolution) wrapper = None # Initialize with UsernameToChatAPI if needed async def handle_user_reference(update: Update, context: ContextTypes.DEFAULT_TYPE): """Extract user from various input formats.""" message = update.message # Extracts user from: # 1. message.users_shared (keyboard user selection) # 2. message.contact (shared contact with user_id) # 3. @username in text (requires username_resolver) # 4. numeric user ID in text shared_user: SharedUser = await extract_passed_user( message=message, username_resolver=wrapper # Optional: for @username resolution ) if shared_user: await update.message.reply_text( f"Found user:\n" f"ID: {shared_user.user_id}\n" f"Username: @{shared_user.username or 'N/A'}\n" f"Name: {shared_user.first_name or ''} {shared_user.last_name or ''}" ) else: await update.message.reply_text("Could not extract user from message.") # Helper function usage def extract_id_example(): text = "Please ban user 123456789 for spam" user_id = get_num_from_text(text) print(f"Extracted ID: {user_id}") # Output: 123456789 application = ApplicationBuilder().token('YOUR_BOT_TOKEN').build() application.add_handler(MessageHandler( filters.TEXT | filters.CONTACT, handle_user_reference )) application.run_polling() ``` -------------------------------- ### URL Extraction Utility Source: https://context7.com/python-telegram-bot/ptbcontrib/llms.txt The extract_urls module provides helper functions to parse URLs and specific Telegram message links from message objects. ```APIDOC ## URL Extraction Utility ### Description Extracts hyperlinks and Telegram-specific message links from text messages or captions. ### Method N/A (Utility Functions) ### Endpoint ptbcontrib.extract_urls ### Parameters #### Function Parameters - **message** (telegram.Message) - Required - The message object to parse. - **private_only** (bool) - Optional - If True, filters for private group links only. - **public_only** (bool) - Optional - If True, filters for public group links only. ### Request Example ```python urls = extract_urls(message) private_links = extract_message_links(message, private_only=True) ``` ### Response #### Success Response - **urls** (list) - A list of strings containing the extracted URLs. ``` -------------------------------- ### Extract URLs from Telegram Messages Source: https://context7.com/python-telegram-bot/ptbcontrib/llms.txt Shows how to use the extract_urls and extract_message_links functions to parse hyperlinks and specific Telegram message links from text or captions. ```python from telegram import Update, Message from telegram.ext import ApplicationBuilder, MessageHandler, filters, ContextTypes from ptbcontrib.extract_urls import extract_urls, extract_message_links async def handle_message_with_urls(update: Update, context: ContextTypes.DEFAULT_TYPE): message: Message = update.message urls = extract_urls(message) if urls: await update.message.reply_text(f"Found URLs:\n" + "\n".join(urls)) all_tg_links = extract_message_links(message) print(f"All Telegram links: {all_tg_links}") private_links = extract_message_links(message, private_only=True) print(f"Private group links: {private_links}") public_links = extract_message_links(message, public_only=True) print(f"Public group links: {public_links}") application = ApplicationBuilder().token('YOUR_BOT_TOKEN').build() application.add_handler(MessageHandler(filters.TEXT | filters.CAPTION, handle_message_with_urls)) application.run_polling() ``` -------------------------------- ### ReplyToMessageFilter - Filter Replies to Specific Message Types Source: https://context7.com/python-telegram-bot/ptbcontrib/llms.txt The ReplyToMessageFilter class enables handlers that respond only to replies directed at specific message types (e.g., photos, text, documents). It can be combined with other filters for complex logic and can also be inverted to exclude certain reply types. Dependencies include `telegram` and `telegram.ext`. ```python from telegram import Update from telegram.ext import ApplicationBuilder, MessageHandler, filters, ContextTypes from ptbcontrib.reply_to_message_filter import ReplyToMessageFilter async def handle_reply_to_photo(update: Update, context: ContextTypes.DEFAULT_TYPE): """Triggered only when user replies to a photo.""" await update.message.reply_text("You replied to a photo!") async def handle_reply_to_text(update: Update, context: ContextTypes.DEFAULT_TYPE): """Triggered only when user replies to a text message.""" original_text = update.message.reply_to_message.text await update.message.reply_text(f"Original message: {original_text}") async def handle_document_reply_to_document(update: Update, context: ContextTypes.DEFAULT_TYPE): """Triggered when user sends a document as a reply to another document.""" await update.message.reply_text("Document received as reply to another document!") application = ApplicationBuilder().token('YOUR_BOT_TOKEN').build() # Handle replies to photos application.add_handler(MessageHandler( ReplyToMessageFilter(filters.PHOTO), handle_reply_to_photo )) # Handle replies to text messages application.add_handler(MessageHandler( ReplyToMessageFilter(filters.TEXT), handle_reply_to_text )) # Combine filters: document replies to documents application.add_handler(MessageHandler( filters.Document.ALL & ReplyToMessageFilter(filters.Document.ALL), handle_document_reply_to_document )) # Inverted filter: replies to anything except stickers application.add_handler(MessageHandler( ~ReplyToMessageFilter(filters.Sticker.ALL), lambda u, c: u.message.reply_text("This is not a reply to a sticker") )) application.run_polling() ``` -------------------------------- ### Extract Passed User Function Source: https://github.com/python-telegram-bot/ptbcontrib/blob/main/ptbcontrib/extract_passed_user/README.md The `extract_passed_user` function attempts to identify and return a user ID from a Telegram message. It checks `Message.users_shared`, `Message.contact`, and parses the `Message.text` for numerical IDs or `@username` mentions. ```APIDOC ## extract_passed_user Function ### Description Extracts a user ID from a Telegram message by checking `Message.users_shared`, `Message.contact`, and parsing `Message.text` for numerical IDs or `@username` mentions. ### Method N/A (This is a Python function, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Function Parameters - **message** (Message) - Required - The Telegram message object to process. - **username_resolver** (UsernameToChatAPI or async function) - Optional - A resolver function required when extracting a user ID from a `@username` mention in the text. ### Request Example ```python # Example using users_shared shared_user = extract_passed_user(message=message) # Example using contact shared_user = extract_passed_user(message=message) # Example using text id shared_user = extract_passed_user(message=message) # Example using text @name (requires username_resolver) shared_user = extract_passed_user(message=message, username_resolver=UsernameToChatAPI(...)) ``` ### Response #### Success Response - **User** - The extracted user object or ID. #### Response Example ```json { "user_id": 123456789, "username": "example_user", "first_name": "Example" } ``` #### Error Handling - If no user can be extracted from the provided sources, the function may return `None`. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.