如何用Pyrogram等Python库获取Telegram频道消息发送者的ID/用户名?
在Telegram Bot中获取频道消息发送者的用户名/ID
使用Pyrogram实现
首先确保你的Bot是频道管理员,并且开启了读取消息权限。频道消息的发送者信息获取逻辑分两种情况:
- 普通频道或超级频道中管理员发送的消息,可通过
message.from_user拿到实际用户信息 - 超级频道中以频道名义发送的消息,
message.sender_chat会返回频道本身的信息(若Bot有权限查看管理员发送记录,from_user仍会存在)
代码示例:
from pyrogram import Client, filters # 替换为你的Bot配置 app = Client("my_channel_bot", api_id=你的API_ID, api_hash="你的API_HASH", bot_token="你的BotToken") @app.on_message(filters.chat("你的频道ID或用户名")) async def process_channel_msg(client, message): # 优先获取实际发送用户 if message.from_user: user_id = message.from_user.id username = message.from_user.username or "无用户名" print(f"发送者ID: {user_id}, 用户名: @{username}") # 若无法获取用户,获取发送消息的频道实体 elif message.sender_chat: chat_id = message.sender_chat.id chat_title = message.sender_chat.title print(f"消息来自频道: {chat_title}, 频道ID: {chat_id}") else: print("无法获取发送者信息") app.run()
使用python-telegram-bot实现
在v13+版本中,逻辑和Pyrogram类似,通过message.from_user和message.sender_chat获取信息:
代码示例:
from telegram import Update from telegram.ext import Updater, MessageHandler, Filters, CallbackContext def process_channel_msg(update: Update, context: CallbackContext): msg = update.effective_message if msg.from_user: user_id = msg.from_user.id username = msg.from_user.username or "无用户名" print(f"发送者ID: {user_id}, 用户名: @{username}") elif msg.sender_chat: chat_id = msg.sender_chat.id chat_title = msg.sender_chat.title print(f"消息来自频道: {chat_title}, 频道ID: {chat_id}") else: print("无法获取发送者信息") def main(): updater = Updater("你的BotToken") dp = updater.dispatcher dp.add_handler(MessageHandler(Filters.chat("你的频道ID或用户名"), process_channel_msg)) updater.start_polling() updater.idle() if __name__ == "__main__": main()
注意事项
- 无论用哪个库,Bot必须是频道管理员,且开启查看消息权限
- 超级频道中,只有当消息由管理员主动发送时,才能拿到
from_user信息;系统自动发送的消息(如频道公告)只能拿到sender_chat
内容的提问来源于stack exchange,提问作者nexgen
相关产品推荐
相关产品推荐

