discord-speech-recognition
Version:
Extension for making discord speech recognition bots.
82 lines • 3.4 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const opus_1 = require("@discordjs/opus");
const voice_1 = require("@discordjs/voice");
const stream_1 = require("stream");
const voiceMessage_1 = require("../voiceMessage");
const events_1 = require("../../events");
class OpusDecodingStream extends stream_1.Transform {
constructor() {
super();
this.encoder = new opus_1.OpusEncoder(48000, 2);
}
_transform(data, encoding, callback) {
this.push(this.encoder.decode(data));
callback();
}
}
/**
* Starts listening on connection and emits `speech` event when someone stops speaking
* @param connection Connection to listen
*/
const handleSpeakingEvent = ({ client, connection, speechOptions, }) => {
connection.receiver.speaking.on("start", function handleSpeechEventOnConnectionReceiver(userId) {
const user = client.users.cache.get(userId);
// Shouldn't proceed if user is undefined, some checks will fail even if they shouldn't
if (!user)
return;
const { shouldProcessSpeech } = speechOptions;
if (shouldProcessSpeech && !shouldProcessSpeech(user)) {
return;
}
if (speechOptions.ignoreBots && (user === null || user === void 0 ? void 0 : user.bot)) {
return;
}
const { receiver } = connection;
const opusStream = receiver.subscribe(userId, {
end: {
behavior: voice_1.EndBehaviorType.AfterSilence,
duration: 300,
},
});
const bufferData = [];
opusStream
.pipe(new OpusDecodingStream())
.on("data", (data) => {
bufferData.push(data);
});
opusStream.on("end", () => __awaiter(this, void 0, void 0, function* () {
const voiceMessage = yield (0, voiceMessage_1.createVoiceMessage)({
client,
bufferData,
user,
connection,
speechOptions,
});
if (voiceMessage)
client.emit(events_1.SpeechEvents.speech, voiceMessage);
}));
});
};
/**
* Enables `speech` event on Client, which is called whenever someone stops speaking
*/
exports.default = (client, speechOptions) => {
client.on(events_1.SpeechEvents.voiceJoin, (connection) => __awaiter(void 0, void 0, void 0, function* () {
if (!connection) {
return;
}
yield (0, voice_1.entersState)(connection, voice_1.VoiceConnectionStatus.Ready, 20e3);
handleSpeakingEvent({ client, speechOptions, connection });
}));
};
//# sourceMappingURL=speech.js.map