This repository has been archived by the owner on Sep 24, 2022. It is now read-only.
forked from cyclic-software/starter-discord-bot
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlinebot.js
55 lines (48 loc) · 1.59 KB
/
linebot.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const express = require('express');
const axios = require('axios');
const line = require('@line/bot-sdk');
const PORT = process.env.PORT || 5000;
const lineConfig = {
channelAccessToken: process.env.LINE_CHANNEL_ACCESS_TOKEN,
channelSecret: process.env.LINE_CHANNEL_SECRET,
};
const lineClient = new line.Client(lineConfig);
const discordWebhookUrl = process.env.DISCORD_WEBHOOK_URL;
const discordWebhookConfig = {
headers: {
'Accept': 'application/json',
'Content-type': 'application/json',
},
};
const generatePostData = (event, profile) => {
const type = event.message.type;
if (type !== 'text') {
return {
username: profile.displayName,
avatar_url: `${profile.pictureUrl}.png`,
content: 'テキスト以外のメッセージを送信しました。',
};
}
return {
username: profile.displayName,
avatar_url: `${profile.pictureUrl}.png`,
content: event.message.text,
};
};
const lineBot = async (req, res) => {
res.status(200).end(); // 'status 200'をLINEのAPIに送信
const events = req.body.events;
events.forEach(async (event) => {
try {
const profile = await lineClient.getProfile(event.source.userId);
const postData = await generatePostData(event, profile);
// DiscordのWebHookにPOST
await axios.post(discordWebhookUrl, postData, discordWebhookConfig);
} catch(error) {
console.error(error);
}
});
};
const app = express();
app.post('/linehook/', line.middleware(lineConfig), (req, res) => lineBot(req, res));
app.listen(PORT, () => console.log(`Listening on ${ PORT } for LINE Messaging API.`));