This repository has been archived on 2024-02-26. You can view files and clone it, but cannot push or open issues or pull requests.
line-bot-js/app.js
2023-01-10 12:01:05 +08:00

87 lines
2.4 KiB
JavaScript

// 背景執行 forever start -a -l line-bot-js.log app.js
// 重新背景執行 forever restart -a -l line-bot-js.log app.js
// 監聽檔案變化 nodemon "npm start"
// Debug nodemon --inspect=192.168.1.15:9229 app.js
require('dotenv').config()
const dateFormat = require('dateformat');
// 引用linebot SDK
var linebot = require('linebot');
const fs = require('fs');
const express = require('express');
const app = express();
//讀取憑證及金鑰
const prikey = fs.readFileSync('../certificate/RSA-privkey.pem', 'utf8');
const cert = fs.readFileSync('../certificate/RSA-cert.pem', 'utf8');
const cafile = fs.readFileSync('../certificate/RSA-chain.pem', 'utf-8');
//建立憑證及金鑰
const credentials = {
key: prikey,
cert: cert,
ca: cafile
};
// 用於辨識Line Channel的資訊
var bot = linebot({
channelId: process.env.toJianMiau,
channelSecret: process.env.channelSecret,
channelAccessToken: process.env.channelAccessToken
});
var ZhuHanbot = linebot({
channelId: process.env.toZhuHantoJianMiau,
channelSecret: process.env.ZhuHanchannelSecret,
channelAccessToken: process.env.ZhuHanchannelAccessToken
});
const LineNotifyClass = require('./LineNotifyClass')
const MessageClass = require('./MessageClass')
const JoinClass = require('./JoinClass')
const MemberJoinedClass = require('./MemberJoinedClass')
const LineNotify = new LineNotifyClass();
const Message = new MessageClass(bot, ZhuHanbot, LineNotify);
const Join = new JoinClass(bot, LineNotify);
const MemberJoined = new MemberJoinedClass(bot, LineNotify);
// 當有人傳送訊息給Bot時
bot.on('event', function (event) {
try {
switch (event.type) {
case 'message': {
Message.Message(event);
break;
}
case 'join': {
Join.Join(event);
break;
}
case 'leave':
case 'follow':
case 'unfollow':
case 'memberJoined': {
MemberJoined.MemberJoined(event);
break;
}
case 'memberLeave':
case 'postback':
case 'accountLink':
case 'fallback':
default:
break;
}
} catch (error) {
console.error(error);
}
});
// Bot所監聽的webhook路徑與port
const port = process.env.PORT || 3000;
bot.listen('/linewebhook', port, credentials, function () {
let datetime = dateFormat(new Date(), "yyyy-mm-dd HH:MM:ss");
console.log(`${datetime} listening on ${port}`);
console.log(`${datetime} [BOT已準備就緒]`);
});