首页 > 解决方案 > 为什么我不能限制我的机器人使用命令 - discord.py

问题描述

'''
@client.event
@commands.has_role('xrole')
async def on_message(message):
#Commands

  if message.content.startswith("!set"):
    credits_message = message.content.split(" ", 2)

    user_name = credits_message[1]
    credit_add_amount = credits_message[2]

    db[user_name] = int(credit_add_amount)   

    #DB Stuff
    await message.channel.send(user_name + "has been set with " + credit_add_amount + ", For further credit adgustment use !add")

 
'''

出于某种原因,无论有没有 xrole 的用户都可以访问机器人,即使有 @commands 限制

没有 xrole 的用户

没有 xrole 的用户^

具有 xrole 的用户

具有 xrole 的用户 ^

标签: discord.py

解决方案


首先不要on_message用于命令,最好使用@bot.command

第二:这段代码应该适合你

@bot.command(pass_context=True)
@commands.has_role("xrole")
async def role_check(ctx):
    await ctx.channel.send('''you have the role "xrole"''')


@role_check.error
async def info_error(ctx, error):
    if isinstance(error, (commands.MissingRole, commands.MissingAnyRole)):
        await ctx.channel.send('''you do not have the role "xrole"''')

推荐阅读