-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
167 lines (131 loc) · 3.62 KB
/
index.ts
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
import WAWebJS, {Client, LocalAuth, MessageTypes} from 'whatsapp-web.js'
import qrcode from 'qrcode-terminal'
import WebSocket from 'ws'
import {toFile} from 'qrcode'
const client = new Client({authStrategy: new LocalAuth()})
let isClientInitialized = false
require('dotenv').config()
const wsUrl = `ws://localhost:${process.env.WS_PORT ?? 3333}`
let ws = new WebSocket(wsUrl, {})
ws.addEventListener('error', async e => {
console.log(`connection failed because ${e.message}, will try again in 5s`)
})
ws.addEventListener('open', async () => {
console.log(`connected to ws at ${wsUrl}`)
await client.initialize()
})
ws.addEventListener('close', async reason => {
console.log(`disconnected from ws`)
if (isClientInitialized) {
await client.destroy()
process.exit(0)
}
})
const sendMessage = async (
content: WAWebJS.MessageContent,
chat: WAWebJS.Chat,
options?: WAWebJS.MessageSendOptions | undefined
): Promise<WAWebJS.Message> => {
await client.sendPresenceAvailable()
await delay(randomIn(1000, 2000))
await chat.sendStateTyping()
const msg = await chat.sendMessage(content, options)
await chat.clearState()
await client.sendPresenceUnavailable()
return msg
}
type WsMessage = {
event: string
}
type WsTranscriptData = {
payload: {
error?: string
transcript: string
chatId: string
messageId: string
}
} & WsMessage
ws.addEventListener('message', async ({data, ...e}: any) => {
let _data
try {
_data = JSON.parse(data)
} catch {
_data = data
}
if (!_data) {
return
}
if (typeof _data === 'object') {
const {payload} = _data as WsTranscriptData
if (!payload) {
console.error('no payload received')
return
}
const chat = await client.getChatById(payload.chatId)
if (!chat) {
console.error(`could not find chat ${payload.chatId}`)
return
}
if (_data.event === 'reply_with_transcription') {
await sendMessage(payload.transcript, chat, {
quotedMessageId: payload.messageId,
})
} else if (_data.event === 'reply_with_error') {
await sendMessage(
'❌ Error: ' + (payload.error ?? 'error while transcribing'),
chat,
{
quotedMessageId: payload.messageId,
}
)
}
} else {
console.log(_data)
}
})
client.on('qr', qr => {
console.log(`got qr at ${new Date().toISOString()}`)
qrcode.generate(qr, {small: true})
toFile('qrcode.png', qr)
})
client.on('ready', () => {
console.log('client is ready')
isClientInitialized = true
})
const isAudio = (msg: WAWebJS.Message) =>
msg.hasMedia &&
(msg.type === MessageTypes.AUDIO || msg.type === MessageTypes.VOICE)
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))
const randomIn = (min: number, max: number) => Math.random() * (max - min) + min
client.on('message', async msg => {
const chat = await msg.getChat()
if (isAudio(msg)) {
try {
const media = await msg.downloadMedia()
if (media === undefined) {
throw new Error('got undefined media.')
}
const {data, mimetype} = media
ws.send(
JSON.stringify({
event: 'transcript_audio',
payload: {
data,
mimetype,
messageId: msg.id._serialized,
chatId: msg.from,
},
})
)
console.log('sent data to ws')
} catch (e) {
console.error(e)
await sendMessage('❌ Error: failed to process media', chat, {
quotedMessageId: msg.id._serialized,
})
await msg.react('👎')
}
} else {
console.log(`got message with body: ${msg.body}`)
}
})