Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Per server prefixs

I was wondering how I would go about allowing every server my bot is connected to, to set their own prefix. I am using the async version of dpy with Commands ext. I would assume you would store the prefix's and server name in a .json file, but I don't know how you would write them or check the file for them.

Thanks

like image 546
Tim Avatar asked Aug 19 '18 08:08

Tim


2 Answers

You can do this with dynamic command prefixes. Write a function or coroutine that takes a Bot and a Message and outputs the appropriate prefix for that message. Assuming you had a JSON of server ids to prefixes:

{ 
  "1234": "!",
  "5678": "?"
}

You can load that json into a dictionary and then look up server ids in that dictionary. Below I also include a default prefix, but you could also raise a CommandError or something for servers with no specific prefix.

from discord import commands
import json

with open("prefixes.json") as f:
    prefixes = json.load(f)
default_prefix = "!"

def prefix(bot, message):
    id = message.guild.id
    return prefixes.get(id, default_prefix)

bot = commands.Bot(command_prefix=prefix)

...
like image 53
Patrick Haugh Avatar answered Oct 21 '22 17:10

Patrick Haugh


Late answer, but for those others also looking for this you can use the get_prefix function.

It's very similar to Patrick Haugh's version, but a little different maybe because of different discord library versions?

prefixes = ['.','!','s.','k!']
ser_pref={'server id':['.',',']}
def get_prefix(bot, msg):
    if msg.guild.id in ser_pref:
        return commands.when_mentioned_or(*ser_pref['server id'])


    return commands.when_mentioned_or(*prefixes)(bot, msg)

bot = commands.Bot(command_prefix=get_prefix)

You can then later make commands to allow more custom server prefixes to other servers by adding their options to the dict

like image 45
KowaiiNeko Avatar answered Oct 21 '22 17:10

KowaiiNeko