0
https://api.telegram.org/bot<token>/getUpdates

我想用python制作一个聊天机器人并将其与电报集成。我正在使用这个 API 来获取用户消息。它工作正常,但有时结果字段为空。因此我的代码崩溃了。一段时间后,我能够看到内容。如何解决这个问题呢。

import requests

def get_last_update(offset):
  url="https://api.telegram.org/bot<token>/getUpdates?timeout=100"
  if offset:
    url=url+"&offset={}".format(offset+1)
  res=requests.get(url).json()
  return res["result"]

def send_message(chat_id,message):
  requests.post("https://api.telegram.org/bot<token>/sendMessage?text={}&chat_id={}".format(message,chat_id))

def find_ans(message):
  return "hi i am bot"


update_id=None
while True:
    updates = get_last_update(update_id)
    if updates:
        for item in updates:
            update_id = item["update_id"]
            try:
                message = str(item["message"]["text"])
            except:
                message = None
            from_ = item["message"]["from"]["id"]
            reply = find_ans(message)
            send_message(from_,reply)

这段代码应该可以正常工作吗?

KeyError                                  Traceback (most recent call last)

<ipython-input-83-741da05a9e41> in <module>()
      1 update_id=None
      2 while True:
----> 3     updates = get_last_update(update_id)
      4     if updates:
      5         for item in updates:

<ipython-input-77-cbcc58e3e84e> in get_last_update(offset)
     65     url=url+"&offset={}".format(offset+1)
     66   res=requests.get(url).json()
---> 67   return res["result"]
     68 
     69 

KeyError: 'result'

这是我得到的错误。

4

0 回答 0