This repository has been archived by the owner on Oct 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
102 lines (82 loc) · 2.48 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
const pg = require('pg-promise')()
const bike = require('./bike.js')
const stairs = require('./stairs.js')
const overview = require('./overview.js')
class State {
constructor (achievements, config, db) {
this.achievements = achievements
this.config = config
this.db = db
}
}
function FitnessBot (config) {
const fitnessBot = {}
const db = pg(config.db)
let state
function init () {
return db.query('SELECT * FROM achievements ORDER BY height')
.then(res => {
state = new State(res, config, db)
})
.catch(onError)
}
function onError (err) {
console.error(`${new Date()} ${err.stack || err}`)
}
function onMessage (message) {
message = Object.assign({}, message, { words: message.text.split(/(?::|,|!|\.|\?)?(?: +|$)/) })
const actions = []
// Stairs Commands
if (message.words.includes('#std')) {
message.doneHash = '#std'
actions.push(stairs.onStairsDone)
}
if (message.words.includes('#stairs')) {
message.doneHash = '#stairs'
actions.push(stairs.onStairsDone)
}
if (message.words.includes('#stairs-lead') || message.words.includes('#stairs-leaderboard')) {
actions.push(stairs.onStairsLeaderboard)
}
if (message.words.includes('#stairs-achievements')) {
actions.push(stairs.onStairsAchievements)
}
// Bike Commands
if (message.words.includes('#btw')) {
message.doneHash = '#btw'
actions.push(bike.onBikeDone)
}
if (message.words.includes('#bike-lead') || message.words.includes('#bike-leaderboard')) {
actions.push(bike.onBikeLeaderboard)
}
if (message.words.includes('#bike-achievements')) {
actions.push(bike.onBikeAchievements)
}
// Overview Commands
if (message.words.includes('#lead') || message.words.includes('#leaderboard')) {
actions.push(overview.onOverviewLeaderboard)
}
if (message.words.includes('#help')) {
actions.push(overview.onHelp)
}
return actions.reduce((promise, action) => promise.then(() => action(message, state)), Promise.resolve())
.catch(onError)
}
if (!config.adapter) {
// External adapter will push messages.
fitnessBot.onMessage = onMessage
} else {
config.adapter.on('message', onMessage)
}
fitnessBot.end = () => {
db.end()
if (config.adapter) {
config.adapter.end()
}
}
init().then(() => {
console.log('Started listening for messages')
return fitnessBot
})
}
module.exports = FitnessBot