[Python] Exception of type KeyError in check_new_post(): slice(1, None, None) [closed]

Discussão em 'Python' iniciado por Stack, Fevereiro 15, 2025.

  1. Stack

    Stack Membro Participativo

    When running, the following code throws an error Exception of type KeyError in check_new_post(): slice(1, None, None) I don't quite understand what this is about and how to fix it. This is the code for the Autoposting bot from vk to tg.



    import time
    import eventlet
    import requests
    import logging
    import telebot

    from time import sleep

    URL_VK = 'https://api.vk.com/method/wall.get?...'
    FILENAME_VK = 'posts_id.txt'
    BASE_POST_URL = 'https://vk.com/xxx?w=wall-xxx'

    BOT_TOKEN = 'xxxx'
    CHANNEL_NAME = '@test'

    bot = telebot.TeleBot(BOT_TOKEN)


    def get_data():
    timeout = eventlet.Timeout(10)
    try:
    feed = requests.get(URL_VK)
    return feed.json()
    except eventlet.timeout.Timeout:
    logging.warning('Got Timeout while retrieving VK JSON data. Cancelling...')
    return None
    finally:
    timeout.cancel()


    def send_new_posts(items, last_id):
    for item in items:
    if item['id'] <= last_id:
    break
    link = '{!s}{!s}'.format(BASE_POST_URL, item['id'])
    bot.send_message(CHANNEL_NAME, link)

    time.sleep(1)
    return


    def check_new_posts_vk():

    logging.info('[VK] Started scanning for new posts')
    with open(FILENAME_VK, 'rt') as file:
    last_id = int(file.read())
    if last_id is None:
    logging.error('Could not read from storage. Skipped iteration.')
    return
    logging.info('Previous last_id is {!s}'.format(last_id))
    try:
    feed = get_data()


    if feed is not None:
    # 0 - это какое-то число, так что начинаем с 1

    entries = feed['response'][1:]

    try:

    # Если пост был закреплен, пропускаем его
    tmp = entries[0]['is_pinned']
    send_new_posts(entries[1:], last_id)
    except KeyError:
    send_new_posts(entries, last_id)
    # Записываем новую "верхушку" группы, чтобы не повторяться
    with open(FILENAME_VK, 'wt') as file:
    try:
    tmp = entries[0]['is_pinned']
    # Если первый пост - закрепленный, то сохраняем ID второго
    file.write(str(entries[1]['id']))
    logging.info('New last_id (VK) is {!s}'.format((entries[1]['id'])))
    except KeyError:
    file.write(str(entries[0]['id']))
    logging.info('New last_id (VK) is {!s}'.format((entries[0]['id'])))
    except Exception as ex:
    logging.error('Exception of type {!s} in check_new_post(): {!s}'.format(type(ex).__name__, str(ex)))
    pass
    logging.info('[VK] Finished scanning')
    return


    check_new_posts_vk()


    I think error in entries = feed['response'][1:]

    I tried to convert the dictionary to different types. It probably wasn't necessary. If anyone can help, I would be extremely grateful, I still don't really understand python myself.

    Continue reading...

Compartilhe esta Página