python - discord.py 添加到服务器上的 json 文件添加
问题描述
我希望我的机器人在对名为 settings.json 的 JSON 文件执行 $prefix(所需前缀)时添加服务器 ID 和选择的前缀。我在下面有一个这个 JSON 文件的例子。
{
"496019377515266060": "$"
}
我需要它,因此当用户键入 $prefix (所需前缀)时,它将添加他们的服务器 ID 和选择的前缀(如果不存在或存在则只会更新前缀)。我已经制作了自定义前缀,但我无法做到,因此用户可以更改它们。
注意 我没有使用重写分支。
解决方案
我在假设您的代码看起来或多或少像这个答案的情况下进行操作。json
每当我们更改文件时,我们都可以使用标准库模块来编辑它:
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)
@bot.command(name="prefix", pass_context=True)
async def _prefix(ctx, new_prefix):
# Do any validations you want to do
prefixes[ctx.message.server.id] = new_prefix
with open("prefixes.json", "w") as f:
json.dump(prefixes, f)
推荐阅读
- python - 在 python 中舍入随机数的最快方法
- php - 如何使用 laravel livewire 对 http 响应的结果进行分页
- flutter - 颤动,每当我进入 videoPlayerScreen 时,我的应用程序就会死机
- c++ - 类构造函数被误解
- javascript - 我可以使用 Mobx 商店制作可观察变量吗?
- angular - 使用 Karma Jasmine 在 Angular 的单元测试中无法读取未定义的属性“on”
- android - Android Mapbox 库错误与资源
- api - WSO2 使用属性表达式获取请求正文
- amazon-web-services - S3 对象级事件未触发
- python-3.x - 再次调用函数后,有没有办法让随机数重新填充到函数内部?