Programming a Discord bot in Python- How do I make the bot restrict commands to a certain server?

Viewed 147

My bot is in multiple servers, and I want to make it only listen to a command if it's in certain server. Here's my code:

@client.command()
async def test(ctx):
  server = ctx.message.guild
  our_server = ('806969018689781870')
  if server.id == our_server:
    await ctx.send("Test confirmed!")

Here I get the ID of the server in which the command was triggered. Then I see if it equals the ID of the server I want to restrict it to. If it does, the command will be fulfilled.

However, this doesn't seem to work. It does not fulfill the command, and I don't get any errors. I'm new to programming, so any insight would be greatly appreciated.

2 Answers

ID's are integers, you're comparing a string

our_server = 806969018689781870
if server.id == our_server:
    await ctx.send("Test confirmed")

Also if you don't want to put this before every command you can make a global check

@client.check
async def check_guild(ctx):
    return ctx.guild.id == 806969018689781870

A simple way is to make a custom check decorator:

def only_this_guild(guild_id: int):
    async def predicate(ctx):
        if ctx.guild is None:
            raise commands.NoPrivateMessage() 
        return ctx.guild.id == guild_id           

    return commands.check(predicate)

you can then use this decorator on your command

@client.command()
@only_this_guild(806969018689781870)
async def test(ctx):
    await ctx.send("Test confirmed!")

If you then try to run this command from a DM or from another server it will raise an error which you can catch to inform users this command is not to be used or just silently ignore it.

Related