11
3

More than 3 years have passed since last update.

Serverless Framework でじゃんけんのLINEbot を作る

Last updated at Posted at 2021-07-24

概要

Line bot上でじゃんけんをできるようにしました。早い話が下記動画です。
RPReplay_Final1627130638.gif

アジェンダ

  1. 実装
  2. リッチメニューの作成
  3. デプロイ・実行
  4. 備考

1. 実装

ディレクトリ構成
~/develop/study/linebot $ tree ./jankenbot -I node_modules 
./jankenbot
├── janken.js
├── package.json
├── serverless.yml
└── yarn.lock
serverless.yml
service: jankenbot

frameworkVersion: '2'

provider:
  name: aws
  runtime: nodejs12.x
  lambdaHashingVersion: 20201221
  stage: dev
  region: ap-northeast-1

plugins:
 - serverless-offline

functions:
  lineWebhook:
    handler: janken.webhook
    events:
      - http:
          path: janken/webhook
          method: post
janken.js
'use strict';

// パッケージのインストール
const line = require('@line/bot-sdk');

// LINEアクセストークンの設定
const config = {
  channelAccessToken: 'アクセストークン',
  channelSecret: 'シークレットキー',
};

// インスタンス化
const client = new line.Client(config);

exports.webhook = async (event, context) => {

  /* リクエストボディ*/
  const body = JSON.parse(event.body)
  /* Lineのevent情報*/
  const response = body.events[0]
  /* ユーザの出した手を取得*/
  const userHand = response.message.text
  /* コンピュータの出した手を取得 */
  const cpHand = getCpHand()

  let message = hantei(userHand, cpHand)
  /* メッセージ送信のために必要な情報 */
  const replyToken = response.replyToken
  console.log('replyToken:' + replyToken)
  const post = {
    type: 'text',
    text: message,
  }

  try {
    await client.replyMessage(replyToken, post)
  } catch (err) {
    console.log(err)
  }
};

/**
 * コンピュータの手を決定します。
 * @return {string} cpHand - コンピュータの手
 */
 function getCpHand(){
  /**ランダム数値を取得(範囲:0~2) */
  let num = Math.floor(Math.random() * 3)
  let cpHand = ''
  if(num ==0){
    cpHand = 'グー'
  }else if(num ==1){
    cpHand = 'チョキ'
  }else{
    cpHand = 'パー'
  }
  return cpHand
}


/**
 * じゃんけんの勝ち負けを判定します。
 * @param {string} userHand - ユーザの出した手
 * @param {string} cpHand - コンピュータの出した手
 * @return {string} - message 判定結果
 */
//TODO ロジックが美しくない。数学的に処理する方法を後日の記事にする。
function hantei(userHand, cpHand){
  let message = ''

  if(userHand == 'グー'){
    if(cpHand == 'グー'){
      message = 'あいこです。(あなた:'+userHand + '、CP:'+ cpHand +')'
    }else if(cpHand == 'チョキ'){
      message = 'あなたの勝ちです。(あなた:'+userHand + '、CP:'+ cpHand +')'
    }else{
      message = 'あなたの負けです。(あなた:'+userHand + '、CP:'+ cpHand +')'
    }
  }else if(userHand == 'チョキ'){
    if(cpHand == 'チョキ'){
      message = 'あいこです。(あなた:'+userHand + '、CP:'+ cpHand +')'
    }else if(cpHand == 'パー'){
      message = 'あなたの勝ちです。(あなた:'+userHand + '、CP:'+ cpHand +')'
    }else{
      message = 'あなたの負けです。(あなた:'+userHand + '、CP:'+ cpHand +')'
    }
  }else{
    if(cpHand == 'パー'){
      message = 'あいこです。(あなた:'+userHand + '、CP:'+ cpHand +')'
    }else if(cpHand == 'グー'){
      message = 'あなたの勝ちです。(あなた:'+userHand + '、CP:'+ cpHand +')'
    }else{
      message = 'あなたの負けです。(あなた:'+userHand + '、CP:'+ cpHand +')'
    }
  }
  return message
}

2. リッチメニューの作成

Linebotでリッチメニューを作成します。えっ、リッチメニューって何って思った人はリンクを参考にしてね。
まぁ、簡単に言うと、下記画像を作成します。
IMG_1415.jpeg

作り方は省略しますが、下記内容が作れていればOKです。
スクリーンショット 2021-07-24 22.09.55.png

3 デプロイ・実行

デプロイ
~/develop/study/linebot/jankenbot $ serverless deploy
Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service jankenbot.zip file to S3 (4.53 MB)...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
.........................
Serverless: Stack update finished...
Service Information
service: jankenbot
stage: dev
region: ap-northeast-1
stack: jankenbot-dev
resources: 12
api keys:
  None
endpoints:
  POST - https://URL/dev/janken/webhook 
functions:
  lineWebhook: jankenbot-dev-lineWebhook
layers:
  None
Serverless: Removing old service artifacts from S3...

webhook用のURLをLine botに追記すれば稼動します!!

4. 備考

じゃんけんの判定ロジックが美しくないですよね。次回の記事では数学的に処理したロジックを紹介します。

11
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
3