问题描述
我想知道如何让我的机器人连接到的每台服务器都设置自己的前缀.我正在使用带有 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.guild.id return prefixes.get(id, default_prefix) bot = commands.Bot(command_prefix=prefix) ...