首页 > 解决方案 > 如何将拒绝消息添加到 Discord py 角色限制命令

问题描述

我有这个代码:

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!")

标签: pythonpython-3.xdiscordrolesdiscord.py

解决方案


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

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')

推荐阅读