W
W
WilayzJerti2021-04-25 16:54:39
Python
WilayzJerti, 2021-04-25 16:54:39

I am writing a telgram bot on the database, for site notifications. Because of what and why the error?

In the database, the user who subscribed to the newsletter is

import config
import logging
import asyncio
from datetime import datetime

from aiogram import Bot, Dispatcher, executor, types
from sqlighter import SQLighter

from stopgame import StopGame

# задаем уровень логов
logging.basicConfig(level=logging.INFO)

# инициализируем бота
bot = Bot(token=config.API_TOKEN)
dp = Dispatcher(bot)

# инициализируем соединение с БД
db = SQLighter('db.db')

# инициализируем парсер
sg = StopGame('lastkey.txt')

# Команда активации подписки
@dp.message_handler(commands=['subscribe'])
async def subscribe(message: types.Message):
  if(not db.subscriber_exists(message.from_user.id)):
    # если юзера нет в базе, добавляем его
    db.add_subscriber(message.from_user.id)
  else:
    # если он уже есть, то просто обновляем ему статус подписки
    db.update_subscription(message.from_user.id, True)
  
  await message.answer("Вы успешно подписались на рассылку!\nЖдите, скоро выйдут новые обзоры и вы узнаете о них первыми =)")

# Команда отписки
@dp.message_handler(commands=['unsubscribe'])
async def unsubscribe(message: types.Message):
  if(not db.subscriber_exists(message.from_user.id)):
    # если юзера нет в базе, добавляем его с неактивной подпиской (запоминаем)
    db.add_subscriber(message.from_user.id, False)
    await message.answer("Вы итак не подписаны.")
  else:
    # если он уже есть, то просто обновляем ему статус подписки
    db.update_subscription(message.from_user.id, False)
    await message.answer("Вы успешно отписаны от рассылки.")

# проверяем наличие новых игр и делаем рассылки
async def scheduled(wait_for):
  while True:
    await asyncio.sleep(wait_for)

    # проверяем наличие новых игр
    new_games = sg.new_games()

    if(new_games):
      # если игры есть, переворачиваем список и итерируем
      new_games.reverse()
      for ng in new_games:
        # парсим инфу о новой игре
        nfo = sg.game_info(ng)

        # получаем список подписчиков бота
        subscriptions = db.get_subscriptions()

        # отправляем всем новость
        with open(sg.download_image(nfo['image']), 'rb') as photo:
          for s in subscriptions:
            await bot.send_photo(
              s[1],
              photo,
              caption = nfo['title'] + "\n" + "Оценка: " + nfo['score'] + "\n" + nfo['excerpt'] + "\n\n" + nfo['link'],
              disable_notification = True
            )
        
        # обновляем ключ
        sg.update_lastkey(nfo['id'])

# запускаем лонг поллинг
if __name__ == '__main__':
  loop = asyncio.get_event_loop()
  loop.create_task(scheduled(10)) # поставим 10 секунд, в качестве теста
  executor.start_polling(dp, skip_updates=True)

The code works, but does not notify and says that there is no active chat
Here is the output:
INFO:aiogram:Bot: Руни [@wilayzRbot]
WARNING:aiogram:Updates were skipped successfully.
INFO:aiogram.dispatcher.dispatcher:Start polling.
ERROR:asyncio:Task exception was never retrieved
future: <Task finished name='Task-1' coro=<scheduled() done, defined at C:\Users\Fantom\Desktop\Runi\bot.py:49> exception=ChatNotFound('Chat not found')>
Traceback (most recent call last):
  File "C:\Users\Fantom\Desktop\Runi\bot.py", line 69, in scheduled
    await bot.send_photo(
  File "C:\Users\Fantom\AppData\Roaming\Python\Python39\site-packages\aiogram\bot\bot.py", line 482, in send_photo
    result = await self.request(api.Methods.SEND_PHOTO, payload, files)
  File "C:\Users\Fantom\AppData\Roaming\Python\Python39\site-packages\aiogram\bot\base.py", line 208, in request
    return await api.make_request(self.session, self.server, self.__token, method, data, files,
  File "C:\Users\Fantom\AppData\Roaming\Python\Python39\site-packages\aiogram\bot\api.py", line 140, in make_request
    return check_result(method, response.content_type, response.status, await response.text())
  File "C:\Users\Fantom\AppData\Roaming\Python\Python39\site-packages\aiogram\bot\api.py", line 115, in check_result
    exceptions.BadRequest.detect(description)
  File "C:\Users\Fantom\AppData\Roaming\Python\Python39\site-packages\aiogram\utils\exceptions.py", line 140, in detect
    raise err(cls.text or description)
aiogram.utils.exceptions.ChatNotFound: Chat not found

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yupiter7575, 2021-04-25
@yupiter7575

Chat not found. What is not clear?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question