Last time, I made a parrot return bot, so apply it I made a bot that randomly asks English words.
Link of previous article https://qiita.com/takuya0125/items/36bdea94c249f592a59f
I will omit the operation method of Heroku and git.
I created the following files in the directory. ・main.py Main source for hitting Line messaging API and asking questions
・ High1.txt A text file that describes English words and their meanings in the first year high school course unit
・ Procfile ・ Requirements ・ Runtime (.Git in hidden file)
I will explain the contents of the main.py file. Since it is long, it is easier to understand if the files are separated, but they have been consolidated into one.
main.py
#Module import
from flask import Flask, request, abort
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
InvalidSignatureError
)
from linebot.models import (
MessageEvent, TextMessage, TextSendMessage,
)
import os
import re
import random
#high1.Read txt
source = 'high1.txt'
with open(source, encoding="utf-8_sig") as f:
data = f.read()
english_words = re.findall('[a-z]+', data) #Alphabet extraction
ja = re.findall('.*[Ah-Hmm].*', data) #Extraction of Japanese
words_dict = dict(zip(english_words, ja)) #Store each in a dictionary
answer =[] #Create a Japanese box of answers to words
#Questions with a list of words and meanings as 1 to 4 choices
def question():
question_word =random.choice(english_words)
correct_answer = words_dict[question_word]
meanings_copy = ja.copy() #Make a copy to extract the wrong choices
meanings_copy.remove(correct_answer)
wrong_answers = random.sample(meanings_copy, 3)
answer_options = [correct_answer] + wrong_answers
random.shuffle(answer_options) #Shuffle the answer
list =[] #Put the options to be asked in the box
for i in range(4):
x = '{}. {}'.format(i + 1, answer_options[i])
list.append(x)
res = re.findall(correct_answer, x)
if len(res) ==1:
answer_num = i+1
answer.append(answer_num)
question_message = ('problem:{}\n{}\n{}\n{}\n{}\nYour answer?'.format(question_word,list[0],list[1],list[2],list[3]))
return question_message #question_Return to message
This is the question for English words.
Next, we will link with the Line messaging API.
main.py
app = Flask(__name__)
app.debug = False
#Get environment variables
#Obtain and set the access token and Channel Secret set in LINE Developers.
YOUR_CHANNEL_ACCESS_TOKEN = os.environ["YOUR_CHANNEL_ACCESS_TOKEN"]
YOUR_CHANNEL_SECRET = os.environ["YOUR_CHANNEL_SECRET"]
line_bot_api = LineBotApi(YOUR_CHANNEL_ACCESS_TOKEN)
handler = WebhookHandler(YOUR_CHANNEL_SECRET)
Up to this point, the tokens and other settings have been set.
Next, the user's answer to the actual question is described.
main.py
@app.route("/callback", methods=['POST'])
def callback():
#Get the value for signature verification from the request header.
signature = request.headers['X-Line-Signature']
#Get the request body.
body = request.get_data(as_text=True)
app.logger.info("Request body: " + body)
# handle webhook body
try:
handler.handle(body, signature)
except InvalidSignatureError:
abort(400)
return 'OK'
@handler.add(MessageEvent, message=TextMessage) #Response to text file
def handle_message(event):
question_message = question() #Executing a question and registering it in a variable
text_pass = event.message.text #Register the received message in a variable
#If the user sends "a", "a", "0", the question will be asked.#
if text_pass == 'a' or text_pass =='Ah' or text_pass =='0':
line_bot_api.reply_message(
event.reply_token,
[TextSendMessage(text = question_message),])
elif int(text_pass) == int(answer[-2]): #If the number sent by the user is correct, reply
line_bot_api.reply_message(event.reply_token,
[TextSendMessage(text = 'Correct answer'),])
elif int(text_pass) != int(answer[-2]): #If the number sent by the user is incorrect, reply
line_bot_api.reply_message(event.reply_token,
[TextSendMessage(text = 'Incorrect answer'),
TextSendMessage(text = 'The correct answer is{}'.format(answer[-2]))],)
#Port number setting
if __name__ == "__main__":
# app.run()
port = int(os.getenv("PORT"))
app.run(host="0.0.0.0", port=port)
Up to this point, it will be linked with Line. It's a hassle to enter "a", "a", and "0" each time you ask a question. This time, we will continue to develop so far and improve it if there is an opportunity in the future.
The hurdles for cooperation with Line are not so high, Actually communicating with users seems to be quite a hurdle. In the future, we will increase and implement ideas that can increase the cooperation with the Line messaging API. Create user-friendly tools little by little.
March 5, 2020 Program revision int(answer[0])⇒int(answer[-2]) Get the penultimate list
How to make an English word bot
References ・ Ingenuity of reply message https://miyabi-lab.space/blog/21 Corresponding part TextSendMessage (text ='What is "'+ event.message.text +'"?') )
・ Create multiple reply messages https://engineering.linecorp.com/ja/blog/imezimatsupumetsuseziwoshi-tsutezhong-dian-nicheng-richi-renaibotsutowozuo-rimashita/ Corresponding part TextSendMessage (text ='If you send location information, I will tell you a list of stations that are open until the last train (* Emoji 1)'), TextSendMessage(text='line://nv/location'),
・ Functionalization and execution of English word questions https://shikasen-engineer.com/python_line_bot/ Corresponding part result = sc.getNews(word)
・ Others https://datacoach.me/data/engineering/python-linebot-talk/ https://keinumata.hatenablog.com/entry/2018/05/08/122348 https://myafu-python.com/line-basic-1/
Recommended Posts