[Python] I made a Line bot that randomly asks English words.

Introduction

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.

Directory structure

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)

Implementation

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.

Summary

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

reference

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

[Python] I made a Line bot that randomly asks English words.
I made a LINE BOT with Python and Heroku
I made a Line Bot that uses Python to retrieve unread Gmail emails!
[Python] I made a LINE Bot that detects faces and performs mosaic processing.
In Python, I made a LINE Bot that sends pollen information from location information.
I made a LINE BOT that returns parrots with Go
I made a stamp substitute bot with line
I made a LINE Bot with Serverless Framework!
I made a Mattermost bot with Python (+ Flask)
I made a Discord bot in Python that translates when it reacts
[AWS] I made a reminder BOT with LINE WORKS
I made a LINE BOT that returns a terrorist image using the Flickr API
I made a Twitter BOT with GAE (python) (with a reference)
I made a household account book bot with LINE Bot
I made a LINE Bot that sends recommended images every day on time
I made a VM that runs OpenCV for Python
[Python] I made a bot that tells me the current temperature when I enter a place name on LINE
I made a python text
I made a discord bot
I want to send a message from Python to LINE Bot
I made a Chatbot using LINE Messaging API and Python
[AWS] I made a reminder BOT with LINE WORKS (implementation)
I made a Line-bot using Python!
I made a wikipedia gacha bot
I made a fortune with Python.
I made a daemon with Python
[Python3] I made a decorator that declares undefined functions and methods.
I made a package that can compare morphological analyzers with Python
I made a Twitter bot that mutters Pokemon caught by #PokemonGO
I made a shuffle that can be reset (reverted) with Python
[LINE Messaging API] Create a BOT that connects with someone with Python
I made a slack bot that notifies me of the temperature
I made a library that adds docstring to a Python stub file.
I made a Chatbot using LINE Messaging API and Python (2) ~ Server ~
[python] I made a class that can write a file tree quickly
I made a payroll program in Python!
I made a Line bot that guesses the gender and age of a person from an image
I made a character counter with Python
[Python] [LINE Bot] Create a parrot return LINE Bot
I made a Hex map with Python
After studying Python3, I made a Slackbot
I made a roguelike game with Python
I made a simple blackjack with Python
I made a configuration file with Python
I made a neuron simulator with Python
[Python] I made a decorator that doesn't seem to have any use.
I made a web application in Python that converts Markdown to HTML
[Python] I made a utility that can access dict type like a path
I made a tool that makes decompression a little easier with CLI (Python3)
[IOS] I made a widget that displays Qiita trends in Pythonista3. [Python]
I made a module PyNanaco that can charge nanaco credit with python
I made a python dictionary file for Neocomplete
I made a competitive programming glossary with Python
I made a weather forecast bot-like with Python.
A memo that I wrote a quicksort in Python
I made a GUI application with Python + PyQt5
Create a LINE BOT with Minette for Python
I made a Twitter fujoshi blocker with Python ①
[Python] I made a Youtube Downloader with Tkinter.
I made a Caesar cryptographic program in Python.
I made a bin picking game with Python