如何将getUpdates()与JSON结合使用

2024-06-16 11:19:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我在网上找到了一个方法,可以用来检索消息和更新bot。你知道吗

下面是我找到的代码:

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的形式返回消息,这可能吗?你知道吗


Tags: theselfjson消息bytesobjectbotupdate
1条回答
网友
1楼 · 发布于 2024-06-16 11:19:55

看起来您正在使用telepot库。你知道吗

关于此错误:

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

函数json.loads()接收str并返回dictAs long asupdateUpdatelistupdate[2]Update。您将update[2]传递给json.loads(),因此出现了上面的错误。你知道吗


I want to return the message as a json

我不明白你说的“返回一个JSON”是什么意思,但这里有两个选项在注释中描述。为您选择合适的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。你知道吗

相关问题 更多 >