每服务器前缀 [英] Per server prefixs
问题描述
我想知道如何允许我的机器人连接到的每个服务器设置自己的前缀。我在Commands ext中使用dpy的异步版本。
我假设您会将前缀和服务器名称存储在.json文件中,但我不知道如何编写或检查它们。
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.
谢谢
推荐答案
您可以使用动态命令前缀来实现。编写一个函数或协程,使其接受 Bot
和 Message
并输出该消息的适当前缀。假设您具有服务器ID的JSON前缀:
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": "?"
}
您可以将该json加载到字典中,然后在其中查找服务器ID字典。在下面,我还提供了一个默认前缀,但是您也可以为没有特定前缀的服务器引发 CommandError
或其他内容。
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.server.id
return prefixes.get(id, default_prefix)
bot = commands.Bot(command_prefix=prefix)
...
这篇关于每服务器前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!