-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathbot.js
110 lines (90 loc) · 2.94 KB
/
bot.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
module.exports = function (RED) {
'use strict'
function WhatsappBot (config) {
RED.nodes.createNode(this, config)
const node = this
node.name = config.name
const SOCKETS_STATE = {
OPENING: 'info',
PAIRING: 'info',
UNPAIRED: 'info',
UNPAIRED_IDLE: 'info',
CONNECTED: 'success',
TIMEOUT: 'error',
CONFLICT: 'error',
UNLAUNCHED: 'error',
PROXYBLOCK: 'error',
TOS_BLOCK: 'error',
SMB_TOS_BLOCK: 'error',
DEPRECATED_VERSION: 'error'
}
const clientNode = RED.nodes.getNode(config.client)
function registerEvents () {
clientNode.on('stateChange', onStateChange.bind(node))
clientNode.on('clientEvent', onClientEvent.bind(node))
}
function onStateChange (socketState) {
setStatus(SOCKETS_STATE[socketState], 'Socket: ' + socketState)
}
function onClientEvent (eventName, ...args) {
node.send({ topic: eventName, payload: args })
}
function onChatEvent (event, chatId, ...args) {
node.send({ topic: event, chatId: chatId, args: args })
}
if (clientNode) {
clientNode.register(node)
setStatus('warning', 'Authenticating...')
clientNode.on('qrCode', function (qrCode) {
node.send({ topic: 'qrCode', payload: [qrCode] })
})
clientNode.on('ready', function (client) {
setStatus('success', 'Connected')
node.client = client
})
registerEvents()
}
node.on('input', function (msg) {
if (msg.topic === 'restart') {
setStatus('warning', 'Authenticating...')
clientNode.restart()
.then(() => node.send({ topic: msg.topic, origin: msg, payload: [true] }))
.catch((err) => node.error('Error while restarting client ' + err.message))
return
}
if (!node.client) {
setStatus('error', 'Client not connected')
return
}
if (typeof node.client[msg.topic] === 'function') {
if (msg.topic === 'onParticipantsChanged' || msg.topic === 'onLiveLocation') {
const chatId = msg.payload[0]
// register for chat event
node.client[msg.topic](chatId, onChatEvent.bind(node, msg.topic, chatId))
} else {
node.client[msg.topic](...msg.payload).then((...args) => {
node.send({
topic: msg.topic,
payload: args,
origin: msg
})
}).catch(err => {
node.error('Requested api "' + msg.topic + '" ' + err.message)
})
}
} else {
node.error('Requested api "' + msg.topic + '" doesn\'t exists')
}
})
// Set node status
function setStatus (type, message) {
const types = { info: 'blue', error: 'red', warning: 'yellow', success: 'green' }
node.status({
fill: types[type] || 'grey',
shape: 'dot',
text: message
})
}
}
RED.nodes.registerType('whatsapp-bot', WhatsappBot)
}