-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot-logic.js
130 lines (119 loc) · 2.4 KB
/
bot-logic.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
/**
* bot logic sample
*/
import { Service } from 'ringcentral-chatbot/dist/models'
/**
* when chat group got new post
* @param {string} text post text content
* @param {object} group info
* @param {Bot} bot instance
*/
const botName = 'welcome-bot'
function defaultWelcomeMsg() {
return 'Welcome, new team member!:grinning:'
}
function help(id, welcomeMsg = defaultWelcomeMsg()) {
return `Hello, I am welcome bot. I will welcome every new member who join this chatgroup with message "@newmember ${welcomeMsg}".
You can reply "![:Person](${id}) **set** your-welcome-message" if you want to set custom welcome message.`
}
exports.onBotGetPost = async ({
group, bot, text
}) => {
let reg = / *set +(.+)$/
let arr = text.match(reg)
let where = {
botId: bot.id,
groupId: group.id,
name: botName
}
if (arr && arr[1]) {
let welcomeMsg = arr[1]
await Service.update({
data: {
welcomeMsg
}
}, {
where
})
return await bot.sendMessage(
group.id,
{
text: 'New welcome message set'
}
)
} else {
let inst = await Service.findOne({
where
})
let text = help(bot.id, inst ? inst.data.welcomeMsg : undefined)
await bot.sendMessage(
group.id,
{
text
}
)
}
}
/**
* when bot join chat group
* @param {object} group info
* @param {Bot} bot instance
*/
exports.onBotJoinGroup = async ({
bot,
group
}) => {
let where = {
botId: bot.id,
groupId: group.id,
name: botName
}
let inst = await Service.findOne({
where
})
if (!inst) {
await Service.create({
botId: bot.id,
groupId: group.id,
data: {
welcomeMsg: defaultWelcomeMsg()
},
// use name store welcome msg
name: botName
})
}
let welcome = inst ? inst.data.welcomeMsg : defaultWelcomeMsg()
await bot.sendMessage(
group.id,
{
text: help(bot.id, welcome)
}
)
}
exports.onPersonsAdded = async({
message,
bot,
group
}) => {
let where = {
botId: bot.id,
groupId: group.id,
name: botName
}
let inst = await Service.findOne({
where
})
if (!inst || !inst.data) {
return
}
let added = message.body.addedPersonIds
let at = added
.reduce((prev, id) => {
return `${prev} ![:Person](${id})`
}, '').trim()
await bot.sendMessage(group.id, {
text: `${at}
${inst.data.welcomeMsg}
`
})
}