DiscordJSv14 Recording / Receiving Voice Audio - javascript

So I'm working on a Discord bot using JS and DiscordJSv14, and want the bot to use audio from a voice chat to send to another bot, some type of listen and snitch bot.
So far I got the Bot's connecting to the voice call but can't get any of the packets to send to the other bot.
Here's some code I've got so far:
const connection = joinVoiceChannel({
channelId: C.id,
guildId: guild.id,
adapterCreator: guild.voiceAdapterCreator,
selfDeaf: false,
selfMute: false,
group: this.client.user.id,
});
if (isListener) {
console.log("Listener Is Joining Voice And Listening...");
const encoder = new OpusEncoder(48000, 2);
let subscription = connection.receiver.subscribe(ID); // ID = Bot's ID
// Basically client.user.id
subscription.on("data", (chunk) => {
console.log(encoder.decode(chunk));
});
}
Console won't log anything about the chunk
Using DiscordJSv14 + #discordjs/opus

Everything worked fine I just needed to add the following code below.
this.client = new Client({
intents: [GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildMessages, GatewayIntentBits.Guilds],
});

Related

nodemon: clean exit - waiting for changes before restart

I've been working on this code for a discord bot that tracks a the voice channels of a server until a specific person joins which then the bot joins and then plays an audio. However whenever I start up my file, it keeps on saying
[nodemon] starting `node index.js`
[nodemon] clean exit - waiting for changes before restart
I have no clue why, I've looked online and I haven't seen any other people having the same issue as me, and if they did the answer didn't help.
Here is my code.
const { Client, GatewayIntentBits } = require('discord.js');
const { Lavalink } = require('discord.js-lavalink');
class MyBot {
// The Discord.js client object that represents our bot
client;
// The ID of the specific person we want to track
userIdToTrack;
// The audio file to play when the specific person joins
audioFile;
constructor(client, userIdToTrack, audioFile) {
// Save the client object and user ID and audio file for later use
this.client = "[bot token]";
this.userIdToTrack = '[discord id]';
this.audioFile = '[file name]';
}
onGuildVoiceJoin(event) {
// Get the member who just joined the voice channel
const member = event.member;
// If the member is the specific person we want to track...
if (member.id === this.userIdToTrack) {
// Get the voice channel that the member joined
const voiceChannel = event.channel;
// Join the voice channel with the bot
voiceChannel.guild.voice.channel.join();
// Play the audio file using Lavalink
lavalink.play(voiceChannel, {
track: '[file name]',
});
const client = new Client({
token: 'bot token]',
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildPresences,
],
});
// Create a new instance of the Lavalink class and connect to the Lavalink nodes
const lavalink = new Lavalink({
client: client,
nodes: [
{ host: 'ratio-w', port: 2334, password: 'youshallnotpass' },
],
});
lavalink.connect();
client.on('ready', () => {
console.log('The bot is ready');
// Create a new instance of the bot, passing in the client object, user ID, and audio file
const bot = new MyBot("bot token", "user id", "file name");
// Listen for voice state update events, which are triggered when a user joins or leaves a voice channel
client.on('voiceStateUpdate', (oldState, newState) => {
// Check if the user we want to track has just joined a voice channel
if (newState.member.id === userIdToTrack && newState.channel) {
// Get the voice channel the user joined
const voiceChannel = newState.channel;
// Join the voice channel with the bot
voiceChannel.join().then(connection => {
// Play the audio file using Lavalink
lavalink.play(voiceChannel, {
track: audioFile,
});
});
}
});
client.on('messageCreate', message => {
if (message.content === 'ping') {
message.reply('hey <#user id>, you STINK!!!!111!');
}
});
client.on('messageCreate', message => {
if (message.content === 'shut up [redacted]') {
message.reply('yeah <#user id> shut up smelly');
}
});
client.on('messageCreate', message => {
if (message.content === 'stop being a nerd [redacted]') {
message.reply('<#user id> be like :nerd:');
}
});
});
process.on('unhandledRejection', (reason, promise) => {
console.log('Unhandled Rejection at:', reason.stack || reason)
// Recommended: send the information to sentry.io
// or whatever crash reporting service you use
})
client.login('[bot id]');}}}
I tried fixing any possible syntax errors, I've tried looking online but no help was found, I've properly started lavalink (I think), I've edited some of the code so that all possible parts are fixed. I've downloaded all possible directories like updating discord.js, node.js, lavalink.js, and more I think.

Discord bot not giving reply [duplicate]

This question already has an answer here:
message.content doesn't have any value in Discord.js
(1 answer)
Closed last month.
Can someone help me out? I'm actually stuck. This the the source code for a bot I made to send GIFs when requesed by a user in a server. The bot is online and connecting to the Discord API.
Discord bot getting online image
The bot should be activated when typed !gif , in keyword the user can type any categorie or emotion they want and the bot would get the gif.
There are no errors shown yet but the bot is still not replying.
No reply image
Bot online image
I am also getting valid reply when used the giphy api url.
const Discord = require('discord.js');
require('dotenv').config();
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("messageCreate", async (message) => {
const tokens = message.content.split(" ");
if (tokens[0] == "!gif") {
const keywords = tokens.slice(1, tokens.length).join(" ");
const url = `http://api.giphy.com/v1/gifs/search?q=tag&api_key=token&limit=5`;
const response = await fetch(url);
const result = await response.json();
const index = Math.floor(Math.random() * result.results.length);
message.channel.send(result.results[index].url);
}
});
client.login(process.env.DISCORD_BOT_TOKEN);
I tried many online fixes none worked I also tried changing version of Discord.js, node-fetch as well as dotenv but none worked.
Discord.js v14
const { Client, GatewayIntentBits, Events } = require('discord.js')
require('dotenv').config()
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessages,
],
})
client.on(Events.MessageCreate, async (message) => {
if (message.author.id === client.user.id) return
const token = message.content.split(' ')
if (token[0] === '!gif')
message.channel.send({
content: `<#${message.author.id}>`,
files: ['https://media.tenor.com/fTTVgygGDh8AAAAM/kitty-cat-sandwich.gif'],
})
})
client.on(Events.ShardReady, () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.login(process.env.TOKEN)

Audio player doesn't play the mp3 discord.js

The audio player doesn't play anything in the voice channel. There is only the green ring around the profile but no sound. Does anyone know why? I'm using discord.js v13
const { Client, Intents, discord } = require('discord.js');
const client = new Client({ intents: [ Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_VOICE_STATES ]});
const { joinVoiceChannel } = require('#discordjs/voice');
const { createAudioPlayer, AudioPlayerStatus, createAudioResource } = require('#discordjs/voice');
client.on("message", message => {
if(message.content.startsWith("!play")){
const channel = message.member.voice.channel
const player = createAudioPlayer();
player.on(AudioPlayerStatus.Playing, () => {
message.channel.send("Now playing")
})
player.on("error", error => {
console.log(error)
})
const resource = createAudioResource('./music.mp3');
player.play(resource)
const connection = joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
const subscription = connection.subscribe(player)
if(subscription){
setTimeout(() => {
subscription.unsubscribe()
}, 15_000)
}
}
})
Your code seems to be fine whats causing the problem is that you need to install ffmpeg-static ( you can find the relating post from the discord.js documentation here ). ffmpeg is used for converting mp3 files to something your discord bot can play. You should also have #discordjs/voice and discord.js but by the looks of it you have.
Please let me know if installing ffmpeg-static solves your problem

DiscordJS V13 doesnt react to dms

I have this very basic code for a very basic discord bot
since the new discord.js version 13 you need to declare intents.
I tried doing that using the bitmap 32767 (basically declaring all intents), however the bot doesnt trigger the "messageCreate" event when a message is send
in the dms it only works in servers.
All privileged gateway intents on the developer site have been set to true.
What am I missing?
const Discord = require("discord.js");
const allIntents = new Discord.Intents(32767);
const client = new Discord.Client({ intents: allIntents });
require("dotenv").config();
const botName = "Miku";
client.once("ready", () => {
//gets executed once at the start of the bot
console.log(botName + " is online!");
});
client.on("messageCreate", (message) => {
console.log("got a message");
});
(async() => {
//bot connects with Discord api
client.login(process.env.TOKEN);
})();
You cannot listen for events in the Direct Messages unless they are direct responses/replies/reactions to the initial message.
For example, you can send a message to new members and wait for a response:
client.on('guildMemberAdd', member =>{
member.send("Welcome to the server!");
message.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
.then((collected) => {
//Now, write your code here that handles the reactions.
});
but there is no way to listen for events within the Direct Messages. As in, client.on... will never fire because of a DM event.

Discord.js v12 code breaks when upgrading to v13

When updating my discord.js to v13 there are many errors I get:
//member.hasPermission is not a function
member.hasPermission("SEND_MESSAGES")
//Cannot send an empty message
channel.send(someEmbed)
//Cannot send an empty message
channel.send({embed: someEmbed})
//Warning: The 'message' event was deprecated, use 'messageCreate' instead
client.on("message", msg => {})
//Cannot send an empty message
channel.send(user)
//[CLIENT_MISSING_INTENTS] Valid intents must be provided for the client
const client = new Client()
//channel.join is not a function
await channel.join()
These don't happen in v12, so how do I fix them in v13?
Discord.js v13 has a lot of changes, and those are only a few. Before updating to v13, you should change the following things
//member.hasPermission("SEND_MESSAGES")
member.permissions.has("SEND_MESSAGES")
//channel.send(someEmbed) / channel.send({embed: someEmbed})
channel.send({ embeds: [someEmbed] }) //make sure it's an array!
//client.on("message", msg => {})
client.on("messageCreate", msg => {})
//channel.send(user)
channel.send(user.toString())
//const client = new Client()
const { Intents, Client } = require("discord.js")
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]}) //more intents may be provided
//await channel.join()
const { joinVoiceChannel } = require("#discordjs/voice") //requires installation
joinVoiceChannel({
channelId: channel.id,
guildId: guild.id,
adapterCreator: guild.voiceAdapterCreator
})
There are some more changes. You can see them in the guide

Categories