You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何通过python-telegram-bot API验证Telegram机器人指令发送者是否为管理员

检查指令发送者是否为管理员(python-telegram-bot)

嘿,这个需求我之前做机器人的时候正好碰到过,用python-telegram-bot实现管理员权限校验其实很直观,下面分主流版本给你讲具体实现:

一、python-telegram-bot v20+(当前推荐版本)

这个版本采用全新的异步API,检查逻辑可以这么写:

1. 实时检查(单命令内实现)

在你的kick/ban命令处理函数里,先获取当前用户的群聊成员身份,再判断是否为管理员或群主:

from telegram import Update, ChatMemberStatus
from telegram.ext import ContextTypes

async def kick_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    # 获取当前聊天ID和发送者ID
    chat_id = update.effective_chat.id
    user_id = update.effective_user.id

    # 获取发送者的群聊成员信息
    chat_member = await context.bot.get_chat_member(chat_id=chat_id, user_id=user_id)
    
    # 判断是否为管理员或群主
    if chat_member.status not in [ChatMemberStatus.ADMINISTRATOR, ChatMemberStatus.OWNER]:
        await update.message.reply_text("抱歉,只有管理员才能执行这个操作!")
        return
    
    # 这里写你的kick逻辑
    # ...

2. 用装饰器批量处理(更优雅)

如果多个命令都需要管理员权限,写个装饰器可以避免重复代码:

from functools import wraps
from telegram import Update, ChatMemberStatus
from telegram.ext import ContextTypes

def admin_only(func):
    @wraps(func)
    async def wrapper(update: Update, context: ContextTypes.DEFAULT_TYPE):
        chat_id = update.effective_chat.id
        user_id = update.effective_user.id
        chat_member = await context.bot.get_chat_member(chat_id=chat_id, user_id=user_id)
        
        if chat_member.status not in [ChatMemberStatus.ADMINISTRATOR, ChatMemberStatus.OWNER]:
            await update.message.reply_text("抱歉,只有管理员才能执行这个操作!")
            return
        return await func(update, context)
    return wrapper

# 然后给需要权限的命令加装饰器
@admin_only
async def kick_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    # 你的kick逻辑
    pass

@admin_only
async def ban_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    # 你的ban逻辑
    pass

二、python-telegram-bot v13.x(旧版本,同步API)

如果还在使用旧版的同步API,逻辑类似,只是语法稍有不同:

from functools import wraps
from telegram import ChatMember
from telegram.ext import Updater, CommandHandler

def admin_only(func):
    @wraps(func)
    def wrapper(update, context):
        chat_id = update.effective_chat.id
        user_id = update.effective_user.id
        chat_member = context.bot.get_chat_member(chat_id=chat_id, user_id=user_id)
        
        # 旧版本用字符串判断状态
        if chat_member.status not in ['administrator', 'creator']:
            update.message.reply_text("抱歉,只有管理员才能执行这个操作!")
            return
        return func(update, context)
    return wrapper

@admin_only
def kick_command(update, context):
    # 你的kick逻辑
    pass

注意事项

  • 确保你的机器人在群聊中拥有查看成员信息的权限,否则get_chat_member会抛出权限错误。
  • 群主(OWNER/creator)的权限高于普通管理员,所以建议把他们也纳入允许范围。

内容的提问来源于stack exchange,提问作者ICanKindOfCode

火山引擎 最新活动