【问题标题】:pymongo returning "Command raised an exception: InvalidDocument: cannot encode object:" when storing datapymongo在存储数据时返回“命令引发异常:InvalidDocument:无法编码对象:”
【发布时间】:2021-10-24 22:44:40
【问题描述】:

我有一个问题,如何使用 Pymongo 编写角色和其他项目的存储,我尝试这样做:

@Bot.event
async def on_ready():
    await Bot.change_presence(status = discord.Status.online, activity = discord.Streaming(name = '!help', url = ''))
    print(Bot.user.name + " is ready.")

    for guild in Bot.guilds:
        for member in guild.members:
            post = {
                "_id": member.id,
                "server_id": guild.id,
                "balance": 300,
                "xp": 0,
                "lvl": 1
         },
         {
             "role": 0,
             "cost": 0
         }

         if collection.count_documents({"_id": member.id}) == 0:
             collection.insert_one(post)

    @commands.command()
    async def add_shop(self, ctx, role: discord.Role, cost: int):
        self.collection.update_one({"_id": ctx.author.id},
            {"$set": {"role": role}})
        self.collection.update_one({"_id": ctx.author.id},
            {"$set": {"cost": cost}})

    await ctx.message.add_reaction("✅")

@commands.command()
async def shop(self, ctx):
    r = self.collection.find_one({"_id": ctx.author.id}["role"])
    c = self.collection.find_one({"_id": ctx.author.id}["cost"])

    await ctx.send(r, c)

但这对我来说并不奏效。我决定联系你。提前谢谢!

【问题讨论】:

  • 当你说“它没有成功”时,你得到了什么错误?
  • 命令引发异常:InvalidDocument:无法编码对象:,类型: 并且在输入第二个命令时:discord.ext.commands.errors.CommandInvokeError:命令引发异常:KeyError:'role'
  • @Den 第一个不言自明,您不能在 MongoDB 中放置 discord.Role,因为它不知道如何处理它。改为存储角色的IDadd_shop 命令的第二行)。
  • 我想获取角色ID,用于使用命令添加角色。

标签: python mongodb discord.py pymongo


【解决方案1】:

MongoDB 和 pymongo 只能存储某些可以理解的类型的对象,例如字符串、数字、日期等here 列出的一些对象。

如果您尝试在这些明确定义的类型之外添加其他类型、对象、类等,您将收到上述错误。

您需要将任何类型转换为支持的类型;如果类支持这一点,也许可以尝试转换为字符串(使用str(object)),否则这里有一些有用的通用文档:

https://pymongo.readthedocs.io/en/stable/examples/custom_type.html

【讨论】:

  • 我能够将角色写入数据库,但输出返回错误:丢弃。 text.commands.errors.Command 调用错误:命令引发异常:KeyError: 'role'
猜你喜欢
  • 2023-03-05
  • 1970-01-01
  • 2013-08-28
  • 1970-01-01
  • 2017-11-17
  • 2013-02-25
  • 2019-08-15
  • 2021-04-30
  • 1970-01-01
相关资源
最近更新 更多