исправь ошибку ERROR:asyncio:Task exception was never retrieved future: <Task finished…
- User
исправь ошибку ERROR:asyncio:Task exception was never retrieved future: <Task finished name='Task-19' coro=<Dispatcher._process_polling_updates() done, defined at C:\Users\Administrator\PycharmProjects\AKOTiB\venv\Lib\site-packages\aiogram\dispatcher\dispatcher.py:407> exception=ChatNotFound('Chat not found')> Traceback (most recent call last): File "C:\Users\Administrator\PycharmProjects\AKOTiB\venv\Lib\site-packages\aiogram\dispatcher\dispatcher.py", line 415, in _process_polling_updates for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\PycharmProjects\AKOTiB\venv\Lib\site-packages\aiogram\dispatcher\dispatcher.py", line 235, in process_updates return await asyncio.gather(*tasks) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\PycharmProjects\AKOTiB\venv\Lib\site-packages\aiogram\dispatcher\handler.py", line 117, in notify response = await handler_obj.handler(*args, **partial_data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\PycharmProjects\AKOTiB\venv\Lib\site-packages\aiogram\dispatcher\dispatcher.py", line 256, in process_update return await self.message_handlers.notify(update.message) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\PycharmProjects\AKOTiB\venv\Lib\site-packages\aiogram\dispatcher\handler.py", line 117, in notify response = await handler_obj.handler(*args, **partial_data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\Desktop\AKOTiB.py", line 275, in handle_file await bot.send_message( File "C:\Users\Administrator\PycharmProjects\AKOTiB\venv\Lib\site-packages\aiogram\bot\bot.py", line 346, in send_message result = await self.request(api.Methods.SEND_MESSAGE, payload) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\PycharmProjects\AKOTiB\venv\Lib\site-packages\aiogram\bot\base.py", line 236, in request return await api.make_request(await self.get_session(), self.server, self.__token, method, data, files, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\PycharmProjects\AKOTiB\venv\Lib\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\Administrator\PycharmProjects\AKOTiB\venv\Lib\site-packages\aiogram\bot\api.py", line 115, in check_result exceptions.BadRequest.detect(description) File "C:\Users\Administrator\PycharmProjects\AKOTiB\venv\Lib\site-packages\aiogram\utils\exceptions.py", line 140, in detect raise err(cls.text or description) aiogram.utils.exceptions.ChatNotFound: Chat not found вот код import logging import pandas as pd import re import io import asyncio import sqlite3 from aiogram import Bot, Dispatcher, types from aiogram.contrib.middlewares.logging import LoggingMiddleware from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup from aiogram.utils import executor from aiogram.types import CallbackQuery from typing import Optional from aiogram import types
API_TOKEN = '6084658919:AAGcYQUODSWD8g0LJ8Ina6FcRZTLxg92s2w'
logging.basicConfig(level=logging.INFO)
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot) dp.middleware.setup(LoggingMiddleware())
ADMIN_ID_1 = 6068499378 ADMIN_ID_2 = 587944057
file_dir = r'C:\Users\Administrator\Desktop\1' file_path = None
teachers_file_path = r"C:\Users\Administrator\Desktop\kollektiv.xlsx" id_file_path = r"C:\Users\Administrator\Desktop\id_klient.txt"
def create_group_buttons(group_list, has_change_button=True): markup = InlineKeyboardMarkup() rows = [group_list[i:i + 3] for i in range(0, len(group_list), 3)]
codefor row in rows: buttons = [InlineKeyboardButton(text=group, callback_data=f"group:{group}") for group in row] markup.row(*buttons) return markupdef get_schedule1(filepath, group): if group == "АОЭ/21": col = 1 elif group == "АОКС/21": col = 2 elif group == "АОИС1/21": col = 3 elif group == "АОРТ/21": col = 4 elif group == "АОМЦ/21": col = 5 elif group == "АОМЦ3/22": col = 6 elif group == "АОЮ1/21": col = 7 elif group == "АОЮ2/21": col = 8 elif group == "АОЭ/20": col = 1 elif group == "АОМТ/20": col = 2 elif group == "АОКС/20": col = 3 elif group == "АОРТ/20": col = 4 elif group == "АОМЦ/20": col = 5 elif group == "АОПИ/20": col = 6 elif group == "АОИС2/21": col = 7 elif group == "АОЮ1/20": col = 8 elif group == "АОЮ2/20": col = 9 elif group == "АОЭ/19": col = 10 elif group == "АОКС/19": col = 11 elif group == "АОМТ/19": col = 12 elif group == "АОРТ/19": col = 13 elif group == "АОПИ/19": col = 14 elif group == "АОМЦ/19": col = 15 else: return "Группа не найдена."
codeif file_path is None: return "Расписание отсутсвует." df = pd.read_excel(file_path, sheet_name='Лист1', header=None, engine='xlrd') schedule = "" if group in ["АОЭ/20", "АОМТ/20", "АОКС/20", "АОРТ/20", "АОМЦ/20", "АОПИ/20", "АОИС2/21", "АОЮ1/20", "АОЮ2/20", "АОЭ/19", "АОКС/19", "АОМТ/19", "АОРТ/19", "АОПИ/19", "АОМЦ/19"]: lessons_range = range(25, 40, 3) else: lessons_range = range(6, 21, 3) for i in lessons_range: lessons = "\n".join(df.iloc[i:i + 3, col].dropna().astype(str).tolist()) schedule += f"Урок {int((i - lessons_range.start) / 3) + 1}:\n{lessons}\n\n" return scheduledef get_teacher(teachers_filepath, query): teachers_df = pd.read_excel(teachers_filepath, sheet_name='Лист1', header=None, usecols=[0, 8], engine='openpyxl')
code# Ищем совпадения с помощью регулярного выражения query_regex = re.compile(r'\b{}\b'.format(query), re.IGNORECASE) teachers = teachers_df[teachers_df[0].apply(lambda x: bool(query_regex.search(str(x)))) | teachers_df[8].apply(lambda x: bool(query_regex.search(str(x))))][0] if teachers.empty: return "Преподаватели не найдены." else: return "\n".join(teachers)@dp.message_handler(commands=["start"]) async def start_handler(message: types.Message) -> None: user_id = message.from_user.id selected_corpus = await get_selected_corpus(user_id)
codeif selected_corpus: await send_group_selection_keyboard(message, selected_corpus) else: await send_corpus_selection_keyboard(message)async def get_selected_corpus(user_id: int) -> Optional[str]: # function body
codeid_file_paths = [ r"C:\Users\Administrator\Desktop\id_klient1.txt", r"C:\Users\Administrator\Desktop\id_klient2.txt" ] for file_path in id_file_paths: with open(file_path, "r") as f: for line in f: if line.strip() and int(line.strip()) == user_id: return "first_corpus" if file_path == id_file_paths[0] else "second_corpus" return Noneasync def send_corpus_selection_keyboard(message: types.Message) -> None: keyboard = InlineKeyboardMarkup() keyboard.add(InlineKeyboardButton(text="Первый корпус", callback_data="first_corpus")) keyboard.add(InlineKeyboardButton(text="Второй корпус", callback_data="second_corpus")) await message.answer("Выберите корпус:", reply_markup=keyboard)
admin_groups = { ADMIN_ID_1: ["second_corpus"], ADMIN_ID_2: ["first_corpus"] }
async def send_group_selection_keyboard(message: types.Message, corpus_name: str, callback_query: types.CallbackQuery = None) -> None: if corpus_name == "first_corpus": group_list = ["АОЭ/21", "АОКС/21", "АОИС1/21", "АОРТ/21", "АОМЦ/21", "АОМЦ3/22", "АОЮ1/21", "АОЮ2/21", "АОЭ/20", "АОМТ/20", "АОКС/20", "АОРТ/20", "АОМЦ/20", "АОПИ/20", "АОИС2/21", "АОЮ1/20", "АОЮ2/20", "АОЭ/19", "АОКС/19", "АОМТ/19", "АОРТ/19", "АОПИ/19", "АОМЦ/19"] if message.from_user.id != ADMIN_ID_1: has_change_button = not corpus_name in admin_groups.get(ADMIN_ID_1, []) markup = create_group_buttons(group_list, has_change_button=has_change_button) else: markup = create_group_buttons(group_list, has_change_button=False)
codeelif corpus_name == "second_corpus": group_list = ["АОЭ/34", "АОКС/35", "АОИС1/36"] if message.from_user.id != ADMIN_ID_2: has_change_button = not corpus_name in admin_groups.get(ADMIN_ID_2, []) markup = create_group_buttons(group_list, has_change_button=has_change_button) else: markup = create_group_buttons(group_list, has_change_button=False) else: group_list = [] markup = create_group_buttons(group_list) if message.from_user.id in [ADMIN_ID_1, ADMIN_ID_2]: has_change_button = not corpus_name in admin_groups.get(message.from_user.id, []) if has_change_button: markup.add(InlineKeyboardButton(text="🔧Изменить расписание", callback_data="change_path")) await message.reply("📃Выберите группу", reply_markup=markup)async def remove_user_id_from_files(user_id: int) -> None: id_file_paths = [ r"C:\Users\Administrator\Desktop\id_klient1.txt", r"C:\Users\Administrator\Desktop\id_klient2.txt" ]
codefor file_path in id_file_paths: id_set = set() with open(file_path, "r") as f: for line in f: if line.strip(): id_set.add(int(line.strip())) if user_id in id_set: id_set.remove(user_id) with open(file_path, "w") as f: for uid in id_set: f.write(str(uid) + "\n")@dp.callback_query_handler(lambda c: c.data in {"first_corpus", "second_corpus"}) async def corpus_selection_handler(callback_query: types.CallbackQuery) -> None: user_id = callback_query.from_user.id selected_corpus = callback_query.data
codewith open(r"C:\Users\Administrator\Desktop\id_klient1.txt", "a") as f1, \ open(r"C:\Users\Administrator\Desktop\id_klient2.txt", "a") as f2: if selected_corpus == "first_corpus": f1.write(str(user_id) + "\n") else: f2.write(str(user_id) + "\n") await send_group_selection_keyboard(callback_query.message, selected_corpus)@dp.callback_query_handler(lambda c: c.data.startswith('group:')) async def process_callback_group(callback_query: types.CallbackQuery): global file_path group = callback_query.data[6:] schedule = get_schedule1(file_path, group) await bot.answer_callback_query(callback_query.id) await bot.send_message(chat_id=callback_query.from_user.id, text=f"Расписание для группы {group}:\n\n{schedule}")
@dp.callback_query_handler(lambda c: c.data == "change_path", user_id=ADMIN_ID_1) async def process_change_path(callback_query: types.CallbackQuery): await bot.answer_callback_query(callback_query.id) await bot.send_message(chat_id=callback_query.from_user.id, text="Отправьте новое расписание:")
@dp.message_handler(user_id=[ADMIN_ID_1, ADMIN_ID_2], content_types=['document']) async def handle_file(message: types.Message): global file_path
code# Save file to disk file_name = message.document.file_name file_path = f"{file_dir}/{file_name}" await message.document.download(file_path) # Inform user about successful save await message.answer(f"Файл '{file_name}' успешно сохранен.") # Create inline button for sending notifications to all users send_notification_button = InlineKeyboardButton( text="Отправить уведомление", callback_data="send_notification" ) inline_keyboard = InlineKeyboardMarkup().add(send_notification_button) # Send message with inline button to admin # Send message with inline button to both admins await bot.send_message( chat_id=[ADMIN_ID_1, ADMIN_ID_2], text="Файл успешно загружен. Хотите отправить уведомление о новом расписании всем пользователям?", reply_markup=inline_keyboard )@dp.callback_query_handler(lambda callback_query: True) async def process_callback_send_notification(callback_query: types.CallbackQuery): # Load list of user IDs to send notification to with open(id_file_path, "r") as f: user_ids = [line.strip() for line in f]
code# Send notification to each user, except the admin # Send notification to each user, except the admins for user_id in user_ids: if user_id != str(ADMIN_ID_1) and user_id != str(ADMIN_ID_2): try: await bot.send_message( chat_id=user_id, text="Появилось новое расписание!", ) except: pass # Send notification to admin that notifications have been sent await bot.send_message( chat_id=ADMIN_ID_1, text="Уведомление отправлено всем пользователям." ) # Answer callback query await bot.answer_callback_query(callback_query.id, text="Уведомление отправлено всем пользователям.")@dp.message_handler(commands=["edit"]) async def edit_handler(message: types.Message) -> None: user_id = message.from_user.id selected_corpus = await get_selected_corpus(user_id)
codeif selected_corpus: await remove_user_id_from_files(user_id) await send_corpus_selection_keyboard(message) else: await message.answer("Вы еще не выбрали корпус. Используйте команду /start для начала.")@dp.message_handler(commands=['teacher']) async def send_teacher_info(message: types.Message): await message.reply("Напиши предмет, или (фамилию, имя, отчество), чтобы получить полностью ФИО преподавателя.")
@dp.message_handler(lambda message: message.text.startswith('/')) async def handle_unsupported_command(message: types.Message): await message.reply("Команда не поддерживается. Используйте /start или /teacher.")
@dp.message_handler() async def process_subject(message: types.Message): subject = message.text.strip() teacher = get_teacher(teachers_file_path, subject) await message.reply(f"🔍Поиск -- {subject}: {teacher}")
if name == 'main': executor.start_polling(dp, skip_updates=True)
- Assistant
Судя по вашему коду и выводу ошибки, эта ошибка возникает потому, что бот пытается отправить сообщение пользователю, но по какой-то причине не может найти этот чат. Вероятно, пользователь заблокировал бота или удалил чат с ботом.
Чтобы обработать ошибку в вашем коде, вы можете использовать
tryиexcept, чтобы перехватитьChatNotFoundисключение при отправке сообщения админу или пользователям.Вот как вы можете изменить функцию
process_callback_send_notification, чтобы обрабатывать это исключение:pythonfrom aiogram.utils.exceptions import ChatNotFound @dp.callback_query_handler(lambda callback_query: True) async def process_callback_send_notification(callback_query: types.CallbackQuery): # Load list of user IDs to send notification to with open(id_file_path, "r") as f: user_ids = [line.strip() for line in f] # Send notification to each user, except the admin # Send notification to each user, except the admins for user_id in user_ids: if user_id != str(ADMIN_ID_1) and user_id != str(ADMIN_ID_2): try: await bot.send_message( chat_id=user_id, text="Появилось новое расписание!", ) except ChatNotFound: pass # Send notification to admin that notifications have been sent try: await bot.send_message( chat_id=ADMIN_ID_1, text="Уведомление отправлено всем пользователям." ) except ChatNotFound: pass # Answer callback query await bot.answer_callback_query(callback_query.id, text="Уведомление отправлено всем пользователям.")Теперь, если возникает ошибка
ChatNotFound, ваш бот будет просто проигнорировать её и продолжить отправку сообщений другим пользователям. Это должно решить вашу проблему. Тем не менее, убедитесь, что вы тщательно протестируете своего бота, чтобы убедиться, что все работает как ожидается.