【发布时间】:2022-12-18 08:31:23
【问题描述】:
我一直在尝试创建一个命令,将用户 ID、选择和响应添加到 json 字典,但我意识到 json.dump 不是正确使用的函数,因为它只用新的替换了 {} 中的内容值,如何将值添加到 {} 中的新行而不是替换它?当我尝试“追加”这些值时,我也遇到了错误,但我不确定这是不是因为用户 ID 是一个 int,我尝试将用户 ID 转换为字符串,但我得到了同样的错误
async def on_submit(self, interaction: discord.Interaction):
with open("reports.json", "r") as f:
data = json.load(f)
if self.answer.value.lower() == "report" or self.answer.value.lower() == "suggestion":
await interaction.response.send_message("Successfully submitted your report/suggestion.", ephemeral=True)
print(f"{interaction.user} sent a {self.answer}: {self.answer2}")
user = data["user"] = str(interaction.user.id)
choice = data["choice"] = self.answer.value.lower()
message = data["message"] = f"{self.answer2.value}\n"
with open("reports.json", "w") as f:
user.append(interaction.user.id)
choice.append(self.answer.value.lower())
message.append(self.answer2.value)
顺便说一句,我收到这个错误
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/ui/modal.py", line 186, in _scheduled_task
await self.on_submit(interaction)
File "/home/container/main.py", line 312, in on_submit
user.append(interaction.user.id)
AttributeError: 'str' object has no attribute 'append'
【问题讨论】:
-
JSON 是什么样的/您期望什么格式?但是
user = data["user"] = str(interaction.user.id)并不是你想要的,也是错误的原因。尝试修改data,然后将其转储回文件。 -
我正在尝试逐行制作它,我将如何修改数据?
标签: python discord discord.py