DiscordJS Play audio file on voice channel - javascript

I followed some tutorials and mixed some of the codes around and it works but I'm having difficulty understanding async with message.guild.channels.forEach no matter how i play to change it.
I want the bot to join only the voice channel where the user typed 'test' without running on all voice channels.
thank you
exports.run = async (client, message, args, level) => {
async function play(channel) {
await channel.join().then(async (connection) => {
let dispatcher = await connection.playFile('./img/aniroze.mp3');
await dispatcher.on('end', function () {
message.channel.send("🎧 **x** 🎧").then(sentEmbed => {
sentEmbed.react("👍")
sentEmbed.react("👎")
channel.leave();});
});
});
}
let timer = 10000;
message.guild.channels.forEach(async (channel) => {
if (channel.type == 'voice' && channel.members.size > 1) {
const embed2 = new Discord.RichEmbed()
.setTitle('🎧 🎧')
.setColor("#3498DB")
.setThumbnail(`${message.author.displayAvatarURL}`)
.setTimestamp()
message.channel.send(embed2);
setTimeout(function () {
play(channel);
}, timer);
}});
setTimeout(function () {
}, timer);
};
exports.conf = {
enabled: true,
aliases: ['test'],
guildOnly: true,
permLevel: 'User'
}

If you want the bot to join the voice channel of the user that sent the command then use this:
const voiceChannel = message.member.voiceChannel
if (!voiceChannel) return message.reply('you are not in a voice channel')
voiceChannel.join()
Note: This is a discord.js v11 answer, for v12 replace member.voiceChannel with member.voice.channel

Related

guild.member.hasPermission is not a function

I was rummaging through an old source of discord.js from v11, and merged most of it to v12, mind you this script is erroring within the ready event, I'd prefer not to put it elsewhere.
This is what I have for now:
client.on('ready', async () => {
log.success(`Authenticated as ${client.user.tag}`);
client.user.setPresence({
activity: {
name: env.PRESENCE_ACTIVITY,
type: env.PRESENCE_TYPE.toUpperCase(),
},
});
const guild = client.guilds.cache.find((g) => g.id === '000000000');
if (!guild)
return console.log(`Can't find any guild with the ID "${env.GUILD_ID}"`);
if (guild.member.hasPermission('ADMINISTRATOR', false)) {
log.success("Bot has the 'ADMINISTRATOR' permission");
} else
log.warn("Bot does not have 'ADMINISTRATOR' permission");
client.guilds.cache
.get(env.GUILD_ID)
.roles.fetch()
.then((roles) => {
goodieRole = roles.cache.get(env.GOODIE_ROLE_ID);
});
});
There is no member property on guilds. If you want to get the bot as a member of that guild, you can fetch() them from guild.members. If you're using discord.js v12, you can use the hasPermission() method to check if the bot has an ADMINISTRATOR flag:
client.on('ready', async () => {
log.success(`Authenticated as ${client.user.tag}`);
client.user.setPresence({
activity: {
name: env.PRESENCE_ACTIVITY,
type: env.PRESENCE_TYPE.toUpperCase(),
},
});
const guild = client.guilds.cache.get(env.GUILD_ID);
if (!guild)
return console.log(`Can't find any guild with the ID "${env.GUILD_ID}"`);
let botMember = await guild.members.fetch(client.user);
if (botMember.hasPermission('ADMINISTRATOR', false)) {
log.success("Bot has the 'ADMINISTRATOR' permission");
} else
log.warn("Bot does not have 'ADMINISTRATOR' permission");
// ...

Set channel permissions to only allow the ticket opener and admin to view the channel - Discord ticket system

I'm having an issue with my ticket discord system where the lock react emoji doesn't actually lock the text chat. The overall slash command executes and my second react emoji, which is an X used to delete the text chat works, but the locking system does not.
The structure is written that any member within the discord will use the /ticket command in "open a ticket" chat and the bot will then create a ticket in a new text channel and name it ticket-userid, and once an admin comes to help the ticket he will then react to the "lock" emoji and lock to channel where only him and the member can see it, no one else. But it's not executing like this, only everything else except this. Does anyone have any idea?
ticket.js
name: 'ticket',
aliases: [],
permissions: [],
description: 'open a ticket!',
async execute(interaction) {
// message.guild is now interaction.guild
const channel = await interaction.guild.channels.create(
// message.author.tag is now interaction.user.tag
`ticket: ${interaction.user.tag}`,
);
channel.setParent('932177870661509141');
// message.guild is now interaction.guild
channel.permissionOverwrites.edit(interaction.guild.id, {
SEND_MESSAGES: false,
VIEW_CHANNEL: false,
});
// message.author is now interaction.member
channel.permissionOverwrites.edit(interaction.member, {
SEND_MESSAGES: true,
VIEW_CHANNEL: true,
});
// we're sending a reply with interaction.reply
// and use fetchReply so we can delete it after 7 seconds
const reply = await interaction.reply({
content: `We will be right with you! ${channel}`,
fetchReply: true,
});
setTimeout(() => {
reply.delete();
}, 7000);
const reactionMessage = await channel.send(
'Thank you for contacting support!',
);
try {
await reactionMessage.react('🔒');
await reactionMessage.react('🛑');
} catch (err) {
channel.send('Error sending emojis!');
throw err;
}
// you should also check if the user reacted is a bot
const filter = (reaction, user) =>
!user.bot &&
interaction.guild.members.cache
.get(user.id)
.permissions.has('ADMINISTRATOR');
const collector = reactionMessage.createReactionCollector({
dispose: true,
filter,
});
collector.on('collect', (reaction, user) => {
switch (reaction.emoji.name) {
case '🔒':
channel.permissionOverwrites.edit(interaction.member, {
SEND_MESSAGES: false,
});
break;
case '🛑':
channel.send('Deleting this channel in 5 seconds!');
setTimeout(() => channel.delete(), 5000);
break;
}
});
},
};
index.js
const fs = require('fs');
const { Client, Collection, Intents, DiscordAPIError } = require('discord.js');
const { token } = require('./config.json');
const prefex = '!';
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
],
});
client.commands = new Collection();
client.events = 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.name, command);
}
client.once('ready', () => {
console.log("You are now connected to Boombap Tickets!");
});
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: 'There was an error while executing this command!',
ephemeral: true,
});
}
});
client.login(token);
channel.permissionOverwrites.edit(interaction.member, {
SEND_MESSAGES: false
});
In this code, the bot sets permission overwrite for reacted person(actually a mod) to restrict sending messages.
But since admins have full privileges, it has no effect.
Instead, you need to restrict #everyone of viewing the channel.
Also you can put all the role id to restrict access in an array and iterate over it to edit overwrites and restrict their access.
So the code would be:
channel.permissionOverwrites.edit(interaction.guild.id, {
VIEW_CHANNEL: false
});
['headchef-role-id', 'cook-role-id'].forEach(roleId => {
channel.permissionOverwrites.edit(roleId, {
VIEW_CHANNEL: false
});
});
Also when opening, your code restricts #everyone to view and send. But since you want #everyone to view the channel, set overwrites code would be:
channel.permissionOverwrites.edit(interaction.member, {
VIEW_CHANNEL: true,
SEND_MESSAGES: false
});
channel.permissionOverwrites.edit(interaction.guild.id, {
VIEW_CHANNEL: true,
SEND_MESSAGES: false
});
Also please note that when creating a channel, its name isn't ticket: user#1234. It would be ticket-user1234.

all the embeds in my code stopped working + mute command error

first issue: all the embeds in my code stopped working - no matter what command I try to run if it has an embed in it I get the error: DiscordAPIError: Cannot send an empty message
second issue: I'm currently programming a mute command with a mongoDB database, it puts everything I need it in the database however if I try to mute someone it ends up only muting them for 1s by default, basically completely ignoring the second argument. heres what I want the command to do: when you mute someone you need to provide the user id and a time (works in ms) + reason then it puts it in the data base.
here's the code: [P.S. Im not getting an error message, it just doesnt work properly like I want it to]
const mongo = require('../mongo.js')
const muteSchema = require('../schemas/mute-schema.js')
const Discord = require('discord.js')
const ms = require ("ms")
module.exports = {
commands: 'mute',
minArgs: 2,
expectedArgs: "<Target user's #> <time> <reason>",
requiredRoles: ['Staff'],
callback: async (message, arguments) => {
const target = message.mentions.users.first() || message.guild.members.cache.get(arguments[0])
if (!target) {
message.channel.send('Please specify someone to mute.')
return
}
const { guild, channel } = message
arguments.shift()
const mutedRole = message.guild.roles.cache.find(role => role.name === 'muted');
const guildId = message.guild.id
const userId = target.id
const reason = arguments.join(' ')
const user = target
const arg2=arguments[2]
const mute = {
author: message.member.user.tag,
timestamp: new Date().getTime(),
reason,
}
await mongo().then(async (mongoose) => {
try {
await muteSchema.findOneAndUpdate(
{
guildId,
userId,
},
{
guildId,
userId,
$push: {
mutes: mute,
},
},
{
upsert: true,
}
)
} finally {
mongoose.connection.close()
}
})
message.delete()
user.roles.add(mutedRole)
setTimeout(function() {
user.roles.remove(mutedRole)
}, ms(`${arg2}`));
try{
message.channel.send(`works`)
}
catch(error){
const embed3 = new Discord.MessageEmbed()
.setDescription(`✅ I Couldn't DM them but **${target} has been muted || ${reason}**`)
.setColor('#004d00')
message.channel.send({ embeds: [embed3] });
}
},
}
djs v13 has a new update where you need to send embeds like this:
const exampleEmbed = new Discord.MessageEmbed()
.setTitle('example')
.setDescription('example')
.setColor('RANDOM')
message.channel.send({embed: [exampleEmbed]});

discord.js error "channel is not defined"

So im making a mute command which creates a mute role and gives it to the mentioned user, and currently i am getting an error: channel is not defined,
I do not know how to fix this error and i need help with this
module.exports = class MuteCommand extends BaseCommand {
constructor() {
super('mute', 'moderation', []);
}
async run(client, message, args) {
if (!message.member.hasPermission("MUTE_MEMBERS")) return message.channel.send("You do not have Permission to use this command.");
if (!message.guild.me.hasPermission('MANAGE_ROLES')) return message.channel.send("I do not have Permission to mute members.");
let reason = args.slice(1).join(' ');
let roleName = 'Muted';
let muteRole = message.guild.roles.cache.find(x => x.name === roleName);
if (typeof muteRole === undefined) {
guild.roles.create({ data: { name: 'Muted', permissions: ['SEND_MESSAGES', 'ADD_REACTIONS'] } });
} else {
}
muteRole = message.guild.roles.cache.find(x => x.name === roleName);
channel.updateOverwrite(channel.guild.roles.muteRole, { SEND_MESSAGES: false });
const mentionedMember = message.mentions.member.first() || message.guild.members.cache.get(args[0]);
const muteEmbed = new Discord.MessageEmbed()
.setTitle('You have been Muted in '+message.guild.name)
.setDescription('Reason for Mute: '+reason)
.setColor('#6DCE75')
.setTimestamp()
.setFooter(client.user.tag, client.user.displayAvatarURL())
.setImage(message.mentionedMember.displayAvatarURL());
if (!args[0]) return message.channel.send('You must mention a user to mute.');
if (!mentionedMember) return message.channel.send('The user mentioned is not in the server.');
if (mentionedMember.user.id == message.author.id) return message.channel.send('You cannot mute yourself.');
if (mentionedMember.user.id == client.user.id) return message.channel.send('You cannot mute me smh.');
if (!reason) reason = 'No reason given.';
if (mentionedMember.roles.cache.has(muteRole.id)) return message.channel.send('This user has already been muted.');
if (message.member.roles.highest.position <= mentionedMember.roles.highest.position) return message.chanel.send('You cannot mute someone whos role is higher and/or the same as yours');
await mentionedMember.send(muteEmbed).catch(err => console.log(err));
await mentionedMember.roles.add(muteRole.id).catch(err => console.log(err).then(message.channel.send('There was an issue while muting the mentioned Member')));
}
}
I beileive that there could be even more errors than i think in this code as I am fairly new to coding.
You have used "channel" without declaring it. Hence, it is undefined.
check your line "channel.updateOverwrite(channel.guild.roles.muteRole, { SEND_MESSAGES: false });"
const { Client, Intents } = require('discord.js')
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', msg => {
if (msg.content === 'ping') {
msg.channel.send('pong');
});
});
Please refer the below links
Discord.JS documentation: https://github.com/discordjs/discord.js
Stack-overflow answer: Discord.js sending a message to a specific channel

How to make bot send message to another channel after reaction | Discord.js

How do I make it so that when someone reacts with the first emoji in this command, the bot deletes the message and sends it to another channel?
Current Code:
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
if (!message.member.hasPermission("MANAGE_MESSAGES"))
return message.channel.send("You are not allowed to run this command.");
let botmessage = args.join(" ");
let pollchannel = bot.channels.cache.get("716348362219323443");
let avatar = message.author.avatarURL({ size: 2048 });
let helpembed = new Discord.MessageEmbed()
.setAuthor(message.author.tag, avatar)
.setColor("#8c52ff")
.setDescription(botmessage);
pollchannel.send(helpembed).then(async msg => {
await msg.react("715383579059945512");
await msg.react("715383579059683349");
});
};
module.exports.help = {
name: "poll"
};
You can use awaitReactions, createReactionCollector or messageReactionAdd event, I think awaitReactions is the best option here since the other two are for more global purposes,
const emojis = ["715383579059945512", "715383579059683349"];
pollchannel.send(helpembed).then(async msg => {
await msg.react(emojis[0]);
await msg.react(emojis[1]);
//generic filter customize to your own wants
const filter = (reaction, user) => emojis.includes(reaction.emoji.id) && user.id === message.author.id;
const options = { errors: ["time"], time: 5000, max: 1 };
msg.awaitReactions(filter, options)
.then(collected => {
const first = collected.first();
if(emojis.indexOf(first.emoji.id) === 0) {
msg.delete();
// certainChannel = <TextChannel>
certainChannel.send(helpembed);
} else {
//case you wanted to do something if they reacted with the second one
}
})
.catch(err => {
//time up, no reactions
});
});

Categories