我的前缀字符串不起作用?主要第13行。有什么解决办法/建议吗?我有一个prefixes.json文件。我该试试什么?我应该使用数据库吗?我可能把message.guild写错了。YT视频
import discord
from discord.ext import commands
import json
def get_prefix(client,message):
with open("prefixes.json", "r") as f:
prefixes = json.load(f)
return prefixes[str(message.guild.id)]
client = commands.Bot(command_prefix= get_prefix)
client.remove_command("help")
@client.event
async def on_guild_join(guild):
with open("prefixes.json", "r") as f:
prefixes = json.load(f)
prefixes[str(guild.id)] = ">"
with open("prefixes.json", "w") as f:
json.dump(prefixes,f)
@client.event
async def on_ready():
print("Sir yes sir")
@client.command()
@commands.has_permissions(administrator = True)
async def changeprefix(ctx, prefix):
with open("prefixes.json", "r") as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)] = prefix
with open("prefixes.json", "w") as f:
json.dump(prefixes,f)
await ctx.send(f"The prefix was changed to {prefix}")
@client.event
async def on_message(msg):
try:
if msg.mentions[0] == client.user:
with open("prefixes.json", "r") as f:
prefixes = json.load(f)
pre = prefixes[str(msg.guild.id)] = prefix
await msg.channel.send(f"My prefix for this server is {pre}")
except:
pass
await client.process_commands(msg)此错误:
File "D:\Discord Bots\8's Server Bot\Bot.py", line 13, in get_prefix
return prefixes[str(message.guild.id)]
KeyError: '960030765704417351'发布于 2022-04-13 07:30:48
当密钥不在json文件中时,就会发生这种情况。尝试删除并在服务器运行时将机器人添加到服务器中。如果这不起作用,请尝试手动添加该行。如果它仍然不能工作,这意味着get_prefix无法正确地访问文件。
还有另一个事件函数,on_guild_remove,用于删除json文件中的密钥,以防机器人从公会中删除。这里有更多的信息。
https://stackoverflow.com/questions/71813908
复制相似问题