Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
4
Help us understand the problem. What is going on with this article?
@inoue2002

【個人メモ】Node.js LINEBOT雛形

More than 1 year has passed since last update.

プロジェクト作成とハローワールド

$ mkdir linebot
$ cd linebot 
$ npm init -y
$ npm i @line/bot-sdk express 
$ npm install dotenv --save
$ touch index.js $$ .env
$ code .
index.js
'use strict';

const express = require('express');
const line = require('@line/bot-sdk');
const PORT = process.env.PORT || 3000;
const dotenv = require('dotenv')
dotenv.config()

const config = {
    channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN,
  channelSecret: process.env.CHANNEL_SECRET
};

const app = express();

app.get('/', (req, res) => res.send('Hello(GET)')); 
app.post('/webhook', line.middleware(config), (req, res) => {
    console.log(req.body.events);

     if(req.body.events[0].replyToken === '00000000000000000000000000000000' && req.body.events[1].replyToken === 'ffffffffffffffffffffffffffffffff'){
        res.send('Hello!(POST)');
        console.log('疎通確認用');
        return; 
    }

    Promise
      .all(req.body.events.map(handleEvent))
      .then((result) => res.json(result));
});

const client = new line.Client(config);

function handleEvent(event) {
  if (event.type !== 'message' || event.message.type !== 'text') {
    return Promise.resolve(null);
  }

  return client.replyMessage(event.replyToken, {
    type: 'text',
    text: event.message.text 
  });
}

app.listen(PORT);
console.log(`Server running at ${PORT}`);
.env.sample
CHANNEL_ACCESS_TOKEN = "xxxxxxxxxxxxxxxxxxx"
CHANNEL_SECRET = "xxxxxxxxxxxxxx"
BASE_URL = 'xxxxxxxxxxxxx.ngrok.io'
$ ngrok http 3000

BASE_URLの書き換え

$ node index.js

webhookURLの設定

4
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
inoue2002
18歳 / 普通科高校生です。LINEBotのコード書いてたり、学校向けにサービスやってたり / LT登壇やITイベント開いたりしてます / 未踏ジュニア2020 / 詳しくはポートフォリオに書いてます / 陸上やってました🏃‍♀️ / #lineapi #nodejs #vuejs #aws

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
4
Help us understand the problem. What is going on with this article?