Search code examples
pythonpython-3.xdiscordrolesdiscord.py

How to add reject message to Discord py role restricted commands


I have this code:

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)

How I can set a reject message? I mean if someone use that command but he doesn't have Admin role, bot will say something like "You aren't admin buddy!"

I've tried this but did not work

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

Solution

  • When a user calls the test command and they do not have the 'Admin' role, a commands.MissingRole error is thrown. You can catch this with 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')