V
V
Vasily Volk2021-06-15 20:06:55
Python
Vasily Volk, 2021-06-15 20:06:55

Error when entering data for the bot and inline mode. How to fix?

Task exception was never retrieved future: this error pops up when executing a request in the telegram bot in inline mode.
Bottom line: there is a bot on aiogram that gives out a horoscope for today when you enter the username of the bot, something like @bot aries
code:

import re
from aiogram.types import InputTextMessageContent, InlineQuery, InlineQueryResultArticle
from aiogram.utils.emoji import emojize
from aiogram.utils.markdown import hbold

from groups.horo_parser import memory_of_horo
from loader import dp, bot
some_emoji = {
    'овен': 'aries',
    'телець': 'taurus',
    'близнюки': 'gemini',
    'рак': 'cancer',
    'лев': 'lion',
    'діва': 'virgo',
    'терези': 'libra',
    'скорпіон': 'scorpio',
    'стрілець': 'sagittarius',
    'козеріг': 'capricorn',
    'водолій': 'aquarius',
    'риби': 'pisces',
}
def parser():
    dict_of_site = memory_of_horo()
    return dict_of_site

@dp.inline_handler()
async def inline_echo(inline_query: InlineQuery):
    text = inline_query.query
    text = text.lower()
    pattern = re.compile(r"\w+")
    try:
        intermed_progress = re.match(pattern, text)
        some_var = intermed_progress.group()

    except AttributeError as ex:
        return

    dict_of_site = parser()
    result = str((await dict_of_site)[f'{some_var}'])
    result = result.replace("[", "")
    result = result.replace("]", "")
    result = result.replace("'", "")
    upper_text = text.upper()
    fin_res = hbold(upper_text)
    emojized = ''
    if some_var in some_emoji:
        emozi = some_emoji[f"{some_var}"]
        emojized = emojize(f":{emozi}:")
    ost_result = f"{fin_res}{emojized}\n{result}"
    input_content = InputTextMessageContent(ost_result)
    item = InlineQueryResultArticle(
        id=1,
        #??????
        title="Гороскоп на сьогодні",
        input_message_content=input_content,
    )
    await bot.answer_inline_query(inline_query.id, results=[item], cache_time=300)

and there is a parser for it
import requests
from bs4 import BeautifulSoup

from loader import schreduler

horo_ukr = ["овен", "телець", "близнюки", "рак", "лев", "діва", "терези", "скорпіон", "стрілець", "козеріг",
            "водолій", "риби"]
horo = ['aries', 'taurus', 'gemini', 'cancer', 'lion', 'virgo', 'libra', 'scorpio', 'sagittarius', 'capricorn',
        'aquarius', 'pisces']


def gg():
    dict_of_site = {}
    i = -1
    for items in horo:
        i += 1
        url = f'https://orakul.com/horoscope/astrologic/general/{items}/today.html'
        res = requests.get(url).text
        soup = BeautifulSoup(res, "lxml")
        page = soup.find('div', class_='horoBlock').find('p').text
        page = page.replace("\r", "")
        page = page.replace("\n", "")
        page = page.strip()
        dict_of_site[horo_ukr[i]] = [page]
    return dict_of_site

async def memory_of_horo():
    some_new_var = gg()
    return some_new_var

def some_new_job():
    scheduler.add_job(memory_of_horo, 'cron', day_of_week="mon-sun", hour=1, minute=0)

so
when you request a zodiac sign longer than 3 characters, the runtime suffers and the output does not occur.
but if you enter let's say @bot cancer, then the bot will give the result.
Where is the mistake?
thanks in advance for help
all error:
base_events.py [LINE:1707] #ERROR    [2021-06-15 15:24:18,928]  Task exception was never retrieved
future: <Task finished name='Task-18' coro=<Dispatcher._process_polling_updates() done, defined at /home/ubuntu/.local/lib/python3.8/site-packages/aiogram/dispatcher/dispatcher.py:380> exception=KeyError('козері')>
Traceback (most recent call last):
  File "/home/ubuntu/.local/lib/python3.8/site-packages/aiogram/dispatcher/dispatcher.py", line 388, in _process_polling_updates
    for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
  File "/home/ubuntu/.local/lib/python3.8/site-packages/aiogram/dispatcher/dispatcher.py", line 225, in process_updates
    return await asyncio.gather(*tasks)
  File "/home/ubuntu/.local/lib/python3.8/site-packages/aiogram/dispatcher/handler.py", line 117, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "/home/ubuntu/.local/lib/python3.8/site-packages/aiogram/dispatcher/dispatcher.py", line 263, in process_update
    return await self.inline_query_handlers.notify(update.inline_query)
  File "/home/ubuntu/.local/lib/python3.8/site-packages/aiogram/dispatcher/handler.py", line 117, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "/home/ubuntu/telegrambot/groups/horo.py", line 40, in inline_echo
    result = str((await dict_of_site)[f'{some_var}'])
KeyError: 'козері'

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
soremix, 2021-06-15
@VovkVasil

I don’t know what you are entering, but the error clearly says that you are sending the bot козері, although there is no such key in the dictionary

S
Stefan, 2021-06-15
@MEDIOFF

result = str((await dict_of_site)[f'{some_var}'])
What is it?
you have dict_of_site = parser()a simple dictionary, as I understand it, remove await

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question