How can I make multi-word argumet. For example a reason for bans or mutes.If I use args[2], args[3], args[4], args[5]... so it's still limited and if nothing is written there, it will write "undefined". So if you knew how to do it, I would be very happy for the answer. :)
const { ReactionCollector } = require("discord.js");
module.exports = {
name: 'ban',
description: "Dočasně zabanuje člena.",
async execute(message, args, Discord, client, chalk, ms){
await message.channel.messages.fetch({limit: 1}).then(messages =>{
message.channel.bulkDelete(messages);
});
const channelId = client.channels.cache.get('802649418087530537');
const author = message.author;
const userName = message.mentions.users.first();
if(!message.member.permissions.has("BAN_MEMBERS")){
message.reply('Nemáš potřebné permisse!')
.then(msg => {
msg.delete({ timeout: 5000 })
});
return;
} else if(!args[1]){
message.reply('!ban <člen> <délka> (<důvod>)')
.then(msg => {
msg.delete({ timeout: 5000 })
});
console.log(chalk.red('[ERROR] Missing args[1]'));
return;
}
if(userName){
const userId = message.guild.members.cache.get(userName.id);
const botId = '799652033509457940';
userId.ban();
const banEmbed = new Discord.MessageEmbed()
.setColor('#a81919')
.setTitle('Ban')
.addFields(
{name:'Člen:', value:`${userId}`},
{name:'Udělil:', value:`${author}`},
{name:'Délka:', value:`${ms(ms(args[1]))}`},
{name:'Důvod:', value:`${args[2]}`},
)
.setTimestamp()
channelId.send(banEmbed)
setTimeout(function () {
message.guild.members.unban(userId);
const unbanEmbed = new Discord.MessageEmbed()
.setColor('#25a819')
.setTitle('Unban')
.addFields(
{name:'Člen:', value:`${userId}`},
{name:'Udělil:', value:`<#${botId}>`},
{name:'Důvod:', value:`Ban vypršel.`},
)
.setTimestamp()
channelId.send(unbanEmbed)
}, ms(args[1]));
console.log(chalk.green(`[INFO] /ban/ ${userId.user.username}, ${ms(ms(args[1]))}`));
}else{
message.channel.send('Nemůžeš zabanovat tohoto člena');
console.log(chalk.red(`[ERROR] /ban/ Can not find target`));
}
}
}
I am assuming that you have defined args correctly. Then you can simply use
args.join(" ");
to seperate each word with spaces.
Related
I want to check if the member is joined to the voice channel that the bot is joined.
The whole code is working, I just want to add that line that I put in code comments.
My code:
const { QueryType } = require('discord-player');
const { MessageEmbed } = require('discord.js');
module.exports = {
name: 'play',
aliases: ['p'],
permissions: ['CONNECT'],
description: 'Plays a music',
voiceChannel: true,
async execute(message, args, cmd, client, Discord, profileData) {
// if the member that used the comamnd is not joined to the voicechannel that the bot is playing music on it, return;
const player = client.player
if (!args[0]) return message.channel.send({ content: `${message.author}, Write the name of the music you want to search. <:Cross:961558777667149874>` });
const res = await client.player.search(args.join(' '), {
requestedBy: message.member,
searchEngine: QueryType.AUTO
});
if (!res || !res.tracks.length) return message.channel.send({ content: `${message.author}, No results found! <:Cross:961558777667149874>` });
const queue = await client.player.createQueue(message.guild, {
metadata: message.channel
});
try {
if (!queue.connection) await queue.connect(message.member.voice.channel)
} catch {
await client.player.deleteQueue(message.guild.id);
return message.channel.send({ content: `<:Cross:961558777667149874> ${message.author}, I can't join audio channel ` });
}
if(client.config.opt.selfDeaf === false) {
let channel = message.member.voice.channel;
const { joinVoiceChannel } = require('#discordjs/voice');
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
selfDeaf: false
});
}
res.playlist ? queue.addTracks(res.tracks) : queue.addTrack(res.tracks[0]);
if (!queue.playing) await queue.play();
},
};
I am not getting any errors.
I am using node.js v16 and discord.js v13
You can use this code to return if the member isn't in the same voice channel as you.
if(message.member.voice.channelId !== message.guild.me.voice.channelId) return;
Then it will return if they aren't in the same channel.
I'm working on something and I need to add ban logging, I tried something but it doesn't send anything.
Any help would be appreciated!
client.on('guildBanAdd', async (guild, user) => {
let Banch = await client.channels.cache.get('ID')
const fetchedLogs = await guild.fetchAuditLogs({
limit: 1,
type: 'MEMBER_BAN_ADD',
});
const banLog = fetchedLogs.entries.first();
if (!banLog) return console.log(`${user.tag} was banned from ${guild.name} but no audit log could be found.`);
const embed = new Discord.MessageEmbed()
.setTitle(`Member Banned`)
.setDescription(`${guild.name}`)
.setColor("RED")
.addField(`Member`, `\n${username}`)
Banch.send(embed)
}
);
This should work
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('guildBanAdd', async (guild, user) => {
const banned = await guild.fetchAuditLogs({
type: 'MEMBER_BAN_ADD',
limit: 1
});
const channel = client.channels.cache.get('ID');
if(!channel) return console.log(`Channel was not found!`);
const userbanned = banned.entries.first();
const { executor, target } = userbanned; // get the user who banned the user and the user that got banned
if(target.id !== user.id) return console.log(`Invalid data in the audit logs!`); // check if the user that got banned in the Audit Logs is the user that is banned
const embed = new Discord.MessageEmbed()
.setTitle(`Member Banned`)
.setDescription(`${guild.name}`)
.setColor("RED")
.addField(`Member`, `${target.username}`);
channel.send(embed).catch(err => {
console.log(err);
});
});
I'm trying to build a music discord bot with yt-search but it gives me undefined whenever I play the song and it joins the voice channel without playing the song. I'm trying to use yt-search to find the video I want or only the URL then pass it to ytdl to run it with the URL given from yt-search but I think I'm wrong in some points. I don't know where, could you please fix my code ?
Image to show the problem:
My code:
const Discord = require("discord.js");
const { prefix, token } = require("./config.json");
const ytdl = require("ytdl-core");
const yts = require("yt-search");
const client = new Discord.Client();
const queue = new Map();
client.once("ready", () => {
console.log("Ready!");
});
client.once("reconnecting", () => {
console.log("Reconnecting!");
});
client.once("disconnect", () => {
console.log("Disconnect!");
});
client.on("message", async message => {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const serverQueue = queue.get(message.guild.id);
if (message.content.startsWith(`${prefix}play`)) {
execute(message, serverQueue);
return;
} else if (message.content.startsWith(`${prefix}skip`)) {
skip(message, serverQueue);
return;
} else if (message.content.startsWith(`${prefix}stop`)) {
stop(message, serverQueue);
return;
} else {
message.channel.send("You need to enter a valid command!");
}
});
async function execute(message, serverQueue) {
const args = message.content.split(" ");
const voiceChannel = message.member.voice.channel;
if (!voiceChannel)
return message.channel.send(
"You need to be in a voice channel to play music!"
);
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has("CONNECT") || !permissions.has("SPEAK")) {
return message.channel.send(
"I need the permissions to join and speak in your voice channel!"
);
}
const r = await yts(args[1,2]);
const video = r.videos.slice( 0, 1 );
console.log(video);
const songInfo = await ytdl.getInfo(video.url);
const song = {
title: songInfo.videoDetails.title,
url: songInfo.videoDetails.video_url,
};
if (!serverQueue) {
const queueContruct = {
textChannel: message.channel,
voiceChannel: voiceChannel,
connection: null,
songs: [],
volume: 5,
playing: true
};
queue.set(message.guild.id, queueContruct);
queueContruct.songs.push(song);
try {
var connection = await voiceChannel.join();
queueContruct.connection = connection;
play(message.guild, queueContruct.songs[0]);
} catch (err) {
console.log(err);
queue.delete(message.guild.id);
return message.channel.send(err);
}
} else {
serverQueue.songs.push(song);
return message.channel.send(`${song.title} has been added to the queue!`);
}
}
function skip(message, serverQueue) {
if (!message.member.voice.channel)
return message.channel.send(
"You have to be in a voice channel to stop the music!"
);
if (!serverQueue)
return message.channel.send("There is no song that I could skip!");
serverQueue.connection.dispatcher.end();
}
function stop(message, serverQueue) {
if (!message.member.voice.channel)
return message.channel.send(
"You have to be in a voice channel to stop the music!"
);
if (!serverQueue)
return message.channel.send("There is no song that I could stop!");
serverQueue.songs = [];
serverQueue.connection.dispatcher.end();
}
function play(guild, song) {
const serverQueue = queue.get(guild.id);
if (!song) {
serverQueue.voiceChannel.leave();
queue.delete(guild.id);
return;
}
const dispatcher = serverQueue.connection
.play(ytdl(song.url))
.on("finish", () => {
serverQueue.songs.shift();
play(guild, serverQueue.songs[0]);
})
.on("error", error => console.error(error));
dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
serverQueue.textChannel.send(`Start playing: **${song.title}**`);
}
client.login(token);
There are two errors. I'm not sure what you think args[1,2] is but it's the same as args[2] which is the third item of the args array. By reading your code, I think you want to use a string here, the search term. By removing the first item (the command) from the args array and joining the rest of them, you will receive a string you can use as keywords. Check out the example below:
const message = { content: '!play some music I want'}
const args = message.content.split(' ')
console.log({ args })
// => ["!play", "some", "music", "I", "want"]
console.log({ 'args[1, 2]': args[1, 2] })
// => "music"
console.log({ 'search': args.slice(1).join(' ') })
// => "some music I want"
The other error is that await yts(query) returns an array of results and when you define the video variable you use r.videos.slice(0, 1). The .slice() method returns a new array with the first item of r.videos.
As the video variable is an array, video.url is undefined. You could fix it by using the first item instead as it will have a url property. You should also check if there are any search results.
Check out the updated code below:
async function execute(message, serverQueue) {
const args = message.content.split(' ');
const voiceChannel = message.member.voice.channel;
if (!voiceChannel)
return message.channel.send(
'You need to be in a voice channel to play music!',
);
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT') || !permissions.has('SPEAK')) {
return message.channel.send(
'I need the permissions to join and speak in your voice channel!',
);
}
const query = args.slice(1).join(' ');
const results = await yts(query);
if (!results.videos.length)
return message.channel.send(`No results for \`${query}\``);
const firstVideo = results.videos[0];
const songInfo = await ytdl.getInfo(firstVideo.url);
const song = {
title: songInfo.videoDetails.title,
url: songInfo.videoDetails.video_url,
};
console.log(song);
if (!serverQueue) {
// ...
// ...
I'm having a problem with my anti ping system. It works alone, but with the other stuff (If (data) ... } else if (!data) {...) they overlap. If I add the if (comrade) on top of the if (data), other commands stop working but the anti ping works. Here is my code (also I get no errors):
const pinger = new Set();
const pinged = new Set();
client.on('message', async (message) => {
const data = await prefix.findOne({
GuildID: message.guild.id
});
let embed = new Discord.MessageEmbed();
const messageArray = message.content.split(" ");
const cmd = messageArray[0];
const args = messageArray.slice(1);
if (data) {
const prefix = data.Prefix;
if (!message.content.startsWith(prefix)) return;
const commandfile = client.commands.get(cmd.slice(prefix.length).toLowerCase() || client.commands.get(client.aliases.get(cmd.slice(prefix.length).toLowerCase())));
commandfile.run(client, message, args);
} else if (!data) {
const prefix = "!";
if (!message.content.startsWith(prefix)) return;
const commandfile = client.commands.get(cmd.slice(prefix.length).toLowerCase() || client.commands.get(client.aliases.get(cmd.slice(prefix.length).toLowerCase())));
commandfile.run(client, message, args);
}
let comrade = message.guild.member(message.mentions.users.first())
let mrole = message.guild.roles.cache.find(r => r.name === 'dont ping again');
let comradeid = message.guild.members.cache.get(comrade.user.id);
let authorid = message.guild.members.cache.get(message.author.id);
if (comrade) {
if (message.author.bot) return;
if (pinger.has(authorid), pinged.has(comradeid)) {
message.guild.channels.cache.forEach(f => {
f.overwritePermissions([{
id: mrole.id,
deny: ['SEND_MESSAGES']
}]);
})
authorid.roles.add(mrole)
setTimeout(() => {
authorid.roles.remove(mrole)
}, 30000)
embed.setTitle('BRUH')
embed.setDescription('YOU CANT MASS PING THAT PERSON')
embed.setColor('RED')
message.channel.send(embed)
} else {
if (!mrole) message.guild.roles.create({ data: { name: 'dont ping again' } });
if (comrade.roles.cache.find(role => role.name === 'dont ping me')) {
pinged.add(comradeid)
setTimeout(() => {
pinged.delete(comradeid)
}, 15000)
pinger.add(authorid)
setTimeout(() => {
pinger.delete(authorid)
}, 15000);
}
}
}
})
It uses a mongoDB (database) because I want my bot to have a change its prefix for other guilds command (which works perfectly). Here the commands work (the if (data) where it checks for a prefix), but the anti pinging system doesn't. I've tried a lot of stuff, but they end up not working. Thanks in advance.
making a discord bot in javascript with visual studio code but for some reason getting an error. I'll show you the code that is relevant first.
Overall trying to get a temporary mute function to work and I want to add it to the available commands which pops up when you hit !help. Table looks like this:
!help
classes I'm working with
Here is the index.js:
const { Client, Collection } = require("discord.js");
const { config } = require("dotenv");
const fs = require("fs");
const client = new Client({
disableEveryone: true
});
client.commands = new Collection();
client.aliases = new Collection();
client.categories = fs.readdirSync("./commands/");
config({
path: __dirname + "/.env"
});
["command"].forEach(handler => {
require(`./handlers/${handler}`)(client);
});
client.on("ready", () => {
console.log(`Hi, ${client.user.username} is now online!`);
client.user.setPresence({
status: "online",
game: {
name: "you get boosted❤️",
type: "Watching"
}
});
});
client.on("message", async message => {
const prefix = "!";
if (message.author.bot) return;
if (!message.guild) return;
if (!message.content.startsWith(prefix)) return;
if (!message.member) message.member = await message.guild.fetchMember(message);
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const cmd = args.shift().toLowerCase();
if (cmd.length === 0) return;
let command = client.commands.get(cmd);
if (!command) command = client.commands.get(client.aliases.get(cmd));
if (command)
command.run(client, message, args);
});
client.login(process.env.TOKEN);
Here is tempmute:
bot.on('message', message => {
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case 'mute':
var person = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[1]));
if(!person) return message.reply("I CANT FIND THE USER " + person)
let mainrole = message.guild.roles.find(role => role.name === "Newbie");
let role = message.guild.roles.find(role => role.name === "mute");
if(!role) return message.reply("Couldn't find the mute role.")
let time = args[2];
if(!time){
return message.reply("You didnt specify a time!");
}
person.removeRole(mainrole.id)
person.addRole(role.id);
message.channel.send(`#${person.user.tag} has now been muted for ${ms(ms(time))}`)
setTimeout(function(){
person.addRole(mainrole.id)
person.removeRole(role.id);
console.log(role.id)
message.channel.send(`#${person.user.tag} has been unmuted.`)
}, ms(time));
break;
}
});
Here is the help.js which lists all commands
const { RichEmbed } = require("discord.js");
const { stripIndents } = require("common-tags");
module.exports = {
name: "help",
aliases: ["h"],
category: "info",
description: "Returns all commands, or one specific command info",
usage: "[command | alias]",
run: async (client, message, args) => {
if (args[0]) {
return getCMD(client, message, args[0]);
} else {
return getAll(client, message);
}
}
}
function getAll(client, message) {
const embed = new RichEmbed()
.setColor("RANDOM")
const commands = (category) => {
return client.commands
.filter(cmd => cmd.category === category)
.map(cmd => `- \`${cmd.name}\``)
.join("\n");
}
const info = client.categories
.map(cat => stripIndents`**${cat[0].toUpperCase() + cat.slice(1)}** \n${commands(cat)}`)
.reduce((string, category) => string + "\n" + category);
return message.channel.send(embed.setDescription(info));
}
function getCMD(client, message, input) {
const embed = new RichEmbed()
const cmd = client.commands.get(input.toLowerCase()) || client.commands.get(client.aliases.get(input.toLowerCase()));
let info = `No information found for command **${input.toLowerCase()}**`;
if (!cmd) {
return message.channel.send(embed.setColor("RED").setDescription(info));
}
if (cmd.name) info = `**Command name**: ${cmd.name}`;
if (cmd.aliases) info += `\n**Aliases**: ${cmd.aliases.map(a => `\`${a}\``).join(", ")}`;
if (cmd.description) info += `\n**Description**: ${cmd.description}`;
if (cmd.usage) {
info += `\n**Usage**: ${cmd.usage}`;
embed.setFooter(`Syntax: <> = required, [] = optional`);
}
return message.channel.send(embed.setColor("GREEN").setDescription(info));
}
ERROR:
Error message, bot not defined.
Overall trying to get a temporary mute function to work and I want to add it to the available commands which pops up when you hit !help. Table looks like this:
!help
I think the tempmute simply doesn't work because you use bot.on() instead of client.on(), which was defined in the index.js. I can't help you for the rest but everything is maybe related to this.