【问题标题】:How to load arrays from json file in discord.py?如何从 discord.py 中的 json 文件加载数组?
【发布时间】:2022-01-25 21:49:03
【问题描述】:

我正在考虑创建一个事件,该事件将自动打开一个 json 文件,其中存储了诅咒词,以查看 json 文件中的任何诅咒词是否与发送的消息中的任何词匹配。如果是这样,该消息将自动被删除。但是,它似乎不起作用,因为我真的不知道如何使用 python 语言从 json 文件中加载数组。这是我的代码:

@client.event
async def on_message(message):
  with open ("json_files/cursewords.json", "r") as f:
    swearwords = json.load(f)

    cursewords = swearwords["cursewords"]

    if message.content.lower() == cursewords:
      await message.delete()
    else:
      await client.process_commands(message)

这也是我的 json 文件:

{
  "cursewords": [
    "curse1", 
    "curse2", 
    "curse3", 
    "curse4", 
    "curse5"
    ]
}

我非常感谢任何形式的帮助(curse1、curse2 等已更改为您不希望机器人识别的任何诅咒词)!

【问题讨论】:

  • 此代码正确地从 json 文件中获取单词并将它们转换为列表!没关系。

标签: python json discord


【解决方案1】:

您正在正确加载您的 json 文件。错误在于条件。您应该遍历列表中的每个脏话并检查消息内容是否包含它。

message_content = message.content.lower()
for swear_word in cursewords:
    if swear_word in message_content:
        await message.delete()
        return
await client.process_commands(message)

【讨论】:

    猜你喜欢
    • 2021-09-26
    • 2022-01-08
    • 2012-02-28
    • 1970-01-01
    • 2021-06-06
    • 2022-10-24
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    相关资源
    最近更新 更多