[LINE Messaging API] Create a BOT that connects with someone with Python

Random chat

You can connect with users at random while adding friends to this bot.

flow

    1. Connect with someone by pressing "NEXT" image.png
  1. You can disconnect by pressing "REMOVE" (* Unless you disconnect, you will continue to be connected) image.png

Source code

 randomchat
    |
    |_ config.py
    |
    |_ lineapp.py
    |
    |_ lineapphandl.py
    |
    |_ reply.py
    |
    |_ richmeny.py

Check and set your own channel ・ ** Channel access token ** ・ ** Channel Secret **

config.py


# LINE Messaging API
YOUR_CHANNEL_ACCESS_TOKEN = 'Channel access token'
YOUR_CHANNEL_SECRET = 'Channel secret'

# messages
NEXT = 'NEXT'
NOTNEXT = 'NO PARTICIPANT'
MATCHED = 'MATCHED'

REMOVE = 'REMOVE'

REMOVED = 'REMOVED'

FAILED = 'FAILED'
    1. Check if a rich menu exists (For details, see Create Rich Menu)
  1. When a message is received, the ** TextMessage method ** is called (For details, see Aum Return BOT)

lineapp.py


from flask import Flask, request, abort

from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage,
)
import config, lineapphandl, richmenu
import os


app = Flask(__name__)

YOUR_CHANNEL_SECRET = config.YOUR_CHANNEL_SECRET
YOUR_CHANNEL_ACCESS_TOKEN = config.YOUR_CHANNEL_ACCESS_TOKEN

line_bot_api = LineBotApi(YOUR_CHANNEL_ACCESS_TOKEN)
handler = WebhookHandler(YOUR_CHANNEL_SECRET)

# check for existing richmenu
rich_menu_list = line_bot_api.get_rich_menu_list()
if not rich_menu_list:
    result = richmenu.createRichmeu()
    if not result:
        reply.reply_message(event, config.FAILED)

@app.route("/callback", methods=['POST'])
def callback():
    # get X-Line-Signature header value
    signature = request.headers['X-Line-Signature']

    # get request body as text
    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)

    # handle webhook body
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        print("Invalid signature. Please check your channel access token/channel secret.")
        abort(400)

    return 'OK'


@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    lineapphandl.TextMessage(event)

if __name__ == '__main__':
    app.run()

** **

richmenu.py


from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    RichMenu, RichMenuSize, RichMenuArea, RichMenuBounds, MessageAction, PostbackTemplateAction
)
import randomchat.config


def initMenu(line_bot_api):
    result = False
    try:
        # define a new richmenu
        rich_menu_to_create = RichMenu(
            size = RichMenuSize(width=1200, height=405),
            selected = True,
            name = 'richmenu for randomchat',
            chat_bar_text = 'TAP HERE',
            areas=[
                RichMenuArea(
                    bounds=RichMenuBounds(x=0, y=0, width=480, height=405),
                    action=MessageAction(text='REMOVE')
                ),
                RichMenuArea(
                    bounds=RichMenuBounds(x=480, y=0, width=720, height=405),
                    action=MessageAction(text='NEXT')
                )
            ]
        )
        richMenuId = line_bot_api.create_rich_menu(rich_menu=rich_menu_to_create)

        # upload an image for rich menu
        image = 'richmenu.jpg'
        path = '/home/web/randomchat/' + image
        
        with open(path, 'rb') as f:
            line_bot_api.set_rich_menu_image(richMenuId, "image/jpeg", f)
        
        # set the default rich menu
        line_bot_api.set_default_rich_menu(richMenuId)

        result = True

    except Exception:
        result = False


    return result

** **

    1. User management process
  1. "NEXT" or "REMOVE" or message processing

lineapphandle.py


from flask import Flask, request, abort

from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage,
)
import config, reply
import random, copy

YOUR_CHANNEL_SECRET = config.YOUR_CHANNEL_SECRET
YOUR_CHANNEL_ACCESS_TOKEN = config.YOUR_CHANNEL_ACCESS_TOKEN

line_bot_api = LineBotApi(YOUR_CHANNEL_ACCESS_TOKEN)
handler = WebhookHandler(YOUR_CHANNEL_SECRET)

usersList = []
usersDic = {}

def TextMessage(event):
    userId = event.source.user_id
    message = event.message.text
    
    if not userId in usersList:
        usersList.append(userId)
        if not userId in usersDic.keys():
            usersDic[userId] = {}
            usersDic[userId]['toUserId'] = ''
    
    toUsersList = copy.copy(usersList)
    toUsersList.remove(userId)


    if message == config.NEXT:
        if not len(toUsersList) == 0:
            num = random.randint(0, int(len(toUsersList)-1))
            usersDic[userId] = toUsersList[num]
            toUserId = toUsersList[num]
            usersDic[toUserId] = userId

            # delete Id form list
            usersList.remove(userId)
            usersList.remove(toUserId)
            
            # reply
            message = TextSendMessage(text=config.MATCHED)
            reply.reply_message(event, message)
            reply.push_message(toUserId, message)

        else:
            message = TextSendMessage(text=config.NOTNEXT)
            reply.reply_message(event, message)

    elif message == config.REMOVE:
        usersList.remove(userId)
        toUserId = usersDic[userId]
        if userId in usersDic.values():
            pushMessage = TextSendMessage(text=config.REMOVED)
            reply.push_message(toUserId, pushMessage)
            usersDic[toUserId] = ''
        usersDic.pop(userId)
        
        message = TextSendMessage(text=message)
        reply.reply_message(event, message)

    else:
        if usersDic[userId] == '':
            message = TextSendMessage(text=message)
            reply.reply_message(event, message)

        else:
            toUserId = usersDic[userId]
            message = TextSendMessage(text=message)
            reply.push_message(toUserId, message)

** ** reply_message: Send the message to the user who sent it (see for details) push_message: Send a message to the specified user

reply.py


from flask import Flask, request, abort

from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage,
)
import config, lineapphandl


YOUR_CHANNEL_SECRET = config.YOUR_CHANNEL_SECRET
YOUR_CHANNEL_ACCESS_TOKEN = config.YOUR_CHANNEL_ACCESS_TOKEN

line_bot_api = LineBotApi(YOUR_CHANNEL_ACCESS_TOKEN)
handler = WebhookHandler(YOUR_CHANNEL_SECRET)


def reply_message(event, message):
    line_bot_api.reply_message(
        event.reply_token,
        message
    )

def push_message(toUserId, message):
    line_bot_api.push_message(
        toUserId,
        message
    )

Recommended Posts

[LINE Messaging API] Create a BOT that connects with someone with Python
[LINE Messaging API] Create parrot return BOT with Python
[Python] [LINE Bot] Create a parrot return LINE Bot
LINE BOT (Messaging API) development with API Gateway and Lambda (Python) [Part 2]
A script that makes it easy to create rich menus with the LINE Messaging API
LINE BOT with Python + AWS Lambda + API Gateway
Steps to create a Twitter bot with python
I made a LINE BOT with Python and Heroku
Create a directory with python
[Super easy] Let's make a LINE BOT with Python.
Create a discord bot that notifies unilaterally with python (use only requests and json)
I made a LINE BOT that returns parrots with Go
Create a machine learning app with ABEJA Platform + LINE Bot
Create a Mastodon bot with a function to automatically reply with Python
I made LINE-bot with Python + Flask + ngrok + LINE Messaging API
Create a Twitter BOT with the GoogleAppEngine SDK for Python
Tornado-Let's create a Web API that easily returns JSON with JSON
Create a web API that can deliver images with Django
I made a Chatbot using LINE Messaging API and Python
Create Awaitable with Python / C API
Create a virtual environment with Python!
Create a LINE Bot in Django
[Python] A story about making a LINE Bot with a practical manned function on its own without using Salesforce [Messaging API]
Made "Unofficial Apple Refurbished Product Introduction" BOT with LINE Messaging API (v2) + API Gateway + lambda (python)
[Python] I made a Line bot that randomly asks English words.
[Python / Django] Create a web API that responds in JSON format
Create REST API that returns the current time with Python3 + Falcon
I made a Chatbot using LINE Messaging API and Python (2) ~ Server ~
Create a Python function decorator with Class
[Python] A program that creates stairs with #
Automatically create Python API documentation with Sphinx
Build a blockchain with Python ① Create a class
[Python] Create a virtual environment with Anaconda
Let's create a free group with Python
Create a word frequency counter with Python 3.4
[Python] Create a LineBot that runs regularly
[Python] Quickly create an API with Flask
A typed world that begins with Python
Create a bot that boosts Twitter trends
Let's make a Twitter Bot with Python!
Create a BOT that can call images registered with Discord like pictograms
Create a Twitter BOT service with GAE / P + Tweepy + RIOT API! (Part 1)
Create a Twitter BOT service with GAE / P + Tweepy + RIOT API! (Part 2)
The story of making a university 100 yen breakfast LINE bot with Python
How to make an artificial intelligence LINE bot with Flask + LINE Messaging API
Python beginners decided to make a LINE bot with Flask (Flask rough commentary)
I tried to make "Sakurai-san" a LINE BOT with API Gateway + Lambda
I made a stamp substitute bot with line
Create a frame with transparent background with tkinter [Python]
Send a message to LINE with Python (LINE Notify)
Create test data like that with Python (Part 1)
Make a Twitter trend bot with heroku + Python
A nice nimporter that connects nim and python
Create a virtual environment with conda in Python
[Note] Create a one-line timezone class with python
You can easily create a GUI with Python
Create a python3 build environment with Sublime Text3
Create a color bar with Python + Qt (PySide)
I made a LINE Bot with Serverless Framework!
Python: Create a class that supports unpacked assignment
Create a decision tree from 0 with Python (1. Overview)