How to open a file in folders with discord.js - javascript

I am now coding a Discord bot in a folder named "bot", and I am making it play audio file. But I face a problem. If every files I want to make it play are stored in "bot", the folder will look mess. So I want to create a new folder named "music" in "bot". But I don't know to open the file in this way. Here is a part of my original code:
if (cmd === "play" && message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
const dispatcher = connection.play('01. Snow halation.flac');
dispatcher.on('start', () => {
console.log('Now playing!');
});
dispatcher.on('finish', () => {
console.log('Finished playing!');
connection.disconnect();
});
dispatcher.on('error', console.error);
I want let file "01. Snow halation.flac" be in "music", and how can I make it play?

const dispatcher = connection.play('./music/01. Snow halation.flac');

Related

Discord bot node.js extrenal folder with commands

can someone help me how to make my main.js file read another .js file only with one command?
Here is that command:
client.on('voiceStateUpdate', (prevMember, newMember) => {
console.log('old: ', prevMember)
console.log('new: ', newMember)
//let channel = newMember.channel
let channel = "800656175297200149"
const generalChannel = client.channels.cache.get(channel)
// if it's the first person joining voice, notify everyone
if (!prevMember.channelID) {
generalChannel.send(`#everyone ${newMember} just hopped on voice. WARWEEK Tribe go see what's up!`)
}

discord.js - Audio Bot creation, only plays sound clips that are less than 50KB

Goal
I want to be able to play longer audio files using my discord bot.
Working Code
Using Discord.js and Node.js, I have created a discord bot.
So far my code is able to join a voice call and can only play very short audio files <50KB. Which is great, besides the short file part.
Testing Process: to test different audiofiles, I simply replace the path, during the resource creation, to be the desired audio file.
I have tested 5 short files and it works great! But the three long files >~75KB, that I have, do not work. No errors pop up, it just doesn't play.
const { SlashCommandBuilder } = require('#discordjs/builders');
const { joinVoiceChannel } = require('#discordjs/voice');
const { createAudioPlayer , createAudioResource, StreamType} = require('#discordjs/voice');
const { createReadStream } = require('node:fs');
const { join } = require('node:path');
const { VoiceConnectionStatus, AudioPlayerStatus } = require('#discordjs/voice');
module.exports = {
data: new SlashCommandBuilder()
.setName('jensenrage')
.setDescription('Joins channel and plays jensen\'s rage'),
async execute(interaction){
const { joinVoiceChannel } = require('#discordjs/voice');
const channel = interaction.member.voice.channel
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
const resource = createAudioResource(createReadStream(join(__dirname, '../AudioFiles/short.mp3')), {
inlineVolume : true
});
resource.volume.setVolume(0.2);
const player = createAudioPlayer();
connection.subscribe(player);
player.play(resource)
await interaction.reply( "Enjoy!")
}
}
I have looked into why this is, but most of the answers do not explain why the short files play but the long ones do not.
I am assuming that this line is the the issue, but unsure why.
const resource = createAudioResource(createReadStream(join(__dirname, '../AudioFiles/short.mp3')), {
inlineVolume : true
});
These are my dependencies
--------------------------------------------------
Core Dependencies
- #discordjs/voice: 0.8.0
- prism-media: 1.3.2
- prism-media: 1.3.2
Opus Libraries
- #discordjs/opus: 0.5.3
- opusscript: 0.0.8
Encryption Libraries
- sodium: not found
- libsodium-wrappers: 0.7.10
- tweetnacl: not found
FFmpeg
- version: 4.4.1-essentials_build-www.gyan.dev
- libopus: yes

problem trying to send a client.reply as an embed Message with discord.js

actually i´m working and learning about discord.js and node.js to make a bot, but i have a simple issue, and i don´t know why the embed messages doesn´t work, i tried with the documentarion examples and code of other devs, but in all cases when i try to send the message to a channel, using client.reply(embed) throws me an error saying me that can send an empty message.
i´m using the last version of discord.js (v13.3.1) and i´m using the basic documentation event and the command handlers (works perfectly if i don´t try to send embeds).
This is my index.js and my help.js files:
//This is my index.js i don´t have problem with this but i include it if there are an issue related with this topic.
const fs = require('fs');
const { Client, Collection, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const { token } = require('./config.json');
client.commands = new Collection();
const commandFiles = fs.readdirSync('./Commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./Commands/${file}`);
client.commands.set(command.data.name, command);
}
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
return interaction.reply({ content: 'Parece que ha ocurrido algun problema con el comando.', ephemeral: true });
}
});
const eventFiles = fs.readdirSync('./Events').filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./Events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
client.login(token);
Now the help.js , this is going to be a Command, but i don´t wanna only to code the commands using the SlashCommands, because of it i´m triying to create this as an event:
//This is the help command using an event
const { clientId } = require("../config.json");
const { MessageEmbed } = require("discord.js");
//testx is going to store the embed message
const testx = new MessageEmbed().setTitle('Test').setDescription('Test');
module.exports = {
name: 'messageCreate',
execute(client) {
//This condition determines if isn´t a message of the bot, and if the written command is !!help
if (client.author.id !== clientId && client.content === '!!help') {
//if the condition is true, send the embed message
//client.reply(testx); //the problem is here.
console.log(testx);
}
},
};
And this is the error i got from the terminal:
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (C:\Users\ //...and more info of my dirs
if i print the testx const in my console, i can see the two values i setted in the const filled with the text "Test", i don´t know why isn´t work or what i need to take this to work.
Thanks and i appreciate any help.
In V13, embeds must be sent differently.
client.reply({embeds: [testx]});
I also recommend editing client to interaction in your command files as it may be misleading, or to actually pass the client and interaction, as you'll most likely need to access the client at some point.
Also, you seem to be confusing interactions with messages.
Interactions do not have an author property, you must use user or member.
They also do not have a content property, to get an argument you must use interaction.options
You also, as far as I can see, are not actually deploying your commands. It looks like you've merged the V12 and V13 command handler tutorial together. I reccomend reading this tutorial again, and making sure you're doing it properly for V13.

Downloading a video using fluent-ffmpeg in nodejs and express

I am working on a side project to download videos from Reddit, but they separate video and audio in different files. so i have to merge them first before downloading them in the client. i was able to do all of this as in the following snippet of code.
const ffmpeg = require("fluent-ffmpeg");
const proc = new ffmpeg();
app.post('/download', async (req, res) => {
const audio = "some aduio link";
const video = "some video link";
proc.addInput(video)
.output('${some path}./video.mp4')
.format('mp4')
.on("error", err => console.log(err))
.on('end', () => console.log('Done'));
if(audio) {
proc.addInput(audio);
}
proc.run()
});
using the above code, the video is being download locally in the the server in the specified path.
but i want to download the video in the client browser who sent the request. i tried :
proc.pipe(res);
but it didn't work, it's my first time working with ffmpeg , so it would be nice if someone give me a hint
add writeToStream(res, { end: true }); atn the end to stream
const ffmpeg = require("fluent-ffmpeg");
const proc = new ffmpeg();
app.post('/download', async (req, res) => {
const audio = "some aduio link";
const video = "some video link";
ffmpeg(video).format('mp4')
.on("error", err => console.log(err))
.on('end', () => console.log('Done')).writeToStream(res, { end: true });
});
`
i hope it works

Discord JS (Bot Presence)

So, in Discord, users can have a custom status, however, when I try to set my bot up with one nothing happens...Even though CUSTOM_STATUS is available
I have bot.user.setPresence({ activity: { name: "Testing", type: "CUSTOM_STATUS" }, status: "online" });
inside of the ready event. I was just wondering why this doesn't work and if there is a work around
According to the docs.
Bots cannot set a CUSTOM_STATUS, it is only for custom statuses received from users
The valid types you could choose from are:
PLAYING
STREAMING
LISTENING
WATCHING
Try client.user.setActivity(Your Status)
I am using this and its working fine
If you are using v12 then i cant help you
You should make sure that your setPresence command is in your ready event. For example, this is my ready command:
const {PREFIX} = require('../config.json');
const { Message } = require('discord.js');
const message = require('./message.js');
//must update when new module.exports event happens
const leaveEvent = require('../util/guildMemberRemove');
const invitecounterEvent = require('../util/guildMemberAddinvitecounter');
const modmailEvent = require('../util/modmail');
module.exports = (client, message) => {
//must update when new module.exports event happens
leaveEvent(client);
invitecounterEvent(client);
modmailEvent(client);
console.log(' ');
console.log(`Hi, ${client.user.username} is now online! My Prefix is ${PREFIX}`);
console.log(`Bot has started, with ${client.users.size} users, in ${client.channels.size} channels of ${client.guilds.size} guilds.`);
//client.user.setActivity(`Serving ${client.guilds.size} servers`); (big servers only)
client.user.setActivity('U', { type: 'WATCHING' }) //PLAYING, STREAMING, LISTENING, WATCHING, CUSTOM_STATUS
.then(presence => console.log(`Activity set to: WATCHING ${presence.activities[0].name}`))
.catch(console.error);
console.log(`Ready as ${client.user.tag} to serve in ${client.channels.cache.size} channels on ${client.guilds.cache.size} servers, for a total of ${client.users.cache.size} users.`);
client.generateInvite(['SEND_MESSAGES', 'MANAGE_GUILD', 'MENTION_EVERYONE', 'ADMINISTRATOR',])
.then(link => {
console.log(`Generated bot invite link: ${link}`);
// eslint-disable-next-line no-undef
inviteLink = link;
});
};
The part that should help you is client.user.setActivity('U', { type: 'WATCHING' })
The different types you can do are PLAYING, STREAMING, LISTENING, and WATCHING.

Categories

Resources