Sending more then one mp4 attachment - javascript

I'm trying to create a bot where it sends song snippets, and I am wondering how I would go about sending more than one mp4 with a single command.
const Discord = require('discord.js');
const fs = require('fs');
const { Client, MessageAttachment } = require('discord.js');
const config = require('./config.json');
const { prefix, token } = require('./config.json');
const client = new Client();
const { MessageEmbed } = require('discord.js');
client.commands = new Discord.Collection();
const { Menu } = require('discord.js-menu')
const EventEmitter = require('events');
const { content, author, channel } = message
if (author.bot) {
return const embeds = {
[`${prefix}snip attention`]: {
title: 'attention whore prod. fortune swan',
attachmentPath: './ericsnip/attention_whore/attention.mp4',
[`${prefix}snip attention`]: {
title: 'attention whore prod. fortune swan',
attachmentPath: './ericsnip/attention_whore/attw.mp4',
},
}```
This is what I currently have, I tried to experiment by having the bot go through the file and to send every file that ends with .mp4
[`${prefix}snip hot seat`]: {
title: 'hot seat prod. Alice Gas',
attachmentPath: {const :musicFiles = fs.readdirSync('./ericsnip/hot_seat/').filter(file => file.endsWith(".mp4")),
}
},
But now it doesn't even send anything.

If you take a look at the discord.js documentation, and go to the message options, it tells you that you can provide an array of file options to the message, which means you can attach multiple files.
It is also outlined at the <Channel>.send() method in the documentation.
For example, to send multiple attachments in a message you can do something like:
<Channel>.send({
files: [{
name: "file name here",
attachment: "./path/to/attachment"
},
{
name: "file name here 2",
attachment: "./path/to/attachment_2"
}]
});
I suggest you try relying on the documentation a little more in future. Once you get the hang of it, it is really easy to understand and find what you're looking for, and it gives you all your discord.js related answers.

Related

Sending a random sound file as a response not working

I'm trying to make a talking ben command for my bot, and it just won't work. I want the bot to send an audio clip as a response whenever someone asks a question, and if they don't specify a question, the bot will send a "ben" sound effect. No response to the command in Discord at all.
Here's the code:
ben.js:
const Discord = require('discord.js');
const yes = new Discord.MessageAttachment(
'https://soundboardguy.com/sounds/talking-ben-yes_scachnw/',
);
const no = new Discord.MessageAttachment(
'https://soundboardguy.com/sounds/talking-ben-no/',
);
const laugh = new Discord.MessageAttachment(
'https://soundboardguy.com/sounds/talking-ben-laugh/',
);
const uhh = new Discord.MessageAttachment(
'https://www.101soundboards.com/sounds/726466-uhh',
);
const ben = new Discord.MessageAttachment(
'https://www.101soundboards.com/sounds/726450-ben',
);
module.exports = {
name: 'ben',
description: 'talking ben command',
async execute(client, message, args) {
if (!args[0]) return ben;
let benreplies = [yes, no, laugh, uhh];
let result = Math.floor(Math.random() * benreplies.length);
message.channel.send(replies[result]);
},
};
main.js:
const Discord = require('discord.js');
const client = new Discord.Client({ intents: ['GUILDS', 'GUILD_MESSAGES'] });
const prefix = '.';
const fs = require('fs');
client.commands = new Discord.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.name, command);
}
client.once('ready', () => {
console.log('Blueberry bot is online!');
});
client.on('messageCreate', (message) => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ + /);
const command = args.shift().toLowerCase();
// ...
else if (command === 'ben') {
client.commands.get('ben').execute(message, args, Discord);
}
});
First, you need to make sure that the links to the sound files are valid. You're currently using links pointing to an HTML page, not the mp3 files.
Second, you need to use an object with a files property to send a file. See the MessageOptions. files will also need to be an array. The following will work:
let sounds = [
{
id: 'ben',
link: 'https://soundboardguy.com/wp-content/uploads/2022/03/talking-ben-ben.mp3',
},
{
id: 'laugh',
link: 'https://soundboardguy.com/wp-content/uploads/2022/02/Talking-Ben-Laughing-Sound-Effect-1.mp3',
},
{
id: 'no',
link: 'https://soundboardguy.com/wp-content/uploads/2022/03/Talking-Ben-No-Sound-Effect.mp3',
},
{
id: 'uhh',
link: 'https://soundboardguy.com/wp-content/uploads/2021/06/huh-uhh.mp3',
},
{
id: 'yes',
link: 'https://soundboardguy.com/wp-content/uploads/2022/03/talking-ben-yes_SCacHNW.mp3',
},
];
let randomSound = sounds[Math.floor(Math.random() * sounds.length)];
message.channel.send({
files: [new MessageAttachment(randomSound.link, `${randomSound.id}.mp3`)],
});
The links are incorrect, you used the links that have a user interface, where the user can see the audio, login, see "related" audios etc.. not the actual source audio mp3 file.
For example, that link : https://www.101soundboards.com/sounds/726450-ben is incorrect. Replace it with https://www.101soundboards.com/storage/board_sounds_rendered/726450.mp3 Do the exact same thing with every file and you're ready to go !

Importing variables from other files

I am trying to import a variable from one of my files (File 1) and use it in File 2. I have imported File 2 into File 1 but I am receiving error. My channel ID is correct, in this case you would have to choose the channel so the channel ID is not the issue here.
TypeError: setr.send is not a function
File 1
const Discord = require("discord.js");
const axios = require("axios");
let config = require("../config.json");
module.exports = {
name: "setrestart",
description: "sets the restart channel",
async execute(message, args) {
const perm = new Discord.MessageEmbed()
.setDescription(":x: You do not have permission to use this command.")
.setColor("#E74C3C");
if (!message.guild.me.hasPermission("ADMINISTRATOR"))
return message.channel.send(perm);
if (message.author.id !== "ID")
return message.channel.send(perm);
const channelx =
message.mentions.channels.first() ||
message.guild.channels.cache.find((c) => c.id === args[0]);
if (!channelx)
return message.channel.send(
`:x: Please specify the channel where server restarts will go!`
);
message.reply(`All server restart logs will now go to ${channelx}.`)
},
};
File 2
const Discord = require("discord.js");
const axios = require("axios");
let config = require("../config.json");
let setr = require("./setrestart"); // This is importing file 1
module.exports = {
name: "restart",
description: "send a restart message in status channel",
async execute(message, args) {
const perm = new Discord.MessageEmbed()
.setDescription(":x: You do not have permission to use this command.")
.setColor("#E74C3C");
if (!message.guild.me.hasPermission("ADMINISTRATOR"))
return message.channel.send(perm);
if (message.author.id !== "ID")
return message.channel.send(perm);
const restart = new Discord.MessageEmbed()
.setTitle(" Server Restarted! ")
.setDescription(`F8 connect to ${config.SERVER_URL} `)
.setColor("RANDOM")
.setTimestamp()
.setFooter(`${config.SERVER_LOGO}`);
setr.channelx.send(restart) // This does not work.
},
};
Help is much appreciated.
Edit: I left out the most crucial thing about what I am trying to import.
I am trying to import channelx which is in File 1 and I am trying to use the variable in File 2.
Output
User: /setrestart #channel
Bot: All server restart logs will now go to ${channelx}.
User: /restart
Bot: Embed sent in channelx
The variable channelx is accessible only in the function scope of execute(), you can't import it. Basically after the function goes out of scope the variable is lost. Use a global object, note that the object is destroyed when the program exits. So if you are trying to make some kind of bot's configuration, you want to save the object to a file.
Here is an example of how to properly implement what you are trying to do.
File 1 (file1.js):
// ... Load storage from a JSON file ...
const storage = {};
module.exports = {
name: "setrestart",
description: "sets the restart channel",
async execute(message, args) {
// ... Permission checking ...
const channelx = message.mentions.channels.first() ||
message.guild.channels.cache.find((c) => c.id === args[0]);
if (!channelx) {
return message.channel.send(
`:x: Please specify the channel where server restarts will go!`
);
}
// Store restart channel id per guild
storage[message.guild.id] = channelx.id;
message.reply(`All server restart logs will now go to ${channelx}.`);
// ... Write to the storage JSON file and update it with new data ...
},
};
module.exports.storage = storage;
File 2 (file2.js):
const Discord = require("discord.js");
const file1 = require("./file1.js");
module.exports = {
name: "restart",
description: "send a restart message in status channel",
async execute(message, args) {
// ... Permission checking ...
const restart = new Discord.MessageEmbed()
.setTitle(" Server Restarted! ")
.setColor("RANDOM")
.setTimestamp();
const channelId = file1.storage[message.guild.id];
// If there is no restart channel set, default to the system channel
if (!channelId) channelId = message.guild.systemChannelID;
const channel = await message.client.channels.fetch(channelId);
channel.send(restart);
},
};
Note that I have remove some parts of your code, to make it work on my machine.
Using discord.js ^12.5.3.
I am pretty sure you can't use the module.exports in that way. You should just add the channelx to the exports instead.
using this.channelx = channelx.
This is not how importing and exporting works. Your channelx variable is defined within the execution of a function, and you are not returning it.
I am not sure how the whole Discord API works and what are the shapes that get returned, but you should be able to do something like this:
File 1
module.exports = {
name: "setrestart",
description: "sets the restart channel",
async execute(message, args) {
// ... everything as per your file
message.reply(`All server restart logs will now go to ${channelx}.`);
return channelx;
},
};
File 2
module.exports = {
name: "restart",
description: "send a restart message in status channel",
async execute(message, args) {
// ... everything the same as per your file
const channelx = await setr.execute(message, args);
channelx.send(restart);
},
};
Basically, what is happening here is that the first module exposes a function that figures out your target channel and then returns it.
Once you return it, you can do whatever you want with that.
Please be aware that your first function might not need to be async as you don't have any await instruction.
Read more about scope: https://developer.mozilla.org/en-US/docs/Glossary/Scope

embed adding the same line multiple times

I'm currently working on a command show a user's profile using and embed but every time the command gets used the text gets added again. so if you use the command twice you see the text twice and so on. I've tried to find a solution for about an hour but I can't find anything. I've also tried to rewrite the code multiple times and I currently have this
const { discord, MessageEmbed } = require('discord.js');
const embed = new MessageEmbed();
const users = require('../users.json');
const stand = require('../standsInfo.json');
module.exports = {
name: 'profile',
description: 'show the users profile',
execute(message, args) {
var user = message.author;
var xpNeeded = (users[user.id].level+(users[user.id].level+1))*45;
embed.setTitle(`${user.username}'s profile`);
embed.setThumbnail(user.displayAvatarURL());
embed.addField('level', `${users[user.id].level}`);
embed.addField('experience', `${users[user.id].xp}/${xpNeeded}`);
message.channel.send({embeds: [embed] });
}
}
edit: so. I just realized what was wrong I used addField instead of setField
Move const embed = new MessageEmbed(); to inside the execute scope. Otherwise you will keep editing the same embed and sending again, with added fields
const { discord, MessageEmbed } = require('discord.js');
const users = require('../users.json');
const stand = require('../standsInfo.json');
module.exports = {
name: 'profile',
description: 'show the users profile',
execute(message, args) {
var user = message.author;
var xpNeeded = (users[user.id].level+(users[user.id].level+1))*45;
const embed = new MessageEmbed();
embed.setTitle(`${user.username}'s profile`);
embed.setThumbnail(user.displayAvatarURL());
embed.addField('level', `${users[user.id].level}`);
embed.addField('experience', `${users[user.id].xp}/${xpNeeded}`);
message.channel.send({embeds: [embed] });
}
}

Discord.js Cannot read property 'fetch' of undefined

I just started developing with Javascript and Discord.js a few days ago and got this Error:
TypeError: Cannot read property 'fetch' of undefined
I am trying to make a poll command. This is the Code (I deleted everything else and just wanted it to get the channel out of it):
const Discord = require('discord.js');
const client = new Discord.Collection();
module.exports = {
name: 'poll',
description: 'can make polls',
cooldown: 5,
usage: '[ask] [emoji1] [emoji 2]',
aliases: ['createpoll'],
execute(message, args) {
client.channels.fetch('744582158324072468')
.then (channel => console.log(channel.name))
.catch(console.error);
// message.react(args[1]).then(() => message.react(args[0]));
},
};
I already tried to put it in the Main.js which works:
client.on('message', message => {
if (message.content.startsWith('.poll')) {
client.channels.fetch('744582158324072468')
.then (channel => console.log(channel.name))
.catch(console.error);
}
}
But I want it ion the correct file. This is what I have above the client.on('message', etc.
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token, tprefix, welcomechannel, guildID } = require('./config.json');
const client = new Discord.Client({
fetchAllMembers: true,
});
client.commands = new Discord.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.name, command);
}
const cooldowns = new Discord.Collection();
// update
client.once('ready', () => {
console.log(`${tprefix}Paperbot got geupdated.`);
});
Of course, I googled around and read the documentation but that didn't help.
As I said, I am new to programming and it could be an easy fix, but I would love to fix this problem as fast as possible, thank you very much.
Figured it out. I just needed to add message to client.channels.fetch
Now it is working with this code:
const { tprefix, pollchannel, modchannel } = require('../config.json');
module.exports = {
name: 'poll',
description: 'can make polls',
cooldown: 5,
usage: '[ask] [emoji1] [emoji 2]',
aliases: ['createpoll'],
execute(message) {
message.client.channels.fetch('744582158324072468')
.then (channel => console.log(channel.name))
.catch(console.error);
},
};
Thank you #Jack Towns
You assign client to a new Discord collection at the top of your code.
You are essentially doing Collection.channels.fetch instead of client.channels.fetch.
You need to pass the client from your main file to your commands.

discord.js client.user.setPresence() breaks bot

My bot currently runs fine. I decided to add a 'playing ' status to it. This is the relevant code:
// Import the discord.js modules required
const Discord = require('discord.js');
// Create an instance of a Discord client
const client = new Discord.Client();
// Load config properties from 'config.json'
const config = require("./config.json");
const contest = config.contest;
// Set bots status to playing 'contest' defined in 'config.json'
client.user.setPresence({
game:{
name:contest
},
status:'online'
});
In 'config.json':
{
"contest": "Example Game"
}
When I add this, the bot no longer works, and appears offline. Any ideas?
EDIT:
Source of the information:
https://discord.js.org/#/docs/main/stable/class/ClientUser?scrollTo=setPresence
In the example section:
// Set the client user's presence
client.user.setPresence({ game: { name: 'with discord.js' }, status: 'idle' })
.then(console.log)
.catch(console.error);
You need to read the config, instead of
const config = require(...)
You need
const fs = require("fs");
const config = JSON.parse(fs.readFileSync("config.json"));
const contest = config.contest;
Then
game:{
name:contest
}
Figured it out - this needs to be placed inside an event, otherwise it's just floating code. For example, I placed this inside a
client.on('ready) event.

Categories

Resources