discord.py - 为不同的不和谐服务器创建自定义前缀
问题描述
我试图让机器人有一个前缀,你可以为你想要的每台服务器使用,但是当你使用命令时,它会在控制台中弹出
return prefixes[str(message.guild.id)] #recieve the prefix for the guild id given
KeyError: '882434407212925000'
这是我使用的代码和它说它失败的行
def get_prefix(client, message): ##first we define get_prefix
with open("prefixes.js", "r") as f: ##we open and read the prefixes.json, assuming it's in the same file
prefixes = json.load(f) #load the json as prefixes
return prefixes[str(message.guild.id)] #recieve the prefix for the guild id given
解决方案
错误的文件类型
首先,您尝试输入的文件是一个 .js (JavaScript) 文件,它不是一种数据库形式。您很可能正在寻找可以存储数据的 .json(JavaScript 对象表示法)文件。
公会ID找不到
您的代码不起作用的另一个原因是您返回的数据集不存在。换句话说,公会不在前缀文件中。
例子
def get_prefix(client, message):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
try:
return prefixes[str(message.guild.id)]
except:
prefixes[str(message.guild.id)] = 'put default prefix here'}
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f)
return prefixes(message.guild.id)]
将“将默认前缀放在此处”替换为您的机器人前缀。
解释
在上面的示例中,我在您的代码中添加了一个 try except,以便在发生错误时(无法在数据集中找到公会)将其添加到数据集中并返回机器人的默认前缀作为占位符。
推荐阅读
- linux - 在 unix 中使用 sed 将文件中的所有单词转换为 *
- c++ - 在返回值上调用 std::move - 签名应该是什么
- python-3.x - RuntimeError:reduce 同步失败:设备端断言触发
- python - 遍历 pandas 中的行并计算唯一的主题标签
- echarts - 如何设置 echarts-gl 图表的初始旋转?
- swift - 在 2D 图像中使用 ARSCNFaceGeometry 几何点
- joomla - joomla3 超级用户的密码被黑了
- python - 在 psycopg2 中移动命名光标
- javascript - 使用 Jest 的通用捕获测试代码 - 竞争条件
- python - 使用 MySQL 数据库中的 python 烧瓶计算列的平均值:NameError: name 'rate' is not defined