如何将拒绝消息添加到 Discord py 角色限制命令

Posted

技术标签:

【中文标题】如何将拒绝消息添加到 Discord py 角色限制命令【英文标题】:How to add reject message to Discord py role restricted commands 【发布时间】: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!")

【问题讨论】:

【参考方案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(),如果用户只指定了其中一个角色,它将允许您调用该命令。您无法检查用户是否有role1role2。 Documentation【参考方案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!")

【讨论】:

以上是关于如何将拒绝消息添加到 Discord py 角色限制命令的主要内容,如果未能解决你的问题,请参考以下文章

Discord Py - 如何使用文本命令向公会的所有成员添加多个角色

如何让我的机器人忽略来自具有特定角色的人的消息? (不和谐.py)

如何将 discord.py remove_roles 用于多个角色? (作为参数的对象列表)

通过 ID 添加角色 discord.py

discord.py 按内容获取消息

如何使用 discord.py 创建颜色角色