-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
175 lines (146 loc) · 5.49 KB
/
index.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
'use strict';
require('dotenv').config();
const line = require('@line/bot-sdk');
const express = require('express');
const mysql = require('mysql2');
const correctTypo = require('./controllers/correctTypo');
const handleCommand = require('./controllers/command');
const {
createAndLinkRichMenu,
unlinkRichMenuFromUser
} = require('./controllers/richmenu');
const createScoreImage = require('./controllers/createScoreImage');
const path = require('path');
// create LINE SDK config from env variables
const config = {
channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN,
channelSecret: process.env.CHANNEL_SECRET,
};
// create LINE SDK client
const client = new line.Client(config);
// create LINE SDK client
const connection = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
});
// connect to MySQL
connection.connect((err) => {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
// create Express app
const app = express();
// http://localhost:3000/admin?password=1234
// Serve the admin page
app.get('/admin', (req, res) => {
const password = req.query.password; // Retrieve the password from the query parameter
const correctPassword = process.env.PASSWORD; // Retrieve the correct password from the .env file
// Check if the password matches
if (password !== correctPassword) {
res.status(401).send('Unauthorized'); // Return Unauthorized status if the password is incorrect
return;
}
res.sendFile(path.join(__dirname, 'public', 'admin.html')); // Serve the admin.html file
});
// Serve static files
app.use(express.static(path.join(__dirname, 'public')));
// register a webhook handler with middleware
app.post('/callback', line.middleware(config), (req, res) => {
Promise
.all(req.body.events.map(handleEvent))
.then((result) => res.json(result))
.catch((err) => {
console.error(err);
res.status(500).end();
});
});
// event handler
async function handleEvent(event) {
if (event.type !== 'message' || event.message.type !== 'text') {
return Promise.resolve(null);
}
let message = event.message.text;
const lineId = event.source.userId;
const userProfile = await client.getProfile(lineId);
const userName = userProfile.displayName;
console.log(`User ID: ${lineId}, User name: ${userName}, User message: ${message}`);
// Check and correct user typos
message = correctTypo(message);
// Check if user exists
const sqlSelectUser = 'SELECT * FROM users WHERE line_id = ?';
const user = await queryAsync(sqlSelectUser, [lineId]);
if (!user.length) {
const sqlInsertUser = 'INSERT INTO users (user_name, line_id, role_id) VALUES (?, ?, 1)';
await queryAsync(sqlInsertUser, [userName, lineId]);
// Create the Rich Menu, upload the image, and link it to the user
// await createAndLinkRichMenu(client, lineId);
}
const sqlUserId = 'SELECT u.user_id FROM users u WHERE line_id = ?';
const uId = await queryAsync(sqlUserId, [lineId]);
const userId = uId[0].user_id;
const sqlUserRole = 'SELECT r.role_name FROM users u JOIN roles r ON u.role_id = r.role_id WHERE u.user_id = ?';
const userRole = await queryAsync(sqlUserRole, [userId]);
const role = userRole[0].role_name;
// Unlink the current rich menu from the user
await unlinkRichMenuFromUser(client, lineId);
// Create the Rich Menu, upload the image, and link it to the user
await createAndLinkRichMenu(client, lineId, role);
// Handle user commands
let replyMessage = await handleCommand(message, userId, userName, role, client, queryAsync, createScoreImage);
const sqlInsert = 'INSERT INTO messages (message, user_id) VALUES (?, ?)';
connection.query(sqlInsert, [message, userId], (err, result) => {
if (err) {
console.error(err);
return;
}
console.log('message stored in MySQL');
});
// return client.replyMessage(event.replyToken, echo);
if (replyMessage.type === 'image') {
// Reply with the image message
return client.replyMessage(event.replyToken, replyMessage);
} else {
// Reply with the text message
const echo = {
type: 'text',
text: replyMessage,
};
const sqlInsert2 = 'INSERT INTO messages (message, user_id) VALUES (?, ?)';
connection.query(sqlInsert2, [replyMessage, userId], (err, result) => {
if (err) {
console.error(err);
return;
}
console.log('reply message stored in MySQL');
});
return client.replyMessage(event.replyToken, echo);
}
}
function queryAsync(sql, params) {
return new Promise((resolve, reject) => {
connection.query(sql, params, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
}
app.get('/:imageFilename', (req, res) => {
const imageFilename = req.params.imageFilename;
const imagePath = path.join(__dirname, 'img', imageFilename);
res.sendFile(imagePath);
});
const apiRoutes = require('./apiRoutes');
app.use(apiRoutes);
// start Express server
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`listening on ${port}`);
});