我收到错误消息“ KeyError”,Python,电报api

时间:2020-06-02 11:46:37

标签: python api telegram

我正在为Telegram编程聊天机器人,它的作用并不重要。它访问Telegram的api并在那里处理json文件。

我想用requests.post(url + "getUpdates?offset=" + str(update_id))处理偏移量。

整个代码:

# -*- coding: utf-8 -*-

import requests as requests
import re
import codecs
import sys

from time import sleep

UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)

url = "https://some sort of api"

def get_chat_id(update):
    chat_id = update['message']["chat"]["id"]
    return chat_id

def get_message_text(update):
    message_text = update["message"]["text"]
    return message_text



def last_update(req):
    response = requests.get(req + "getUpdates")
    response = response.json()
    result = response["result"]
    total_updates = len(result) - 1
    return result[total_updates]

def send_message(chat_id, message_text):
    params = {"chat_id":chat_id, "text": message_text}
    response = requests.post(url + "sendMessage", data=params)
    return response

def main():
    update_id = last_update(url)["update_id"]

    while (True):
        update = last_update(url)
        message = get_message_text(update).lower()
        if update_id == update["update_id"]:
            if get_message_text(update).lower() == "Hello":
                send_message(get_chat_id(update), 'Hello World!')


            requests.post(url + "getUpdates?offset=" + str(update_id))
            update_id += 1
            sleep(1)

main()


错误消息:

  File "main.py", line 450, in <module>
    main()
  File "main.py", line 413, in main
    message = get_message_text(update).lower()
  File "main.py", line 21, in get_message_text
    message_text = update["message"]["text"]
KeyError: 'text'

0 个答案:

没有答案