代码之家  ›  专栏  ›  技术社区  ›  Javian Thor

如何修复Mongo DB delete_many({})错误

  •  0
  • Javian Thor  · 技术社区  · 3 月前

    我制作了一个不和谐的机器人,可以清除特定的数据库

    @bot.tree.command(name="clear-database", description="Clears the specified database.")
    @app_commands.choices(database=[
         app_commands.Choice(name="Keys", value="keys"),
         app_commands.Choice(name="Users", value="users")
    ])
    async def cleardb(i: discord.Interaction, database: app_commands.Choice[str]):
      try:
          if database.value == "keys":
             client.get_database("keys").get_collection("standard" + i.guild.id).delete_many({})
             await i.response.send_message(f"Cleared the {database.name} database.")
          elif database.value == "users":
             client.get_database("keys").get_collection("standard" + i.guild.id).delete_many({})
             await i.response.send_message(f"Cleared the {database.name} database.")
      except Exception as e:
         await i.response.send_message(f"Error, {e}")
         print(e)
    

    每当我使用该命令时,都会显示异常错误:“只能将str(而不是“int”)连接到str”

    我试着在谷歌上查找,但一切都完全无关。

    1 回复  |  直到 3 月前
        1
  •  0
  •   Soniya Prasad    3 月前

    我想,当你试图将公会ID与字符串“standard”连接起来时,可能会发生这个错误。

    让我们检查一下您的代码:

    client.get_database("keys").get_collection("standard" + i.guild.id).delete_many({})
    

    在这里 "standard" + i.guild.id 尝试连接字符串( "standard" )带有公会ID( i.guild.id ). 然而 i.guild.id 很可能是一个整数,并且Python不允许使用 + 操作人员

    要解决这个问题,你需要在连接公会ID之前将其转换为字符串。你可以使用 str() 函数来执行此操作。这是修改后的代码。

    client.get_database("keys").get_collection("standard" + str(i.guild.id)).delete_many({})
    

    此更改应该可以解决您遇到的错误。