如何通过用户名获取用户ID以使用python-telegram-bot踢群成员
根据用户名获取Telegram用户ID的方法(python-telegram-bot)
以下是几种针对你的场景的可行方案,均基于python-telegram-bot库实现:
1. 直接查询群组内的成员ID
如果目标用户在你要操作的群组中,可以调用get_chat_member方法获取用户信息,从中提取ID:
from telegram import Bot # 初始化机器人 bot = Bot(token="你的机器人令牌") # 替换为你的目标群组ID(负数格式) target_chat_id = -1001234567890 # 替换为目标用户名(不带@前缀) target_username = "example_user" try: chat_member = bot.get_chat_member(target_chat_id, target_username) user_id = chat_member.user.id print(f"目标用户ID:{user_id}") # 后续直接使用ban_chat_member # bot.ban_chat_member(target_chat_id, user_id) except Exception as e: print(f"获取失败:{e}")
注意:该方法仅适用于目标用户当前在群组内的情况,否则会抛出权限或用户不存在的异常。
2. 提前监听群组消息收集ID
如果需要批量或提前获取群组用户的ID,可以通过消息处理器监听群组内的消息,自动记录用户名与ID的对应关系(可存入字典或数据库):
from telegram.ext import Updater, MessageHandler, Filters # 用于存储用户名和ID的映射 user_id_map = {} def track_user_ids(update, context): user = update.message.from_user if user.username: user_id_map[user.username] = user.id # 可选:打印或持久化存储 print(f"已记录:@{user.username} -> {user.id}") def main(): updater = Updater("你的机器人令牌") dp = updater.dispatcher # 监听群组内所有消息 dp.add_handler(MessageHandler(Filters.chat_type.groups, track_user_ids)) updater.start_polling() updater.idle() if __name__ == "__main__": main()
后续需要踢人时,直接从user_id_map中通过用户名取出ID即可。
3. 使用新版本库的get_users方法
如果你使用的是python-telegram-bot v20及以上版本,可以直接调用get_users方法批量查询用户名对应的用户信息:
from telegram import Bot bot = Bot(token="你的机器人令牌") target_username = "example_user" try: # 传入用户名列表,返回User对象列表 users = bot.get_users([target_username]) if users: user_id = users[0].id print(f"目标用户ID:{user_id}") except Exception as e: print(f"获取失败:{e}")
注意:该方法要求机器人与目标用户存在互动(同群组或用户曾给机器人发过消息),否则无法获取到用户信息。
内容的提问来源于stack exchange,提问作者mlody jano
相关产品推荐
相关产品推荐

