you don’t need to write the code completely, just show where to change or add something else, make the user, after selecting the case, no longer show the choice of the case at startup by checking the id if his id is from one case, if he wants to change the case, then enters the /edit command, which allows you to change the case and deletes its id from the file and transfers it to another from selection corps
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
def create_group_buttons(groups):
markup = InlineKeyboardMarkup()
rows = [groups[i:i + 3] for i in range(0, len(groups), 3)]
code
for row in rows:
buttons = [InlineKeyboardButton(text=group, callback_data=f"group:{group}") for group in row]
markup.row(*buttons)
return markup
def 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 "Группа не найдена."
code
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
async def save_user_id(selected_corp: str, user_id: int):
if selected_corp == "first_corpus":
id_file_path = r"C:\Users\Administrator\Desktop\id_klient1.txt"
elif selected_corp == "second_corpus":
id_file_path = r"C:\Users\Administrator\Desktop\id_klient2.txt"
id_set = set()
# Сохранение ID в файл
with open(id_file_path, "r") as f:
for line in f:
if line.strip():
id_set.add(int(line.strip()))
code
id_set.add(user_id)
with open(id_file_path, "w") as f:
for user_id in id_set:
f.write(str(user_id) + "\n")
@dp.callback_query_handler(lambda c: c.data in ['first_corpus', 'second_corpus'])
async def process_callback_corp_query(callback_query: CallbackQuery):
selected_corp = callback_query.data
# Дальнейшая обработка выбранного корпуса, например, сохранение в базу данных или использование в других функциях
await callback_query.answer(text=f"Выбран {selected_corp} корпус")
message = callback_query.message
user_id = message.from_user.id
await save_user_id(selected_corp, user_id)
@dp.message_handler(user_id=ADMIN_ID, 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
await bot.send_message(
chat_id=ADMIN_ID,
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
for user_id in user_ids:
if user_id != str(ADMIN_ID):
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,
text="Уведомление отправлено всем пользователям."
)
# Answer callback query
await bot.answer_callback_query(callback_query.id, text="Уведомление отправлено всем пользователям.")
@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.")
if name == 'main':
executor.start_polling(dp, skip_updates=True)
You can follow these steps to edit the code and achieve the mentioned requirements:
Add a new command '/edit' to handle the edit case, and use user states for id management.
python
from aiogram.contrib.middlewares.logging import LoggingMiddleware
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters import Command, Text
# ...
# Replace the previous handler with this new one
@dp.message_handler(Command("start"))
async def send_welcome(message: types.Message, state: FSMContext):
current_state = await state.get_state()
if current_state:
return
keyboard = InlineKeyboardMarkup()
keyboard.add(InlineKeyboardButton(text="Первый корпус", callback_data="first_corpus"))
keyboard.add(InlineKeyboardButton(text="Второй корпус", callback_data="second_corpus"))
await message.answer("Выберите корпус:", reply_markup=keyboard)
@dp.message_handler(Command("edit"))
async def change_case(message: types.Message, state: FSMContext):
current_state = await state.get_state()
if not current_state:
return
await state.finish()
keyboard = InlineKeyboardMarkup()
keyboard.add(InlineKeyboardButton(text="Первый корпус", callback_data="first_corpus"))
keyboard.add(InlineKeyboardButton(text="Второй корпус", callback_data="second_corpus"))
await message.answer("Выберите новый корпус:", reply_markup=keyboard)
Modify the save_user_id() and process_callback_corp_query() functions to save and load user_ids using FSMContext. Change the save_user_id() and process_callback_corp_query() in the following way:
Here, we save the user state when the user selects a corpus, and clear the state when they switch to a new corpus.
Modify the other functions with 'state' instead of hardcoded paths. For example, you can modify the 'process_subject' fonction like this:
python
@dp.message_handler()
async def process_subject(message: types.Message, state: FSMContext):
# ...
user_data = await state.get_data()
selected_corp = user_data.get("selected_corp") # Get saved corpus from the state
# ... Perform other operations
This way, you can use the user state selected_corp to track and update the user's selected corpus. Whenever the user wants to switch their case, they can enter the /edit command, and their corpus will be updated accordingly.