Skip to content

Instantly share code, notes, and snippets.

@taketakekaho
Created June 4, 2021 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taketakekaho/5db119356d76fab9d65c9530e40dd18f to your computer and use it in GitHub Desktop.
Save taketakekaho/5db119356d76fab9d65c9530e40dd18f to your computer and use it in GitHub Desktop.
2021/6/5 Amazon Lex はじめてのLINEチャットボット
const Line = require('@line/bot-sdk')
const Aws = require('aws-sdk')
const channelAccessToken = process.env.CHANNEL_ACCESS_TOKEN
const channelSecret = process.env.CHANNEL_SECRET
const lex = new Aws.LexRuntime()
const line = new Line.Client({ channelAccessToken, channelSecret })
exports.handler = async (event) => {
console.log(JSON.stringify(event))
// Signature validation LINEから来たデータかをbot-sdkで検証
if (!Line.validateSignature(event.body, channelSecret, event.headers['x-line-signature'])) {
return {
//不正だった場合400を返す
statusCode: 400,
body: 'Bad Request',
}
}
//LINEからきたメッセージをJSON形式に変換
const body = JSON.parse(event.body)
const events = body.events
// webhookのendpoint検証すると0件のイベントが送信されるので0件の時はステータスコード200を返す
if (events.length === 0) {
return {
statusCode: 200,
body: 'Test OK',
}
}
for (let i = 0; i < events.length; i++) {
if ('replyToken' in events[i]) {
const event = events[i]
const replyToken = event.replyToken
if ('message' in event) {
const messageEvent = event
//テキストメッセージ送信時の処理
if (messageEvent.message.type === 'text') {
const inputText = messageEvent.message.text
const param = {
botAlias: 'prod',
botName: 'BookTrip_jaJP',
userId: messageEvent.source.userId,
inputText
}
const result = await lex.postText(param).promise()
const messages = []
if (result.dialogState === 'ReadyForFulfillment') {
messages.push({
type: 'text',
text: '予約が完了しました!'
})
} else {
messages.push({
type: 'text',
text: result.message
})
}
await line.replyMessage(replyToken, messages)
}
}
}
}
return {
statusCode: 200,
body: 'OK'
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment