Проблема с Python
Я в Питоне новичок. Пишу бота новостей и не могу догнать, где ошибка. Подскажите, пожалуйста.
import json
import requests
import keys
from news_file import get_news_from_keyword, get_news_from_topic
telegram_key = keys.get_telegram_key()
base_url = 'https://api.telegram.org/' + str(telegram_key)
while True:
try:
offset
except:
url = base_url + '/getUpdates'
res = requests.get(url)
res = res.text
res = json.loads(res)['result']
if res == []:
continue
res = res[0]['update_id']
offset = int(res) + 1
url = base_url + '/getUpdates' + '?timeout=500&offset=' + str(offset)
res = requests.get(url)
if len(json.loads(res.text)['result']) == 0:
continue
result = json.loads(res.text)['result'][0]
text = result['message']['text']
if text.lower() == 'end':
break
if text.lower().startswith('keyword'):
keyword = text.split(' ')[1:]
keyword = "%20".join(keyword)
to_send = get_news_from_keyword(keyword)
elif text.lower().startswith('topic'):
topic = text.split(' ')[1:]
topic = '%20'.join(topic)
to_send = get_news_from_topic(topic)
else:
to_send = '\nПриветствую тебя!\n\n' \
'Получить новости по теме :\n' \
'Тип "Topic Topic_Name" \n' \
'Пример : "Topic Weather" \n\n\n' \
'Получить новость по специальному слову\n' \
'Тип "keyword key" \n' \
'Пример : "Keyword Rain" \n\n\n' \
'Если вы не получили новость,\n' \
'Попробуйте отправить еще раз с правильным кодом\n\n\n' \
'Пожалуйста, подождите хотя бы 5 секунд, чтобы получить ответ\n'
sender = str(result['message']['from']['id'])
if type(to_send) == str:
reply_url = base_url + '/sendMessage?chat_id=' + str(sender) + '&text=' + str(to_send)
requests.get(reply_url)
if type(to_send) == list:
if len(to_send) == 0:
header = 'Не найдена новость :' + str(text) + '\nПерефразируйте это.'
reply_url = base_url + '/sendMessage?chat_id=' + str(sender) + '&text=' + str(header)
requests.get(reply_url)
requests.get(reply_url)
else:
header = 'Top ' + str(len(to_send)) + ' Результат для вас'
reply_url = base_url + '/sendMessage?chat_id=' + str(sender) + '&text=' + str(header)
requests.get(reply_url)
for reply in to_send:
reply_url = base_url + '/sendMessage?chat_id=' + str(sender) + '&text=' + str(reply)
requests.get(reply_url)
offset += 1
Выдаёт две ошибки.
line 11, in offset NameError: name 'offset' is not defined
line 17, in res = json.loads(res)['result'] KeyError: 'result'
Ответы (1 шт):
Автор решения: Рустам Нафиков
→ Ссылка
Могу подсказать лишь на счет первой ошибки: offset не существует на момент, когда ты пытаешься его вызвать. Его нужно хотя бы пустым объявить перед местом, где ты его вызываешь, чтобы потом в случае исключения у тебя нулевая переменная offset уже заполнилась тем, чем надо