0

我在网上找到了一种用于检索消息和更新机器人的方法。

这是我找到的代码:

def getMessage(self, offset):
    if offset:
        update = self.bot.getUpdates(offset=offset) 
    else:
        update = self.bot.getUpdates()
    update_json = json.loads(update[2])
    return update_json

我收到以下错误:

TypeError(f'the JSON object must be str, bytes or bytearray, '  
TypeError: the JSON object must be str, bytes or bytearray, not Update

我想将消息作为 json 返回,这可能吗?

4

1 回答 1

0

看起来你正在使用telepot图书馆。

关于这个错误:

TypeError(f'JSON对象必须是str, bytes or bytearray, '
TypeError: JSON对象必须是str, bytes or bytearray, 不是Update

函数json.loads()接收 astr并返回 a dict只要 update是s的一个,list就是一个。而且您正在传递给,因此出现上述错误。Updateupdate[2]Updateupdate[2]json.loads()


我想将消息作为 json 返回

我不明白“返回 JSON”是什么意思,但这里有 2 个选项在评论中描述。选择return适合您的:

def getMessage(self, offset):
    if offset:
        updates = self.bot.getUpdates(offset=offset) 
    else:
        updates = self.bot.getUpdates()

    # updates is a list of <Update> objects
    # an <Update> can or can not be a <Message>

    # if you want to return a message from a third update as a python dict use this:
    return updates[2]["message"]  # dict

    ### OR ###

    # if you want to return a message from a third update as a JSON string, use this:
    return json.dumps(update[2]["message"])  # JSON string

边注

我也不明白你为什么要从更新列表中返回第三个元素。

请注意,它updates可以是一个空列表(或其中少于 3 个元素的列表),并且updates[2]会引发IndexError.

于 2019-05-22T15:08:02.803 回答