-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·337 lines (321 loc) · 12.3 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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
#!/usr/bin/env node
var Discord = require('discord.js')
var http = require('http')
var crypto = require('crypto')
function sleep(minisecond) {
return new Promise((wakeup) => {
setTimeout(wakeup, minisecond)
})
}
class BackendConnector {
constructor(apiUrl) {
this.apiUrl = apiUrl
this.userProperty = {}
}
request(method, path, json) {
return new Promise((routeResponse, routeError) => {
var request = http.request(
`${this.apiUrl}/${path}`,
{
method: method,
headers: {
'Content-Type': 'application/json',
'User-Agent': 'quiz-chatbot-discord QA bot (node.js)'
}
},
(response) => {
var responseData = ''
response.on('data', (segment) => responseData += segment)
response.on('end', () => {
var json
try {
json = JSON.parse(responseData)
}
catch (parseError) {
routeError(parseError)
}
if (json) routeResponse(json)
})
}
)
request.on('timeout', (timeoutError) => routeError(timeoutError))
if (json) request.write(JSON.stringify(json))
request.end()
})
}
async regist(user) {
const response = await this.request('POST', 'players', user)
if (response.status.status_code == 409) {
// this should be duplicate user
throw new Error(response.status.message)
}
else if (response.status.status_code != 201) {
throw response
}
else return response.data
}
isUserFinishQuestion(uid) {
var db = this.userProperty
return db[`${uid}.finish_question`]
}
setUserFinishQuestion(uid, finish = true) {
var db = this.userProperty
db[`${uid}.finish_question`] = true
}
async getQuestionFeed(uid) {
if (this.isUserFinishQuestion(uid)) {
return await this.getQuestionRandom(uid)
}
const response = await this.request('GET', `players/${uid}/feed`)
if (response.data) return response.data
else if (response.status.status_code == 200) {
this.setUserFinishQuestion(uid)
return await this.getQuestionRandom(uid)
}
else if (response.status.status_code == 500) {
var message = '你尚未註冊,請先使用 /start 命令註冊才會開始計分'
throw new Error(message)
}
else throw response.status
}
async getQuestionRandom(uid) {
const response = await this.request('GET', `players/${uid}/rand`)
return response.data
}
async getStatus(uid) {
var response = await this.request('GET', `players/${uid}`)
if (response.status.status_code == 200) return response.data
else throw new Error(`player ${uid} not found`)
}
async answerQuestion(answer) {
const uid = answer.player_name
if (this.isUserFinishQuestion(uid)) return null
const response = await this.request('POST', 'answers', answer)
if (response.status.status_code == 409) {
throw new Error('this question is already answered')
}
else return response.data
}
}
class MyClient {
constructor(token, backendConnector, responseBase) {
var client = new Discord.Client()
this.client = client
this.backendConnector = backendConnector
this.responseBase = responseBase
this.platform = 'discord'
var promiseClient = new Promise((afterLogin) => {
client.once('ready', afterLogin)
})
client.on('message', (message) => {
if (this.isSelf(message)) return false
else if (this.isMention(message) || message.channel.type == 'dm') {
if (message.content.match(/\/\w+/)) {
return this.routeCommand(message)
.catch((commandError) => {
return message.reply(commandError.message)
.then(() => console.log(commandError))
})
}
else {
// this is a easy delay echo system,
// it will echo your message after you send next message
return message.channel.awaitMessages(
(newMessage) => !this.isSelf(newMessage),
{max: 1}
).then((collection) => {
return collection.first().reply(message.content)
})
}
}
else return false
})
this.then = promiseClient.then.bind(promiseClient)
client.login(token)
}
userToApiName(user) {
return `${this.platform}-${user.id}`
}
isMention(message) {
return message.mentions.has(this.client.user)
}
isSelf(message) {
return message.author.id == this.client.user.id
}
answerQuestion(answer, user, question) {
var backendConnector = this.backendConnector
var apiName = this.userToApiName(user)
// map A-D to 0-3
var correct = answer == (question.answer.charCodeAt() - 65)
return backendConnector.answerQuestion({
player_name: apiName,
correct,
quiz_number: question.number
}).catch(scoreError => {
return user.send(scoreError.message || String(scoreError))
}).then(() => {
function responseCorrect(emoji, responseBase) {
var i = Math.floor(responseBase.length * Math.random())
return user.send(`${emoji} ${responseBase[i]}`)
}
var base = this.responseBase
if (correct) return responseCorrect(base.emoji.right, base.right)
else return responseCorrect(base.emoji.wrong, base.wrong)
})
}
routeCommand(message) {
function commandIs(command) {
return Boolean((message.content.match(`/${command}`)))
}
var responseBase = this.responseBase
if (commandIs('help')) {
var rich = new Discord.MessageEmbed(responseBase.command.help)
rich.setColor(responseBase.command.color)
return message.channel.send(rich)
} else if (commandIs('statistic')) {
return message.reply(responseBase.command.statistic)
}
else if (commandIs('next')) {
return this.responseQuestion(message.author)
}
else if (commandIs('start')) {
var user = message.author
var nickname
var matchUid = message.content.match(/\/start\s+(\S+)/)
if (matchUid && matchUid[1]) nickname = matchUid[1]
else nickname = user.username
var apiName = this.userToApiName(user)
return this.backendConnector.regist({
name: apiName,
nickname,
platform: this.platform
}).catch((registError) => {
var message = registError.message || String(registError)
return user.send(message)
.then(() => this.backendConnector.getStatus(apiName))
}).then(
(userJson) => user.send(
this.richifyStatus(userJson)
)
).then(
() => message.reply('quiz already start in your private chat')
).then(
() => this.responseQuestion(user)
)
}
else if (commandIs('status')) {
return this.backendConnector
.getStatus(this.userToApiName(message.author))
.then((user) => {
return message.channel.send(this.richifyStatus(user))
}).catch((userError) => {
return message.reply(userError.message)
})
}
else {
return Promise.reject(new Error('no this command TT'))
}
}
richifyStatus(user) {
var responseBase = this.responseBase
var rich = new Discord.MessageEmbed({
title: 'status',
description: `${user.nickname} quiz status`
})
rich.setColor(responseBase.command.color)
rich.addField('暱稱', user.nickname)
rich.addField('id', user.name)
rich.addField('平台', user.platform)
rich.addField('分數', user.score)
rich.addField('名次', user.rank)
rich.addField('剩餘題數', user.last)
return rich
}
stringToColor(string) {
const hash = crypto.createHash('sha256')
hash.update(string)
const buffer = hash.digest()
return Array.from(buffer.slice(0, 3))
}
escape(string) {
return Discord.Util.escapeMarkdown(string).replace(/:/g, '\\$&')
}
responseQuestion(user) {
var isAnswer = (reaction) => { // TODO move to static method
var emoji = reaction.emoji
var number = this.responseBase.emoji.number
return reaction.count == 2 &&
number.some((emojiString) => emojiString == emoji.name)
}
var apiName = this.userToApiName(user)
var question
return this.backendConnector
.getQuestionFeed(apiName)
.then((q) => {
question = q
var category = question.tags.join(' ') || '其它'
var rich = new Discord.MessageEmbed({
title: category,
description: question.description,
color: this.stringToColor(category)
// author: question.author
})
var numberToEmoji =
(number) => this.responseBase.emoji.number[number]
var empty = '\u200B'
rich.addField(empty, `${question.score} 分`)
question.options.forEach(
(text, index) => rich.addField(
empty,
`${numberToEmoji(index)} ${this.escape(text)}`
)
)
if (question.hint) {
const hint = this.escape(question.hint)
rich.addField('提示', `||${hint}||`)
}
return user.send(rich)
}).then((message) => {
var number = this.responseBase.emoji.number
var reaction = Promise.resolve(true)
for (let i=0; i<=3; i++) {
reaction = reaction.then(
() => message.react(number[i])
)
}
return reaction.then(() => message)
}).then((message) => message.awaitReactions(
isAnswer,
{max: 1}
)).then((reactionCollection) => {
var emoji = reactionCollection.first().emoji
var answer = this.responseBase.emoji.number.indexOf(emoji.name)
return this.answerQuestion(answer, user, question)
}).then(() => sleep(1000))
.then(() => this.responseQuestion(user))
.catch((questionError) => {
user.send(questionError.message)
})
}
}
exports.MyClient = MyClient
exports.Discord = Discord
exports.BackendConnector = BackendConnector
exports.run = function (apiUrl, token, responseDatabase) {
var backendConnector = new this.BackendConnector(apiUrl)
var myClient = new this.MyClient(token, backendConnector, responseDatabase)
return myClient
}
exports.runArgvFile = function () {
const fs = require('fs')
const process = require('process')
const [apiFile, tokenFile, responseDatabaseFile] = process.argv.slice(2)
const apiUrl = fs.readFileSync(apiFile, 'utf8').trim()
const token = fs.readFileSync(tokenFile, 'utf8').trim()
const responseDatabase =
JSON.parse(fs.readFileSync(responseDatabaseFile, 'utf8'))
return this.run(apiUrl, token, responseDatabase)
}
if (require.main == module) {
exports.runArgvFile()
}