Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2025
24
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.80 KB | None | 0 0
  1. import sqlite3
  2. import time
  3. from datetime import datetime
  4. from telegram import Update, ReplyKeyboardMarkup
  5. from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext, ConversationHandler
  6.  
  7. # Database Setup
  8. conn = sqlite3.connect("quiz_bot.db", check_same_thread=False)
  9. cursor = conn.cursor()
  10. cursor.execute("""
  11. CREATE TABLE IF NOT EXISTS users (
  12. id INTEGER PRIMARY KEY,
  13. username TEXT,
  14. score REAL,
  15. last_played DATE
  16. )
  17. """)
  18. cursor.execute("""
  19. CREATE TABLE IF NOT EXISTS admins (
  20. id INTEGER PRIMARY KEY,
  21. password TEXT
  22. )
  23. """)
  24. cursor.execute("""
  25. CREATE TABLE IF NOT EXISTS questions (
  26. id INTEGER PRIMARY KEY,
  27. question TEXT,
  28. option1 TEXT,
  29. option2 TEXT,
  30. option3 TEXT,
  31. option4 TEXT,
  32. correct_option INTEGER
  33. )
  34. """)
  35. conn.commit()
  36.  
  37. # States for conversation handler
  38. ADMIN_AUTH, ADD_QUESTIONS, QUIZ_ACTIVE = range(3)
  39. admin_password = "securepassword"
  40. game_active = False
  41.  
  42. # Start Command
  43. def start(update: Update, context: CallbackContext) -> None:
  44. update.message.reply_text("Привет! Добро пожаловать в квиз-игру. Используйте /startgame, чтобы начать игру.")
  45.  
  46. # Admin Authentication
  47. def admin(update: Update, context: CallbackContext) -> int:
  48. update.message.reply_text("Введите пароль администратора:")
  49. return ADMIN_AUTH
  50.  
  51. def check_admin(update: Update, context: CallbackContext) -> int:
  52. if update.message.text == admin_password:
  53. update.message.reply_text("Аутентификация успешна! Используйте /questions, чтобы добавить вопросы.")
  54. return ConversationHandler.END
  55. else:
  56. update.message.reply_text("Неверный пароль. Попробуйте снова.")
  57. return ADMIN_AUTH
  58.  
  59. # Adding Questions
  60. def add_questions(update: Update, context: CallbackContext) -> int:
  61. update.message.reply_text("Введите вопрос и 4 варианта ответа через запятую, последний вариант - правильный.")
  62. return ADD_QUESTIONS
  63.  
  64. def save_question(update: Update, context: CallbackContext) -> int:
  65. try:
  66. question_data = update.message.text.split(",")
  67. if len(question_data) == 5:
  68. cursor.execute("INSERT INTO questions (question, option1, option2, option3, option4, correct_option) VALUES (?, ?, ?, ?, ?, ?)",
  69. question_data)
  70. conn.commit()
  71. update.message.reply_text("Вопрос добавлен!")
  72. else:
  73. update.message.reply_text("Ошибка! Введите вопрос правильно.")
  74. except Exception as e:
  75. update.message.reply_text(f"Ошибка: {e}")
  76. return ConversationHandler.END
  77.  
  78. # Start and Stop Game
  79.  
  80. def start_game(update: Update, context: CallbackContext) -> None:
  81. global game_active
  82. game_active = True
  83. update.message.reply_text("Игра началась! Отвечайте на вопросы.")
  84.  
  85. def stop_game(update: Update, context: CallbackContext) -> None:
  86. global game_active
  87. game_active = False
  88. update.message.reply_text("Игра завершена! Итоги будут подведены.")
  89.  
  90. # Quiz Handling
  91.  
  92. def play_quiz(update: Update, context: CallbackContext) -> None:
  93. if not game_active:
  94. update.message.reply_text("Сейчас нельзя играть. Дождитесь начала игры.")
  95. return
  96. cursor.execute("SELECT * FROM questions ORDER BY RANDOM() LIMIT 5")
  97. questions = cursor.fetchall()
  98. score = 0
  99. start_time = time.time()
  100.  
  101. for q in questions:
  102. question_text = f"{q[1]}\n1. {q[2]}\n2. {q[3]}\n3. {q[4]}\n4. {q[5]}"
  103. update.message.reply_text(question_text)
  104. response = context.bot.wait_for_message(chat_id=update.message.chat_id)
  105. if response.text.strip() == str(q[6]):
  106. score += 1
  107.  
  108. elapsed_time = time.time() - start_time
  109. final_score = round(score / elapsed_time, 2)
  110. cursor.execute("INSERT INTO users (username, score, last_played) VALUES (?, ?, ?) ON CONFLICT(id) DO UPDATE SET score=?, last_played=?",
  111. (update.message.chat.username, final_score, datetime.now(), final_score, datetime.now()))
  112. conn.commit()
  113. update.message.reply_text(f"Ваш результат: {final_score} очков!")
  114.  
  115. # Leaderboard
  116.  
  117. def leaderboard(update: Update, context: CallbackContext) -> None:
  118. cursor.execute("SELECT username, score FROM users ORDER BY score DESC LIMIT 10")
  119. leaders = cursor.fetchall()
  120. text = "🏆 Таблица лидеров: \n" + "\n".join([f"{i+1}. {user[0]} - {user[1]} очков" for i, user in enumerate(leaders)])
  121. update.message.reply_text(text)
  122.  
  123. # Main Bot Setup
  124.  
  125. def main():
  126. updater = Updater("YOUR_TELEGRAM_BOT_TOKEN")
  127. dp = updater.dispatcher
  128.  
  129. dp.add_handler(CommandHandler("start", start))
  130. dp.add_handler(CommandHandler("startgame", start_game))
  131. dp.add_handler(CommandHandler("stopgame", stop_game))
  132. dp.add_handler(CommandHandler("leaderboard", leaderboard))
  133.  
  134. dp.add_handler(ConversationHandler(
  135. entry_points=[CommandHandler("admin", admin)],
  136. states={ADMIN_AUTH: [MessageHandler(Filters.text & ~Filters.command, check_admin)]},
  137. fallbacks=[]
  138. ))
  139.  
  140. dp.add_handler(ConversationHandler(
  141. entry_points=[CommandHandler("questions", add_questions)],
  142. states={ADD_QUESTIONS: [MessageHandler(Filters.text & ~Filters.command, save_question)]},
  143. fallbacks=[]
  144. ))
  145.  
  146. dp.add_handler(MessageHandler(Filters.text & ~Filters.command, play_quiz))
  147.  
  148. updater.start_polling()
  149. updater.idle()
  150.  
  151. if __name__ == "__main__":
  152. main()
  153.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement