You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

解决Discord机器人MongoDB delete_many({})执行时的拼接错误

问题原因

错误can only concatenate str (not "int") to str的核心原因是:i.guild.id是整数类型,你试图直接将它与字符串"standard"进行拼接,而Python不支持字符串和整数的直接相加操作。

解决方案

将i.guild.id转换为字符串后再拼接,有两种简洁的实现方式:

方式1:使用str()函数转换类型

把代码中两处的"standard" + i.guild.id替换为:

"standard" + str(i.guild.id)

方式2:使用f-string格式化(推荐)

f-string是Python 3.6+的特性,写法更直观:

f"standard{i.guild.id}"
修改后的完整代码
@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(f"standard{i.guild.id}").delete_many({})
         await i.response.send_message(f"Cleared the {database.name} database.")
      elif database.value == "users":
         # 修正原代码的数据库名称错误
         client.get_database("users").get_collection(f"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)
额外提示

原代码中清理Users数据库时,错误地调用了client.get_database("keys"),这会导致实际清理的还是Keys数据库的集合,已在修改后的代码中修正为client.get_database("users"),若不符合你的实际需求可自行调整。

内容的提问来源于stack exchange,提问作者Javian Thor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 18:16:22