Guest User

Untitled

a guest
Jan 4th, 2024
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* eslint-disable @typescript-eslint/no-unused-vars */
  2. /* eslint-disable @typescript-eslint/explicit-function-return-type */
  3. import 'dotenv/config';
  4. import { Client, Guild, IntentsBitField } from 'discord.js';
  5. import {
  6.   joinVoiceChannel,
  7.   EndBehaviorType,
  8.   createAudioPlayer,
  9.   createAudioResource,
  10. } from '@discordjs/voice';
  11. import prism from 'prism-media';
  12.  
  13. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  14. // @ts-ignore - node-wit's types are not up to date
  15. import { Wit } from 'node-wit';
  16. import { Readable } from 'node:stream';
  17.  
  18. if (!process.env.DISCORD_TOKEN) throw new Error('DISCORD_TOKEN is not defined');
  19. if (!process.env.WIT_AI_TOKEN) throw new Error('WIT_AI_TOKEN is not defined');
  20.  
  21. const witClient = new Wit({ accessToken: process.env.WIT_AI_TOKEN });
  22. const client = new Client({
  23.   intents: [
  24.     IntentsBitField.Flags.Guilds,
  25.     IntentsBitField.Flags.GuildMessages,
  26.     IntentsBitField.Flags.GuildVoiceStates,
  27.     IntentsBitField.Flags.MessageContent,
  28.   ],
  29. });
  30.  
  31. // [...]
  32.  
  33. // Drop 2 bytes every 2 bytes to convert stereo to mono
  34. const convertStereoToMono = (stereoData: Buffer): Buffer =>
  35.   Buffer.from(stereoData.filter((_, index) => index % 4 < 2));
  36.  
  37. client.on('voiceStateUpdate', (oldMember, newMember) => {
  38.   if (
  39.     oldMember.id !== process.env.MAFIOU_ID ||
  40.     newMember.id !== process.env.MAFIOU_ID
  41.   )
  42.     return;
  43.   const newUserChannel = newMember.channelId;
  44.   const oldUserChannel = oldMember.channelId;
  45.  
  46.   if (newUserChannel && newUserChannel != '') {
  47.     const connection = joinVoiceChannel({
  48.       channelId: newUserChannel,
  49.       guildId: newMember.guild.id,
  50.       adapterCreator: newMember.guild.voiceAdapterCreator,
  51.       selfDeaf: false,
  52.     });
  53.     const player = createAudioPlayer();
  54.     connection.subscribe(player);
  55.  
  56.     if (newUserChannel === '') {
  57.       connection.destroy();
  58.     }
  59.  
  60.     const receiver = connection.receiver;
  61.  
  62.     receiver.speaking.on('start', (userId) => {
  63.       const user = client.users.cache.get(userId)?.username ?? userId;
  64.       console.log(`User ${user} started speaking`);
  65.       const opusStream = connection.receiver.subscribe(userId, {
  66.         end: {
  67.           behavior: EndBehaviorType.AfterSilence,
  68.           duration: 300,
  69.         },
  70.       });
  71.       const audioBuffers: Buffer[] = [];
  72.       opusStream
  73.         .pipe(
  74.           new prism.opus.Decoder({ rate: 48_000, channels: 2, frameSize: 960 }),
  75.         )
  76.         .on('data', (chunk) => {
  77.           audioBuffers.push(chunk);
  78.         })
  79.         .on('end', async () => {
  80.           const resultBuffer = Buffer.concat(audioBuffers);
  81.           try {
  82.             const voiceDuration = resultBuffer.length / 48_000 / 2;
  83.             if (voiceDuration < 1) return; // Ignore environment noises
  84.             const witResponse = await witClient.speech(
  85.               'audio/raw;endian=little;encoding=signed-integer;rate=48k;bits=16',
  86.               Readable.from(convertStereoToMono(resultBuffer)),
  87.             );
  88.             console.log(
  89.               `${user}: ${witResponse.text}`,
  90.               witResponse,
  91.               witResponse?.speech?.tokens,
  92.             );
  93.  
  94.             if (!mav) return;
  95.             // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  96.             // @ts-ignore
  97.             const mafiou = await mav.members.fetch(process.env.MAFIOU_ID);
  98.             // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  99.             // @ts-ignore
  100.             const ftefane = await mav.members.fetch(process.env.FTEFANE_ID);
  101.             // Actions associées à chaque phrase
  102.             interface Actions {
  103.               [key: string]: (guild: Guild) => Promise<void>;
  104.             }
  105.  
  106.             const aboie = createAudioResource('../sounds/aboie.mp3');
  107.  
  108.             const actions: Actions = {
  109.                 // [...]
  110.               // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
  111.               'aboie matthew': async (guild: Guild) => {
  112.                 console.log('oe');
  113.                 console.log(`aboie : ${aboie}`);
  114.                 player.play(aboie);
  115.               },
  116.               'aboie mafiou': async (guild: Guild) => {
  117.                 console.log('oe');
  118.                 console.log(`aboie : ${aboie}`);
  119.  
  120.                 player.play(aboie);
  121.               },
  122.               'aboie mafieux': async (guild: Guild) => {
  123.                 console.log('oe');
  124.                 console.log(`aboie : ${aboie}`);
  125.                 player.play(aboie);
  126.               },
  127.               'aboa mafiou': async (guild: Guild) => {
  128.                 console.log('oe');
  129.                 console.log(`aboie : ${aboie}`);
  130.                 player.play(aboie);
  131.               },
  132.             };
  133.            
  134.              // [...]
Advertisement
Add Comment
Please, Sign In to add comment