-
Notifications
You must be signed in to change notification settings - Fork 0
/
vdiscord.js
273 lines (225 loc) · 8.47 KB
/
vdiscord.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
const Discord = require("discord.js");
const console = require("console");
const fs = require("fs");
const ws = require("ws");
const axios = require('axios');
const EventEmitter = require('events');
const config = require("./config.json");
const TOKEN_ENDPOINT = "https://api.assemblyai.com/v2/realtime/token";
const RT_ENDPOINT = "wss://api.assemblyai.com/v2/realtime/ws?sample_rate=48000&token="
const FRAMES_PER_BUFFER = 48000 //1 fps? actually a lot faster
const COMMANDS = [
"death",
"definitely",
"deafen",
"deaf",
"defin",
"undeffin",
"undeffin",
"undeafen",
"undeffin",
"undeathin",
"undeathined",
"undefined",
"undefinly",
"undefin",
"skip",
"stop",
"leave",
"translate",
"weather"
];
class VDiscord {
static client;
static keys;
static emitter = new EventEmitter();
constructor(client){
const speech = require("@google-cloud/speech");
const projectId = "angular-unison-338316";
const keyFilename = "angular-unison-338316-0c8e7e275407.json";
this.googleClient = new speech.SpeechClient({ projectId, keyFilename });
this.users = new Map();
this.lookup = new Map();
this.buffers = new Map();
this.snapshots = new Map();
this.keyphrase = "alexa";
console.log("Initializing discord");
this.initDiscord(client);
//console.log("Initializing assemblyai")
//this.initAssembly();
}
initDiscord(client){
this.discord = client;
}
initAssembly(){
/*
//receive transcription handling
this.ws.onmessage = (message) => {
//if(message.data == undefined);
const info = JSON.parse(message.data);
const id =
console.log("Transcription received. " + info)
this.parseTranscript(info.text);
};
console.log("Finished assembly ai initialization");*/
}
async newToken(){
const response = await axios.post(TOKEN_ENDPOINT, // use account token to get a temp user token
{ expires_in: 3600 }, // can set a TTL timer in seconds. (TODO: system for refreshing tokens)
{ headers: { authorization: config.assembly_token } }); // AssemblyAI API Key goes here
console.log("DATA: ", response.data.token);
return response.data.token;
}
//assembly 'message' event calls parse function which sends data to bot
async parseTranscript(rtext, endpoint){
//parse message
//check for keyphrase
let text = rtext;
if(text.includes(this.snapshots.get(endpoint)))
text = rtext.substring(this.snapshots.get(endpoint).length);
let keyloc = text.toLowerCase().indexOf(this.keyphrase);
if(keyloc == -1) return;
//check for valid command
let message = null;
for(const str of COMMANDS){
if(text.includes(str)){
message = str;
break;
}
}
if(message == null) return;
/*
Attempt at fabricating DiscordMessage object. does not work
TODO: make
console.log(this.discord.yep);
messageObject = new Discord.Message(this.discord, {
id: this.discord.yep,
content: config.prefix + message,
author: null,
pinned: false,
tts: null,
embeds: null,
attachments: null,
nonce: "",
channel: this.discord.chan,
guild: this.discord.guild,
member: this.lookup.get(endpoint)
}, this.discord.chan)
*/
this.discord.emit("voice", message, this.lookup.get(endpoint));
this.snapshots.set(endpoint, rtext);
console.log(this.snapshots.get())
//make required arguments
//emit event using cleint
}
async googleAudio(chunk, user){
let username = user.user.username;
if(!this.users.has(user)){
this.buffers.set(user, Buffer.alloc(0));
this.users.set(user, null);
}
this.buffers.set(user, Buffer.concat([this.buffers.get(user), chunk]));
if(this.buffers.get(user).length / 2 >= FRAMES_PER_BUFFER){}
let new_buffer = await this.convert_audio(chunk);
const bytes = new_buffer.toString('base64');
const audio = {
content: bytes,
};
const config = {
encoding: "LINEAR16",
sampleRateHertz: 48000,
languageCode: "en-US",
};
const request = {
audio: audio,
config: config,
};
// Detects speech in the audio file
const [response] = await this.googleClient.recognize(request);
const transcription = response.results
.map((result) => result.alternatives[0].transcript)
.join("\n");
console.log(`Transcription: ${transcription}`);
}
//discord 'join' event calls send function which starts sending audio
async sendAudio(chunk, user){
let username = user.user.username;
if(!this.users.has(user)){
let promise = this.newToken();
promise.then((value) =>{
let endpoint = RT_ENDPOINT + value;
var rtSocket = new ws.WebSocket(endpoint);
rtSocket.onmessage = (message) => {
const info = JSON.parse(message.data);
//print transcript for debug
console.log(info.text)
if(typeof info.text != "undefined" && info.message_type == 'PartialTranscript')
this.parseTranscript(info.text, endpoint);
}
console.log("NEW USER: ", username, "||", endpoint);
this.users.set(user, rtSocket);
this.lookup.set(endpoint, user);
});
this.buffers.set(user, Buffer.alloc(0));
this.users.set(user, null);
}
this.buffers.set(user, Buffer.concat([this.buffers.get(user), chunk]));
if(this.buffers.get(user).length / 2 >= FRAMES_PER_BUFFER){
let slice = this.buffers.get(user).slice(0, FRAMES_PER_BUFFER*2);
this.buffers.set(user, this.buffers.get(user).slice(FRAMES_PER_BUFFER * 2));
const data = new Int16Array(slice);
const ndata = new Int16Array(data.length/2);
for (let i = 0; i < FRAMES_PER_BUFFER*2; i+=2) {
ndata[i] = data[i * 2]
ndata[i + 1] = data[i * 2 + 1]
}
const mono = Buffer.from(ndata, "binary");
//fs.appendFileSync("testfile",mono);
//Audio bitstream debugging
//Wait for websocket to open
while(this.users.get(user) == null || this.users.get(user).readyState == 0){
await new Promise(r => setTimeout(r, 100));
}
//Send audio stream to AssemblyAI
let response = await this.users.get(user).send(JSON.stringify({
audio_data: mono.toString('base64'),
word_boost: [this.keyphrase, "deafen", "undeafen", "undeafin"],
format_text: false
}));
}
}
//manually flushes/pushes buffer
async finished(user){
let slice = this.buffers.get(user).slice(0);
this.buffers.get(user) = this.buffers.get(user).slice(buffer.length);
const data = new Int16Array(slice);
const ndata = new Int16Array(data.length/2);
for (let i = 0; i < slice.length; i+=2) {
ndata[i] = data[i * 2]
ndata[i + 1] = data[i * 2 + 1]
}
const mono = Buffer.from(ndata, "binary");
this.users.get(user).send(JSON.stringify({
audio_data: mono.toString('base64'),
word_boost: [this.keyphrase],
format_text: false
}));
}
async convert_audio(input) {
try {
// stereo to mono channel
const data = new Int16Array(input);
const ndata = new Int16Array(data.length / 2);
for (let i = 0, j = 0; i < data.length; i += 4) {
ndata[j++] = data[i];
ndata[j++] = data[i + 1];
}
return Buffer.from(ndata);
} catch (e) {
console.log(e);
console.log("convert_audio: " + e);
throw e;
}
}
}
module.exports = VDiscord;