/
plotoh
/
pub
Обзор
Документация
Войти
/
plotoh
/
pub
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
main.py
274 строки
12 KB
plotoh
upload files
24 дек 2024, 13:40
24 дек 2024, 13:40
6464473
Код
Авторство
О чём код?
import json from config import TELEGRAM_BOT_TOKEN from random import choice, randrange from string import ascii_lowercase, ascii_uppercase from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update from telegram.ext import ( ApplicationBuilder, CallbackQueryHandler, CommandHandler, ContextTypes, MessageHandler, filters, ) # Глобальные переменные для настроек пароля space = False digits = False symbols = False waiting_for_login_platform = False waiting_for_number = False password_length = 12 # Функция для начала взаимодействия с ботом async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: keyboard = [[InlineKeyboardButton("Меню", callback_data='menu')]] reply_markup = InlineKeyboardMarkup(keyboard) await update.message.reply_text('welcome') await menu(update, context) # Функция для отображения главного меню async def menu(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: query = update.callback_query if update.callback_query else None if query: await query.answer() keyboard = [ [InlineKeyboardButton("Генератор паролей", callback_data='button1')], [InlineKeyboardButton("Да | Нет", callback_data='button2')], [InlineKeyboardButton("Контроль финансов", callback_data='button3')], [InlineKeyboardButton("Контроль сна", callback_data='button4')], [InlineKeyboardButton("Напоминалка", callback_data='button5')] ] reply_markup = InlineKeyboardMarkup(keyboard) new_text = 'Выбери нужный функционал:' if query: if query.message.text != new_text or query.message.reply_markup != reply_markup: await query.edit_message_text(text=new_text, reply_markup=reply_markup) else: await update.message.reply_text(text=new_text, reply_markup=reply_markup) # Обработчик кнопок в меню async def button_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: query = update.callback_query await query.answer() if query.data == 'button1': await show_password_generator(update, context) elif query.data == 'button2': await show_yes_or_no(update, query) elif query.data == 'button3': await show_moneycontrol(update, query) elif query.data == 'button4': await show_sleepcontrol(update, query) elif query.data == 'button5': await show_reminder(update, query) # Генерация пароля def gen_password(n=12) -> str: chars = ascii_lowercase * 2 + ascii_uppercase if digits: chars += "0123456789" if symbols: chars += "!#*?@$%&,-.:;<>" password = [choice(chars) for _ in range(n)] if space: password[randrange(n)] = ' ' return ''.join(password) # Команда для генератора паролей async def generator_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: await show_password_generator(update, context) # Отображение генератора паролей async def show_password_generator(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: query = update.callback_query if update.callback_query else None if query: await query.answer() keyboard = [ [InlineKeyboardButton("Сгенерировать пароль", callback_data='generate')], [InlineKeyboardButton("Количество символов", callback_data='length')], [InlineKeyboardButton("Сохранить пароль", callback_data='save_pass')], [InlineKeyboardButton("Пробел" + (" ✅" if space else ""), callback_data='space_option')], [InlineKeyboardButton("Цифры" + (" ✅" if digits else ""), callback_data='digits_option')], [InlineKeyboardButton("Спец. символы" + (" ✅" if symbols else ""), callback_data='symbols_option')], [InlineKeyboardButton("Назад", callback_data='gen_back')] ] reply_markup = InlineKeyboardMarkup(keyboard) new_text = "Выбери опцию:" if query: if query.message.text != new_text or query.message.reply_markup != reply_markup: await query.edit_message_text(text=new_text, reply_markup=reply_markup) else: await update.message.reply_text(text=new_text, reply_markup=reply_markup) # Обработчик кнопок генератора паролей async def button_handler_for_password_generator(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: global space, digits, symbols, waiting_for_number, password_length, waiting_for_login_platform query = update.callback_query await query.answer() if query.data == 'space_option': space = not space elif query.data == 'digits_option': digits = not digits elif query.data == 'symbols_option': symbols = not symbols elif query.data == 'length': waiting_for_number = True await query.message.reply_text("Введи желаемую длину пароля") elif query.data == 'save_pass': waiting_for_login_platform = True await query.message.reply_text("Введи платформу и логин в формате: Платформа, Логин, Пароль (если нужно взять последний сгенерированный пароль, то введи 0)") elif query.data == 'generate': password = gen_password(n=password_length) await query.message.reply_text(password) elif query.data == 'gen_back': await menu(update, context) await show_password_generator(update, context) # Сохранение пароля async def saving_password(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: global waiting_for_login_platform if waiting_for_login_platform: try: platform, login, password_for_saving = update.message.text.split(', ') if password_for_saving == '0': password_for_saving = gen_password(n=password_length) credentials = { 'Платформа': platform, 'Логин': login, 'Пароль': password_for_saving } with open('passwords.txt', 'a+', encoding="utf-8") as file: json.dump(credentials, file, ensure_ascii=False) file.write('\n') waiting_for_login_platform = False await update.message.reply_text("Пароль записан.") except ValueError: await update.message.reply_text("Введи корректные данные.") else: await update.message.reply_text("Не ожидается ввода данных для сохранения пароля.") # Ввод длины пароля async def password_length_input(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: global waiting_for_number, password_length if waiting_for_number: try: password_length = int(update.message.text) waiting_for_number = False await update.message.reply_text(f"Теперь длина пароля {password_length} символов.") except ValueError: await update.message.reply_text("Пожалуйста, введи корректное число.") else: await update.message.reply_text("Бот не ожидает ввода длины пароля.") # Команда для отображения "Да | Нет" async def yes_or_no_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: query = update.callback_query await show_yes_or_no(update, query) # Отображение "Да | Нет" async def show_yes_or_no(update: Update, query): keyboard = [ [InlineKeyboardButton("Да | Нет", callback_data='yes_no')], [InlineKeyboardButton("Выбор из двух вариантов", callback_data='two_variants')], [InlineKeyboardButton("Назад", callback_data='yn_back')] ] reply_markup = InlineKeyboardMarkup(keyboard) if query: await query.edit_message_text(text="Да | Нет", reply_markup=reply_markup) else: await update.message.reply_text(text="Да | Нет", reply_markup=reply_markup) # Обработчик кнопок "Да | Нет" async def button_handler_for_yes_or_no(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: query = update.callback_query await query.answer() if query.data == 'yes_no': await query.message.reply_text(choice(['Да', 'Нет'])) elif query.data == 'two_variants': await query.message.reply_text(choice(['Первый вариант', 'Второй вариант'])) elif query.data == 'yn_back': await menu(update, context) # Команды для контроля финансов, сна и напоминалки async def moneycontrol_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: query = update.callback_query await show_moneycontrol(update, query) async def show_moneycontrol(update: Update, query): if query: await query.message.reply_text(text='Ты выбрал Контроль финансов. Его пока нет.') else: await update.message.reply_text(text='Ты выбрал Контроль финансов. Его пока нет.') async def sleepcontrol_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: query = update.callback_query await show_sleepcontrol(update, query) async def show_sleepcontrol(update: Update, query): if query: await query.message.reply_text(text='Ты выбрал Контроль сна. Его пока нет.') else: await update.message.reply_text(text='Ты выбрал Контроль сна. Его пока нет.') async def reminder_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: query = update.callback_query await show_reminder(update, query) async def show_reminder(update: Update, query): if query: await query.message.reply_text(text='Ты выбрал Напоминалку. Её пока нет.') else: await update.message.reply_text(text='Ты выбрал Напоминалку. Её пока нет.') # Основная функция для запуска бота def main(): app = ApplicationBuilder().token(TELEGRAM_BOT_TOKEN).build() command_handlers = [ CommandHandler("start", start), CommandHandler("generator", generator_command), CommandHandler("yes_or_no", yes_or_no_command), CommandHandler("moneycontrol", moneycontrol_command), CommandHandler("sleepcontrol", sleepcontrol_command), CommandHandler("reminder", reminder_command) ] callback_query_handlers = [ CallbackQueryHandler(menu, pattern='menu'), CallbackQueryHandler(button_handler, pattern='button1|button2|button3|button4|button5'), CallbackQueryHandler(button_handler_for_password_generator, pattern='space_option|digits_option|symbols_option|save_pass|length|generate|gen_back'), CallbackQueryHandler(button_handler_for_yes_or_no, pattern='yes_no|two_variants|yn_back') ] for handler in command_handlers: app.add_handler(handler) for handler in callback_query_handlers: app.add_handler(handler) app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, saving_password)) app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, password_length_input)) app.run_polling() if __name__ == '__main__': main()