-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlanguage_bot.py
More file actions
245 lines (166 loc) · 7.5 KB
/
language_bot.py
File metadata and controls
245 lines (166 loc) · 7.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=W0613, C0116
# type: ignore[union-attr]
# This program is dedicated to the public domain under the CC0 license.
"""
Simple Bot to quiz vocabulary.
First, a few handler functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is started and runs until we press Ctrl-C on the command line.
Usage:
Simple bot to quiz vocabulary
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""
import datetime
import logging
import os
import random
import string
from os.path import dirname, join
import toml
from dotenv import load_dotenv
from telegram import ReplyKeyboardMarkup, Update
from telegram.ext import (CallbackContext, CommandHandler, Filters, MessageHandler, Updater)
QUIZ_NAME_KEY = 'quiz_name'
QUESTIONS_KEY = 'questions'
QUESTION_NUM_KEY = 'question_num'
NUM_CORRECT_KEY = 'correct'
NUM_QUESTIONS = 5
# Enable logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
logger = logging.getLogger(__name__)
def send_greeting(update: Update, context: CallbackContext) -> None:
now = datetime.datetime.now()
if now.hour < 11:
update.message.reply_text("おはよう")
elif now.hour < 19:
update.message.reply_text("こんにちは")
else:
update.message.reply_text("こんばんは")
def choose_questions(question_set, num_questions):
random.shuffle(question_set)
chosen_questions = question_set[:num_questions]
for _idx, question in enumerate(chosen_questions):
question_type = random.choice(['japanese', 'english'])
question['question_type'] = question_type
if ';' in question[question_type]:
possible_questions = question[question_type].split(';')
question_text = random.choice(possible_questions)
question['question_text'] = question_text
else:
question['question_text'] = question[question_type]
if question_type == 'japanese':
question['answer_text'] = question['english']
else:
question['answer_text'] = question['japanese']
return chosen_questions
# Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error.
def start(update: Update, context: CallbackContext) -> None:
"""Send a message when the command /start is issued."""
send_greeting(update, context)
question_sets = [*questions.keys()]
# Perhaps the user has asked to start a new quiz
if QUIZ_NAME_KEY in context.user_data:
context.user_data.pop(QUIZ_NAME_KEY)
if len(question_sets) == 1:
start_quiz(question_sets[0], update, context)
else:
# Show the user the list of available question sets
quiz_keyboard = [[question_set] for question_set in question_sets]
quiz_markup = ReplyKeyboardMarkup(quiz_keyboard, one_time_keyboard=True)
update.message.reply_text("Choose the questions that you want to be tested on.", reply_markup=quiz_markup)
def start_quiz(name: str, update: Update, context: CallbackContext) -> None:
question_set = questions[name]
chosen_questions = choose_questions(question_set, NUM_QUESTIONS)
context.user_data[QUIZ_NAME_KEY] = name
context.user_data[QUESTIONS_KEY] = chosen_questions
context.user_data[QUESTION_NUM_KEY] = 0
context.user_data[NUM_CORRECT_KEY] = 0
update.message.reply_text("I will now ask you {} questions.".format(len(chosen_questions)))
ask_question(update, context)
def ask_question(update: Update, context: CallbackContext) -> None:
quiz_questions = context.user_data[QUESTIONS_KEY]
question_num = context.user_data[QUESTION_NUM_KEY]
question = quiz_questions[question_num]
update.message.reply_text(question['question_text'])
def help_command(update: Update, context: CallbackContext) -> None:
"""Send a message when the command /help is issued."""
update.message.reply_text('Help!')
def compare_text(text1, text2) -> bool:
cleaned_text1 = text1.translate(str.maketrans('', '', string.punctuation))
cleaned_text2 = text2.translate(str.maketrans('', '', string.punctuation))
return cleaned_text1.casefold() == cleaned_text2.casefold()
def check_answer(correct_answer, response) -> bool:
if ';' in correct_answer:
correct_answers = correct_answer.split(';')
for alternative_answer in correct_answers:
if compare_text(alternative_answer, response):
return True
return False
return compare_text(correct_answer, response)
def check_response(update: Update, context: CallbackContext) -> None:
"""Check the user's response."""
if QUIZ_NAME_KEY not in context.user_data:
start_quiz(update.message.text, update, context)
return
question_num = context.user_data[QUESTION_NUM_KEY]
quiz_questions = context.user_data[QUESTIONS_KEY]
question = quiz_questions[question_num]
answer_text = question['answer_text']
is_correct = check_answer(answer_text, update.message.text)
if is_correct:
update.message.reply_text('Correct!')
context.user_data[NUM_CORRECT_KEY] += 1
# TODO tell the alternative answer(s) to the user
if ';' in answer_text:
update.message.reply_text('Do not forget that there are alternative answers!')
else:
# TODO format the text properly if there are multiple correct answers
update.message.reply_text('The correct answer was "{0}".'.format(answer_text))
question_num = question_num + 1
context.user_data[QUESTION_NUM_KEY] = question_num
if question_num == len(quiz_questions):
end_quiz(update, context)
else:
ask_question(update, context)
def end_quiz(update: Update, context: CallbackContext) -> None:
correct = context.user_data[NUM_CORRECT_KEY]
quiz_questions = context.user_data[QUESTIONS_KEY]
update.message.reply_text('You scored {} out of {}.'.format(correct, len(quiz_questions)))
update.message.reply_text('To try again, just /start.')
if QUIZ_NAME_KEY in context.user_data:
context.user_data.pop(QUIZ_NAME_KEY)
def load_questions():
global questions
questions = toml.load("genki1.toml")
def main():
load_questions()
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
# Get variables from the environment
BOT_TOKEN = os.getenv('BOT_TOKEN')
"""Start the bot."""
# Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater(BOT_TOKEN, use_context=True)
# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
# on different commands - answer in Telegram
dispatcher.add_handler(CommandHandler("start", start))
dispatcher.add_handler(CommandHandler("help", help_command))
# on noncommand i.e message - echo the message on Telegram
dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, check_response))
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()