Напиши код для телеграм БОТА-ВИКТОРИНУ с ВОПРОСАМИ и КНОПКАМИ для TELEGRAM на PYTHON
- User
Напиши код для телеграм БОТА-ВИКТОРИНУ с ВОПРОСАМИ и КНОПКАМИ для TELEGRAM на PYTHON
- Assistant
Конечно! Вот пример кода для создания телеграм-бота-викторины с вопросами и кнопками на Python, используя библиотеку
python-telegram-bot:import random from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler from telegram import InlineKeyboardButton, InlineKeyboardMarkup # Список вопросов и ответов questions = [ { 'question': 'В каком году была основана Москва?', 'options': ['1147', '1492', '1666', '1789'], 'answer': 0 }, { 'question': 'Какое самое глубокое озеро в мире?', 'options': ['Онежское', 'Каспийское', 'Байкал', 'Верхнее'], 'answer': 2 }, { 'question': 'Какое количество планет в солнечной системе?', 'options': ['5', '7', '8', '9'], 'answer': 2 } ] # Функция для обработки команды /start def start(update, context): context.bot.send_message(chat_id=update.effective_chat.id, text='Добро пожаловать в игру "Викторина"! Ответьте на вопросы.') random_question(update, context) # Функция для выбора случайного вопроса def random_question(update, context): question = random.choice(questions) options = question['options'] answer_index = question['answer'] # Создаем кнопки для каждого варианта ответа keyboard = [[InlineKeyboardButton(option, callback_data=str(index))] for index, option in enumerate(options)] reply_markup = InlineKeyboardMarkup(keyboard) context.bot.send_message(chat_id=update.effective_chat.id, text=question['question'], reply_markup=reply_markup) # Записываем правильный ответ в контекст для проверки позже context.user_data['answer_index'] = answer_index # Функция для обработки выбора ответа def answer(update, context): selected_option = int(update.callback_query.data) answer_index = context.user_data['answer_index'] if selected_option == answer_index: context.bot.send_message(chat_id=update.effective_chat.id, text='Правильно! Выберите следующий вопрос:') else: context.bot.send_message(chat_id=update.effective_chat.id, text='Неправильно! Попробуйте еще раз.') return random_question(update, context) # Функция для обработки текстовых ответов def handle_text(update, context): context.bot.send_message(chat_id=update.effective_chat.id, text='Пожалуйста, выберите один из предложенных вариантов ответа.') # Создаем экземпляр Updater и регистрируем обработчики updater = Updater(token='TOKEN', use_context=True) dispatcher = updater.dispatcher dispatcher.add_handler(CommandHandler('start', start)) dispatcher.add_handler(CallbackQueryHandler(answer)) dispatcher.add_handler(MessageHandler(Filters.text, handle_text)) # Запускаем бота updater.start_polling()Примечание: не забудьте заменить
'TOKEN'на ваш токен бота, который можно получить у BotFather. - User
другой вариант кода
- Assistant
Конечно! Вот еще один вариант кода для телеграм-бота-викторины с вопросами и кнопками на Python, используя библиотеку
python-telegram-bot:import random from telegram.ext import Updater, CommandHandler, CallbackQueryHandler from telegram import InlineKeyboardButton, InlineKeyboardMarkup # Список вопросов и ответов questions = [ { 'question': 'В каком году была основана Москва?', 'options': ['1147', '1492', '1666', '1789'], 'answer': 0 }, { 'question': 'Какое самое глубокое озеро в мире?', 'options': ['Онежское', 'Каспийское', 'Байкал', 'Верхнее'], 'answer': 2 }, { 'question': 'Какое количество планет в солнечной системе?', 'options': ['5', '7', '8', '9'], 'answer': 2 } ] # Функция для обработки команды /start def start(update, context): context.bot.send_message(chat_id=update.effective_chat.id, text='Добро пожаловать в игру "Викторина"! Ответьте на вопросы.') random_question(update, context) # Функция для выбора случайного вопроса def random_question(update, context): question = random.choice(questions) options = question['options'] answer_index = question['answer'] # Создаем кнопки для каждого варианта ответа reply_markup = InlineKeyboardMarkup.from_column( [[InlineKeyboardButton(option, callback_data=str(index))] for index, option in enumerate(options)] ) context.bot.send_message(chat_id=update.effective_chat.id, text=question['question'], reply_markup=reply_markup) # Записываем правильный ответ в контекст для проверки позже context.user_data['answer_index'] = answer_index # Функция для обработки выбора ответа def answer(update, context): selected_option = int(update.callback_query.data) answer_index = context.user_data['answer_index'] if selected_option == answer_index: context.bot.send_message(chat_id=update.effective_chat.id, text='Правильно! Выберите следующий вопрос:') else: context.bot.send_message(chat_id=update.effective_chat.id, text='Неправильно! Попробуйте еще раз.') return random_question(update, context) # Создаем экземпляр Updater и регистрируем обработчики updater = Updater(token='TOKEN', use_context=True) dispatcher = updater.dispatcher dispatcher.add_handler(CommandHandler('start', start)) dispatcher.add_handler(CallbackQueryHandler(answer)) # Запускаем бота updater.start_polling()Примечание: также не забудьте заменить
'TOKEN'на ваш токен бота. Этот код имеет более компактную реализацию использованияInlineKeyboardMarkup.from_column()для создания кнопок.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.