API Gateway + LambdaでLINE Bot開発

こんにちは。katoです。

今回はAWSサービスを利用したLINE Botの開発を行っていきたいと思います。

 

概要

LINE BotはLINE Developersアカウントを所有していれば簡単に作成することが可能です。

今回はDeveloper Trialのプランを利用して、簡易的なLINE Botを作成します。

 

手順

LINE Developers

まず初めにLINE Developers側のセットアップを行います。

LINEのアカウントを所有している場合には、LINEアカウントを利用してLINE Developersを開始することが可能です。

LINEを起動し、「ホーム」→「設定」→「アカウント」を開き、「メールアドレス」と「パスワード」を設定します。

設定したメールアドレス宛に認証番号が届きますので、LINE側でこの番号を入力して登録を完了します。

LINE Developersにて開発を行っていきます。

下記URLにアクセスし、「ログイン」をクリックします。

 

https://developers.line.biz/ja/

 

「LINEアカウントでログイン」を選択し、先程設定したメールアドレスとパスワードでログインします。

開発者登録を求められるので適当に入力して次に進みます。

プロバイダーを作成します。
プロバイダー名を入力するのみなので好きな名前で作成して下さい。

次にチャネルを作成します。

今回はBotを作成するので「Messaging API」を選択し、チャネルを作成していきます。

設定は適宜入力していくのみなので簡単ですが、「line」といった文字がアプリ名に含まれるとエラーでチャネルが作成できないようので、ここだけ注意してください。

作成したチャネルを開き、設定を行っていきます。

「メッセージ送受信設定」の個所の設定が少しだけ必要です。

まず、「アクセストークン」にて「再発行」をクリックし、アクセストークンを発行します。

このアクセストークンはLambdaからLINEに対してメッセージを送る際に利用するので控えておきます。

次に、「Webhook送信」を「利用する」に設定します。

「Webhook URL」はAPI Gatewayのエンドポイントを指定するので、今は設定不要です。

その他の設定は任意となりますので、適宜用途などに合わせて設定してください。

 

AWS

ここからAWS側の設定に移っていきます。

まずLambda関数を作成します。

今回はPython 3.6にて関数の作成を行っています。

  1. import json
  2. import boto3
  3. import urllib
  4. import re
  5. import os
  6. def lambda_handler(event, context):
  7. print (event)
  8. url = "https://api.line.me/v2/bot/message/reply"
  9. method = "POST"
  10. headers = {
  11. 'Authorization': os.environ['CHANNEL_ACCESS_TOKEN'],
  12. 'Content-Type': 'application/json'
  13. }
  14. if (event['events'][0]['type'] == "postback"):
  15. if (event['events'][0]['postback']['data'] == "blog"):
  16. message = [
  17. {
  18. "type": "text",
  19. "text": "ブログをお探しします!",
  20. "quickReply": {
  21. "items": [
  22. {
  23. "type": "action",
  24. "action": {
  25. "type": "postback",
  26. "label": "おすすめ",
  27. "data": "Recommended",
  28. "displayText": "おすすめ"
  29. }
  30. },
  31. {
  32. "type": "action",
  33. "action": {
  34. "type": "postback",
  35. "label": "キーワード検索",
  36. "data": "keyword",
  37. "displayText": "キーワード検索"
  38. }
  39. }
  40. ]
  41. }
  42. }
  43. ]
  44. elif (event['events'][0]['postback']['data'] == "Recommended"):
  45. message = [
  46. {
  47. "type": "text",
  48. "text": "おすすめはこちら!"
  49. },
  50. {
  51. "type": "text",
  52. "text": "https://xp-cloud.jp/blog/news/"
  53. }
  54. ]
  55. elif (event['events'][0]['postback']['data'] == "service"):
  56. message = [
  57. {
  58. "type": "text",
  59. "text": "どのようなサービスをお探しでしょうか?",
  60. "quickReply": {
  61. "items": [
  62. {
  63. "type": "action",
  64. "action": {
  65. "type": "postback",
  66. "label": "AWS導入",
  67. "data": "AWS",
  68. "displayText": "AWS"
  69. }
  70. },
  71. {
  72. "type": "action",
  73. "action": {
  74. "type": "postback",
  75. "label": "Backup",
  76. "data": "Backup",
  77. "displayText": "Backup"
  78. }
  79. },
  80. {
  81. "type": "action",
  82. "action": {
  83. "type": "postback",
  84. "label": "AWS移行",
  85. "data": "Migration",
  86. "displayText": "Migration"
  87. }
  88. },
  89. {
  90. "type": "action",
  91. "action": {
  92. "type": "postback",
  93. "label": "アプリ開発",
  94. "data": "app",
  95. "displayText": "app"
  96. }
  97. },
  98. {
  99. "type": "action",
  100. "action": {
  101. "type": "postback",
  102. "label": "監視・運用",
  103. "data": "operation",
  104. "displayText": "operation"
  105. }
  106. },
  107. {
  108. "type": "action",
  109. "action": {
  110. "type": "postback",
  111. "label": "VPN・専用線",
  112. "data": "VPN",
  113. "displayText": "VPN"
  114. }
  115. },
  116. {
  117. "type": "action",
  118. "action": {
  119. "type": "postback",
  120. "label": "鳴子",
  121. "data": "NARUKO",
  122. "displayText": "NARUKO"
  123. }
  124. }
  125. ]
  126. }
  127. }
  128. ]
  129. elif (event['events'][0]['postback']['data'] == "AWS"):
  130. message = [
  131. {
  132. "type": "text",
  133. "text": "サービスサイトにご案内します!"
  134. },
  135. {
  136. "type": "text",
  137. "text": "https://xp-cloud.jp/service/#aws_consul"
  138. }
  139. ]
  140. elif (event['events'][0]['postback']['data'] == "Backup"):
  141. message = [
  142. {
  143. "type": "text",
  144. "text": "サービスサイトにご案内します!"
  145. },
  146. {
  147. "type": "text",
  148. "text": "https://xp-cloud.jp/service/#cloud"
  149. }
  150. ]
  151. elif (event['events'][0]['postback']['data'] == "Migration"):
  152. message = [
  153. {
  154. "type": "text",
  155. "text": "サービスサイトにご案内します!"
  156. },
  157. {
  158. "type": "text",
  159. "text": "https://xp-cloud.jp/service/#cloudmigration"
  160. }
  161. ]
  162. elif (event['events'][0]['postback']['data'] == "app"):
  163. message = [
  164. {
  165. "type": "text",
  166. "text": "サービスサイトにご案内します!"
  167. },
  168. {
  169. "type": "text",
  170. "text": "https://xp-cloud.jp/service/#application"
  171. }
  172. ]
  173. elif (event['events'][0]['postback']['data'] == "operation"):
  174. message = [
  175. {
  176. "type": "text",
  177. "text": "サービスサイトにご案内します!"
  178. },
  179. {
  180. "type": "text",
  181. "text": "https://xp-cloud.jp/service/#network"
  182. }
  183. ]
  184. elif (event['events'][0]['postback']['data'] == "VPN"):
  185. message = [
  186. {
  187. "type": "text",
  188. "text": "サービスサイトにご案内します!"
  189. },
  190. {
  191. "type": "text",
  192. "text": "https://xp-cloud.jp/service/#monitoring"
  193. }
  194. ]
  195. elif (event['events'][0]['postback']['data'] == "NARUKO"):
  196. message = [
  197. {
  198. "type": "text",
  199. "text": "サービスサイトにご案内します!"
  200. },
  201. {
  202. "type": "text",
  203. "text": "https://xp-cloud.jp/naruko/"
  204. }
  205. ]
  206. elif (event['events'][0]['postback']['data'] == "keyword"):
  207. message = [
  208. {
  209. "type": "text",
  210. "text": "「検索」の後にスペースを入れてキーワードを入力してください。\n\n例)検索 DynamoDB\n\nキーワードにスペースが含まれる場合にはAND検索となります。"
  211. }
  212. ]
  213. elif (event['events'][0]['type'] == "message"):
  214. if (event['events'][0]['message']['text'] == "案内"):
  215. message = [
  216. {
  217. "type": "text",
  218. "text": "こんにちは!ご用件をお伺いできますでしょうか?",
  219. "quickReply": {
  220. "items": [
  221. {
  222. "type": "action",
  223. "action": {
  224. "type": "postback",
  225. "label": "blog",
  226. "data": "blog",
  227. "displayText": "blog"
  228. }
  229. },
  230. {
  231. "type": "action",
  232. "action": {
  233. "type": "postback",
  234. "label": "service",
  235. "data": "service",
  236. "displayText": "service"
  237. }
  238. }
  239. ]
  240. }
  241. }
  242. ]
  243. elif (re.match("検索", event['events'][0]['message']['text'])):
  244. keywords = event['events'][0]['message']['text'].split()
  245. if (len(keywords) > 1):
  246. keywords.remove("検索")
  247. keyword = "+".join(keywords)
  248. result = "https://xp-cloud.jp/blog/?s=" + str(keyword)
  249. message = [
  250. {
  251. "type": "text",
  252. "text": "検索結果をご案内します。"
  253. },
  254. {
  255. "type": "text",
  256. "text": result
  257. }
  258. ]
  259. else:
  260. message = [
  261. {
  262. "type": "text",
  263. "text": "入力を正しく処理できませんでした。\n「検索」の後にスペースを入れてキーワードを入力してください。\n\n例)検索 DynamoDB"
  264. }
  265. ]
  266. elif (event['events'][0]['message']['text'] == "こんにちは"):
  267. message = [
  268. {
  269. "type": "text",
  270. "text": "こんにちは!"
  271. }
  272. ]
  273. else:
  274. message = [
  275. {
  276. "type": "text",
  277. "text": "ご利用の際には「案内」と入力してください。"
  278. }
  279. ]
  280. else:
  281. message = [
  282. {
  283. "type": "text",
  284. "text": "申し訳ございません。ご入力を正しく受け取ることができませんでした。お手数ですが再度ご入力いただけますでしょうか。"
  285. }
  286. ]
  287. params = {
  288. "replyToken": event['events'][0]['replyToken'],
  289. "messages": message
  290. }
  291. request = urllib.request.Request(url, json.dumps(params).encode("utf-8"), method=method, headers=headers)
  292. with urllib.request.urlopen(request) as res:
  293. body = res.read()
  294. return 0

 

サイト案内をするだけの簡単なBotとなっております。

今回は顧客入力のパターンマッチによって処理するBot機能は最小限に抑え、quickReplyと呼ばれる選択肢タイプのBotを作成しています。

LINE Botでは顧客入力とquickReplyでの入力でイベントが少し異なるので注意が必要です。

また、今回は顧客入力に応答するタイプのBotとなりますので、イベントに含まれる「replyToken」を利用してLINEに対してメッセージを返しています。

LINE連携部分以外は簡単なコードとなっているので、詳細は省略させていただきますが、前半に指定している「Authorization」の指定だけ注意してください。

「Authorization」にはLINEチャネル設定時に発行したアクセストークンを指定するのですが、そのままアクセストークンを指定しても正常に動きませんでした。

下記のようにアクセストークンの先頭に「Bearer  」を指定する必要があるようなので注意して下さい。

 

Bearer <アクセストークン>

 

Lambda関数の作成が完了したらAPI Gatewayを作成していきます。

一般的なLambda連携のPOSTメソッドを作成するのみなのです、手順は省略しますが、リソースの作成だけ少し注意してください。

リソースとして「/」を指定している場合には、LINEからのイベントが正しく送られてきません。

理由は不明ですが「/bot」といったように「/」以外のリソースを作成して、そこにPOSTメソッドを作成してあげる必要があります。

設定が完了したらAPIをデプロイします。

呼び出しURLを先程のLINE Developersの「Webhook URL」に指定すれば設定完了です。

 

動作確認

「案内」と入力することでquickReplyの選択肢が表示されます。

quickReply

 

後は案内に従って選択、入力を行います。

 

なお。顧客側の入力欄に選択した内容が表示されていますが、これはquickReplyの「displayText」を設定しているためです。

quickReplyの「displayText」

 

quickReplyの「displayText」

 

quickReplyではあらかじめ決められた内容しか設定できないため、顧客入力に応じて処理する場合には特定の文字を入力に含めるなどの対応が必要となります。

 

quickReply

 

まとめ

API GatewayとLambdaを利用したLINE Botの開発をご紹介しました。

LINE Botは簡単に開発することができますが、AWSと連携することでBotとしての機能をさらに拡張していくことが可能になるかと思います。

Amazon Rekognitionと連携した画像認識であったり、Amazon Personalizeと連携したユーザ個別のリアルタイムパーソナライゼーションなど、ユニークで実用的な機能をAWSサービスを利用して実現することが可能になります。

次回は他のAWSサービスも連携して、もう少し複雑なBotを作ってみたいと思います。

 

 

 

このブログの著者

 

 

アプリケーション開発バナー   AWS相談会