【问题标题】:How to add reject message to Discord py role restricted commands如何将拒绝消息添加到 Discord py 角色限制命令
【发布时间】:2020-02-22 23:47:07
【问题描述】:

我有这个代码:

import discord
from discord.ext import commands, tasks
import random
from itertools import cycle
from discord.utils import get
import os

bot = commands.Bot(command_prefix='-')


TOKEN = ''


@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')



@bot.command()
@commands.has_role('Admin')
async def test(ctx):
    await ctx.send(":smiley: :wave: Hello, there! :heart: ")

bot.run(TOKEN)

如何设置拒绝消息? 我的意思是如果有人使用该命令但他没有管理员角色,机器人会说类似 “你不是管理员伙伴!”

我试过了,但没用

@bot.command()
@commands.has_role('Admin')
async def test(ctx):
    await ctx.send(":smiley: :wave: Hello, there! :heart: ")
    else:
        await ctx.send("You can't use this!")

【问题讨论】:

    标签: python python-3.x discord roles discord.py


    【解决方案1】:

    当用户调用测试命令并且他们没有“管理员”角色时,会引发 commands.MissingRole 错误。您可以通过error handling 了解这一点。

    import discord
    from discord.ext import commands, tasks
    import random
    from itertools import cycle
    from discord.utils import get
    import os
    
    TOKEN = ''
    
    bot = commands.Bot(command_prefix='-')
    
    @bot.event
    async def on_ready():
        print('Logged in as')
        print(bot.user.name)
        print(bot.user.id)
        print('------')
    
    @bot.command()
    @commands.has_role('Admin')
    async def test(ctx):
        await ctx.send(":smiley: :wave: Hello, there! :heart: ")
    
    @test.error
    async def test_error(ctx, error):
        if isinstance(error, commands.MissingRole):
            await ctx.send('''You aren't admin buddy!''')
    
    bot.run('TOKEN')
    

    【讨论】:

    • 如果这个人有多个权限命令,这将不起作用。
    • @FluxedScript,如果你想指定多个权限命令@commands.has_any_role(role1, role2 ...) 可以很好地解决这个问题,然后当你处理错误时会抛出commands.MissingAnyRole 错误而不是commands.MissingRole。缺点是使用commands.has_any_role(),如果用户只指定了其中一个角色,它将允许您调用该命令。您无法检查用户是否有role1role2Documentation
    【解决方案2】:

    如果用户没有角色,这将让您向用户发送消息。您也可以拥有多个角色而不是管理员。

    @bot.command()
    async def test(ctx):
        if "Admin" in ctx.author.roles:
            await ctx.send(":smiley: :wave: Hello, there! :heart: ")
        else:
            await ctx.send("You are not an admin!")
    

    【讨论】:

      猜你喜欢
      • 2021-09-04
      • 1970-01-01
      • 1970-01-01
      • 2020-10-09
      • 2021-10-09
      • 1970-01-01
      • 2021-02-01
      • 2021-05-22
      • 2021-04-03
      相关资源
      最近更新 更多