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)
To implement the described behavior, you can add an additional table in SQLite to store the user's selected group and use this data later when the user returns to the bot.
First, let's create a helper function to connect to the SQLite database and create a table if it doesn't exist.
python
def connect_to_db():
conn = sqlite3.connect("user_groups.db")
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS user_groups (
user_id INTEGER PRIMARY KEY,
selected_group TEXT NOT NULL
)
""")
conn.commit()
return conn
Now update the function which handles group selection to save the user's choice in the SQLite table.
python
async def process_callback_group(callback_query: types.CallbackQuery):
user_id = callback_query.from_user.id
group = callback_query.data[6:]
conn = connect_to_db()
cursor = conn.cursor()
cursor.execute("""
INSERT OR REPLACE INTO user_groups (user_id, selected_group)
VALUES (?, ?)
""", (user_id, group))
conn.commit()
schedule = get_schedule1(file_path, group)
await bot.answer_callback_query(callback_query.id)
await bot.send_message(chat_id=user_id, text=f"Расписание для группы {group}:\n\n{schedule}")
Now, you can update the /start command handler to use the saved group in the SQLite database if it exists.