【发布时间】:2021-06-06 20:15:03
【问题描述】:
我正在尝试使用一些 JSON 集成在 python 中创建一个 Discord 机器人。我对此很陌生,所以我一直在关注一些教程并阅读其他机器人的代码。
我有 4 个命令使用 JSON 来存储数据和读取数据,这些命令来自一个特定于机器人连接到的每个 Discord Guild 的 JSON 文件。但是这些命令不起作用,并且不更新数据库。目的是该命令收集信息并将其存储起来以供将来与其他命令一起回调。
所有四个命令都给我这个错误:
Error when running command in Discord
四个命令的代码是这样的(抱歉,代码太长了):
# Adds a quote to the Database
@bot.command()
async def addquote(ctx):
with open(str(bot.guilds) + ".json", 'r') as infile:
parsed_json = json.load(infile)
quote = ctx.quote.replace('.addquote', '') # Removes the command from the message
length = AddRecord(parsed_json, ctx.author, quote, ctx.timestamp.date()) # Update local variable holding json
UpdateDB(parsed_json, str(bot.guilds) + ".json") # Rewrite to file
await client.send_message(message.channel, "quote {} added".format(length))
# Adds a quote with name to the Database
@bot.command()
async def addquotename(ctx):
with open(str(bot.guilds) + ".json", 'r') as infile:
parsed_json = json.load(infile)
quote = ctx.content.replace("!addquotewithname ", "") # Removes the command from the message
name = quote.split(' ')[0]
quote = quote.replace(name + " ", "")
length = AddRecordWithName(parsed_json, name, ctx.author, quote, ctx.timestamp.date()) # Update local variable holding json
UpdateDB(parsed_json, str(bot.guilds) + ".json") # Rewrite to file
await client.send_message(message.channel, "quote '{}' added".format(name))
# Gives a random quote from the Database
@bot.command()
async def randomquote(ctx):
with open(str(bot.guilds) + ".json", 'r') as infile:
parsed_json = json.load(infile)
num = random.randint(1, len(parsed_json["quotes"]) - 1)
await client.send_message(message.channel, "quote " + str(num) + ": " + parsed_json["quotes"][str(num)]["content"])
# This command informs who added the quote to the Database
@bot.command()
async def quoteaddedby(ctx):
data = ctx.content.replace("!quoteaddedby", "")
try:
with open(str(bot.guilds) + ".json", 'r') as infile:
parsed_json = json.load(infile)
quotenum = int(data)
if quotenum > len(parsed_json["quotes"]):
print(len(parsed_json["quotes"]))
await client.send_message(message.channel, "Number too large, there are {} quotes".format(len(parsed_json["quotes"]) - 1))
return
await client.send_message(message.channel, parsed_json["quotes"][str(quotenum)]["addedby"])
except ValueError:
await client.send_message(message.channel, "Error - quote requested must be by number")
谢谢
【问题讨论】:
-
您认为
str(bot.guilds)究竟返回了什么?我建议使用带有键和值的单个 json 文件,而不是使用动态名称制作新的 json 文件 -
嗨!通过使用 str(bot.guilds),它将打开特定文件以存储提供给命令的数据。正如我所说,我对此很陌生,所以我正在努力学习。我将尝试寻找另一种解决方案。谢谢!
标签: json python-3.x discord discord.py bots