Python Telegram Bot:如何通过频道ID检查机器人是否为公开频道管理员?
Perfect question! Let's break down how to check if your Python Telegram Bot is an admin of a channel, using the channel ID you extract from a forwarded message. I'll cover implementations for both of the most widely used bot libraries: python-telegram-bot (version 20+, the latest stable) and pyTelegramBotAPI.
Step 1: Extract Channel ID from Forwarded Messages
First, you need to pull the channel ID from the forwarded message sent to your bot. The exact property to access depends on which library you're using:
Example with python-telegram-bot v20
from telegram import Update from telegram.ext import ApplicationBuilder, MessageHandler, filters, ContextTypes async def handle_forwarded_msg(update: Update, context: ContextTypes.DEFAULT_TYPE): # Verify the message is forwarded from a channel if update.message.forward_origin and update.message.forward_origin.type == "channel": channel_id = update.message.forward_origin.chat.id print(f"Extracted Channel ID: {channel_id}") # Check admin status and reply to user is_admin = await check_bot_admin(context, channel_id) reply_text = "I'm an admin of this channel!" if is_admin else "I'm not an admin here (or haven't joined the channel yet)." await update.message.reply_text(reply_text) # Initialize your bot app = ApplicationBuilder().token("YOUR_BOT_TOKEN").build() app.add_handler(MessageHandler(filters.FORWARDED, handle_forwarded_msg)) app.run_polling()
Example with pyTelegramBotAPI
import telebot bot = telebot.TeleBot("YOUR_BOT_TOKEN") @bot.message_handler(func=lambda msg: msg.forward_from_chat is not None) def handle_forwarded_msg(msg): channel_id = msg.forward_from_chat.id print(f"Extracted Channel ID: {channel_id}") # Check admin status and reply is_admin = check_bot_admin(bot, channel_id) reply_text = "I'm an admin of this channel!" if is_admin else "I'm not an admin here (or haven't joined the channel yet)." bot.reply_to(msg, reply_text) bot.polling()
Step 2: Implement the Admin Check Function
The core logic uses Telegram's get_chat_administrators API method to fetch all admins in the channel, then checks if your bot is in that list. You can also verify specific admin permissions if needed.
For python-telegram-bot v20
async def check_bot_admin(context: ContextTypes.DEFAULT_TYPE, channel_id: int) -> bool: try: # Get your bot's own user ID bot_user = await context.bot.get_me() bot_id = bot_user.id # Fetch all channel administrators admins = await context.bot.get_chat_administrators(channel_id) # Check if bot is in the admins list for admin in admins: if admin.user.id == bot_id: # Optional: Verify specific permissions (e.g., delete messages) # if admin.can_delete_messages: # return True return True return False except Exception as e: # Errors here mean the bot isn't a member of the channel, or has no access print(f"Admin check error: {e}") return False
For pyTelegramBotAPI
def check_bot_admin(bot: telebot.TeleBot, channel_id: int) -> bool: try: # Get your bot's own user ID bot_user = bot.get_me() bot_id = bot_user.id # Fetch all channel administrators admins = bot.get_chat_administrators(channel_id) # Check if bot is in the admins list for admin in admins: if admin.user.id == bot_id: # Optional: Verify specific permissions (e.g., post messages) # if admin.can_post_messages: # return True return True return False except Exception as e: # Errors here mean the bot isn't a member of the channel, or has no access print(f"Admin check error: {e}") return False
Key Notes
- Error Handling: If the bot hasn't joined the channel, calling
get_chat_administratorswill throw an exception (likeChatNotFoundorForbidden). We catch this and returnFalseto indicate the bot isn't a member/admin. - Specific Permissions: If you need to ensure the bot has certain admin rights (e.g., deleting messages, pinning posts), use the properties of the
ChatMemberAdministratorobject (likecan_delete_messagesorcan_pin_messages). - Channel ID Format: Channel IDs are always negative integers (e.g.,
-1001234567890), so make sure you're using the full numeric ID without any extra characters.
内容的提问来源于stack exchange,提问作者OuzKagan




