I try to create a very small ticket bot.
I would only like that when reacting a support channel opens and nothing else.
This is the code i am working with.
const ember = new Discord.MessageEmbed()
.setColor('#E40819')
.setTitle('β οΈSUPPORT')
.setDescription("Open a Ticket")
let msgEmbed6 = await message.channel.send(ember)
await msgEmbed6.react('β οΈ')
The code inside the if statement will only run if the user reacts, I'm not sure what you mean by 'open a support channel'.
const reaction = msgEmbed6.awaitReactions((reaction, user) => user.id === message.author.id, { max: 1, timeout: TIME_IN_MILLISECONDS });
if (reaction.size > 0) {
// Creates a new text channel called 'Support'
const supportChannel = await message.guild.channels.create('Support', { type: 'text' });
// Stops #everyone from viewing the channel
await supportChannel.updateOverwrite(message.guild.id, { VIEW_CHANNEL: false });
// Allows the message author to send messages to the channel
await supportChannel.updateOverwrite(message.author, { SEND_MESSAGES: true, VIEW_CHANNEL: true });
}
Related
What I'm trying to do is to change the color of an embed when someone adds a reaction.
The struggle I'm currently facing is making it the if statement fire. So haven't gotten very far.
I'm also probably not targeting any specific embed. As the embed (suggestionsEmbed) has been sent multiple times.
EDIT: Updated with current code. This is working except for one thing. No embed other than the last sent can be edited. See what I mean here.
// SUGGESTIONS EMBED - BEGINS
var suggestionsEmbed;
client.on('messageCreate', async message => {
if (message.channel.id === channelSuggestions && !message.author.bot) {
db.add('counterP.plus', 1);
const embed = new MessageEmbed()
.setColor('#f9db73')
.setTitle(`Suggestion #${await db.fetch('counterP.plus') + await db.fetch('counterM.minus')}`)
.setDescription(message.content)
.setAuthor({ name: message.author.username, iconURL: message.author.displayAvatarURL() })
.setTimestamp()
.setFooter({ text: message.author.id });
suggestionsEmbed = await message.channel.send({ embeds: [embed] })
suggestionsEmbed.react('π')
suggestionsEmbed.react('π');
message.delete({ timeout: 0 });
console.log(db.fetch('counterP.plus'));
}
})
// SUGGESTIONS EMBED - ENDS
// CHANGE EMBED COLOR - BEGINS
const suggestionsApproved = 'π’';
const suggestionsDenied = 'π΄';
client.on('messageReactionAdd', (reaction, user) => {
if (reaction.message.channel.id === channelSuggestions) {
if (reaction.emoji.name === suggestionsApproved && reaction.message.id === suggestionsEmbed.id) {
const suggestionsEmbedApproved = new MessageEmbed(suggestionsEmbed.embeds[0]).setColor('#76de51')
suggestionsEmbed.edit({ embeds: [suggestionsEmbedApproved] });
}
}
})
After the introduction of discord.js v13, you need intents declared in your bot. They were introduced so that developers could choose which types of events their bot wanted to receive. You can learn more about Intents here => Gateway Intents. First, you have to add the GUILD_MESSAGE_REACTIONS intent in your client by using:
const { Client, Intents } = require('discord.js')
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS
]
})
Then after that, you can just use your original code to do whatever you want. Although you might get an error saying DiscordAPIError: Invalid Form Body embeds[0].description: This field is required, so to fix that, all you have to do is add the .setDescription() to your edited embed and then send it. Your final code might look something like this:
const { Client, Intents, MessageEmbed } = require('discord.js')
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS
]
})
const suggestionsApproved = 'π’';
const suggestionsDenied = 'π΄';
const channelSuggestions = 'your channel id'
client.on('messageReactionAdd', (reaction, user) => {
if (reaction.message.channel.id === channelSuggestions) { // Check if the reaction was in a particular channel
if (reaction.emoji.name === suggestionsApproved) { // Check which emoji was selected
const suggestionsEmbedApproved = new MessageEmbed()
.setColor('your color')
.setDescription('your description');
suggestionsEmbed.edit({ embeds: [suggestionsEmbedApproved]});
}
}
})
Edit
In response to the new question, here is the answer:
Instead of naming the embed as suggestionsEmbed, the correct way to do it would be to first create an embed with a different name and then use const suggestionsEmbed = await message.channel.send({ embeds: [embedName] }) so that the code will be like:
const embed = new MessageEmbed()
.setTitle('title')
.setDescription('description')
.setColor('color')
const suggestionsEmbed = await message.channel.send({
embeds: [embed]
})
Second Edit
Since you are already using await message.channel.send(), you don't have to use .then(). All you have to do is change this:
const suggestionsEmbed = await message.channel.send({ embeds: [embed] }).then(sentEmbed => {
sentEmbed.react("π")
sentEmbed.react("π")
});
to this:
const suggestionsEmbed = await message.channel.send({ embeds: [embed] })
suggestionsEmbed.react('π')
suggestionsEmbed.react('π')
Editing the Embed:
Use:
const suggestionsEmbedApproved = new MessageEmbed(suggestionsEmbed.embeds[0]).setTitle('asdfasdf')
suggestionsEmbed.edit({ embeds: [suggestionsEmbedApproved] });
So your code is trying to edit the embed rather than the message that the embed is in, (weird I know) but this should work for you.
Discord intents may vary based on your coding but should look similiar
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MESSAGE_REACTIONS],
partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
})
It should be able to pick up those reactions with the below.
const suggestionsApproved = 'insertReactionEmojiName'
const suggestionsDenied = 'insertReactionEmojiName'
const channelSuggestions = 'yaddayadda'
// I would use a different emoji, one that you can get an name from like this
// π which in discord is named :thumbsup:
client.on('messageReactionAdd', (reaction, user) => {
if (reaction.partial) {
// If the message this reaction belongs to was removed, the fetching might result in an API error which should be handled
try {
await reaction.fetch();
} catch (error) {
console.error('Something went wrong when fetching the message:', error);
// Return as `reaction.message.author` may be undefined/null
return;
}
}
const targetMessage = reaction.message
const channel = targetMessage.channel
if (channel.id === channelSuggestions) {
if (reaction.emoji.name === suggestionsApproved) {
const suggestionsEmbedApproved = new MessageEmbed()
.setColor('#1dce1d')
targetMessage.edit({
embeds: [suggestionsEmbedApproved]
})
console.log('fired!')
}
}
})
To edit any embed which was reacted to instead of only the previous sent one, you can use:
const suggestionsEmbedApproved = new MessageEmbed(reaction.message.embeds[0]).setColor("Your color")
reaction.message.edit({ embeds: [suggestionsEmbedApproved] });
client.on("channelDelete", async channel => {
let channelg = await db.fetch(`channel_${channel.guild.id}`);
if (channelg == "on") {
const logs = await channel.guild.fetchAuditLogs({ type: 'CHANNEL_DELETE' }).then(audit => audit.entries.first())
const deleter = await channel.guild.members.fetch(logs.executor.id);
if(deleter.id == channel.guild.owner.user.id) return;
channel.clone(undefined, true, true, "channel delete system").then(async klon => {
await klon.setParent(channel.parent);
await klon.setPosition(channel.position);
channel.guild.owner.send(`channel: **${channel.name}** channel it occurred again.`)
console.log('correct')
})
}
})
allows you to create a channel back when it is deleted
how to make discord js V11 version compatible, V12 was prepared for release.
can you help? I hope everything is clear
You have to replace guild.members.fetch() with guild.fetchMember()
Also, the first argument of Channel.clone() must be an Object.
Instead of undefined, just provide an empty Object, as all options in the first parameter are optional.
channel.clone({}, true, true, "channel delete system")
I'm trying to create a Discord bot that'll create an invite to the first channel of a Guild when it's added to the aforementioned guild and sending it to the console.
My code (it doesn't work):
client.on("guildCreate", guild => {
const channel = Array.from(guild.channels).sort((a, b) => a.calculatedPosition - b.calculatedPosition)[0];
channel.createInvite({
unique: true
})
.then(invite => {
console.log(`Joined to: ${guild.name} Invite: https://discord.gg/${invite.code}`);
})
});
// Listeing to the guildCreate event.
client.on("guildCreate", guild => {
// Filtering the channels to get only the text channels.
const Channels = guild.channels.cache.filter(channel => channel.type == "text");
// Creating an invite.
Channels.first().createInvite({
maxUses: 1,
unique: true
}).then(invite => {
console.log(`[INVITE] I've created an invite for ${guild.id}:${guild.name} - ${invite.url}`);
});
});
I'm setting up server logs on my Discord bot on Discord.js v12.2.0 and I'm currently trying to set up role logging. I've rummaged around on the internet a bit and I can only find solutions for this on older versions of Discord.js, which obviously don't work on v12.2.0. I've set up the guildMemberUpdate event to log nickname changes, but I simply don't know how to do it for roles. It might just be super simple but I'm not sure how I would go about it.
Here's my code so far:
client.on('guildMemberUpdate', (oldMember, newMember) => {
if (!oldMember.nickname && newMember.nickname) {
const membernewnicklog = new Discord.MessageEmbed()
.setAuthor(`${newMember.user.tag}`, `${newMember.user.displayAvatarURL({ format: "png", dynamic: true })}`)
.setDescription(`**${newMember} nickname added**`)
.setFooter(`${newMember.user.username}'s ID: ${newMember.id}`)
.setTimestamp()
.setColor('#ffff00')
.addField("New nickname", newMember.nickname)
client.channels.cache.get('736996028787589201').send(membernewnicklog);
return;
}
if (oldMember.nickname && !newMember.nickname) {
const memberremovenicklog = new Discord.MessageEmbed()
.setAuthor(`${oldMember.user.tag}`, `${oldMember.user.displayAvatarURL({ format: "png", dynamic: true })}`)
.setDescription(`**${oldMember} nickname removed**`)
.setFooter(`${oldMember.user.username}'s ID: ${oldMember.id}`)
.setTimestamp()
.setColor('#f04747')
.addField("Old nickname", oldMember.nickname)
client.channels.cache.get('736996028787589201').send(memberremovenicklog);
return;
}
if (oldMember.nickname && newMember.nickname) {
const memberchangednicklog = new Discord.MessageEmbed()
.setAuthor(`${newMember.user.tag}`, `${newMember.user.displayAvatarURL({ format: "png", dynamic: true })}`)
.setDescription(`**${newMember} nickname changed**`)
.setFooter(`${newMember.user.username}'s ID: ${newMember.id}`)
.setTimestamp()
.setColor('#ff4500')
.addField("Before", oldMember.nickname)
.addField("After", newMember.nickname);
client.channels.cache.get('736996028787589201').send(memberchangednicklog);
return;
}
});
And here's what I'm going for: https://imgur.com/a/FRbTpGQ (an example from another bot)
Any help would be super appreciated. Thanks!
client.on("guildMemberUpdate", (oldMember, newMember) => {
// Old roles Collection is higher in size than the new one. A role has been removed.
if (oldMember.roles.cache.size > newMember.roles.cache.size) {
// Creating an embed message.
const Embed = new discord.MessageEmbed();
Embed.setColor("RED");
Embed.setAuthor(newMember.user.tag, newMember.user.avatarURL());
// Looping through the role and checking which role was removed.
oldMember.roles.cache.forEach(role => {
if (!newMember.roles.cache.has(role.id)) {
Embed.addField("Role Removed", role);
}
});
client.channels.cache.get("ChannelID").send(Embed);
} else if (oldMember.roles.cache.size < newMember.roles.cache.size) {
const Embed = new discord.MessageEmbed();
Embed.setColor("GREEN");
Embed.setAuthor(newMember.user.tag, newMember.user.avatarURL());
// Looping through the role and checking which role was added.
newMember.roles.cache.forEach(role => {
if (!oldMember.roles.cache.has(role.id)) {
Embed.addField("Role Added", role);
}
});
client.channels.cache.get("ChannelID").send(Embed);
}
});
I am using ytdl-core and node-opus to add music functionality to my bot. I am also following a tutorial. Up until I started to add queuing functionality, the bot worked fine. As I integrated the queuing, the bot could still join and leave voice channels, but can't play music. It outputs (node:22116) UnhandledPromiseRejectionWarning: ReferenceError: play is not defined
As per comments on the video, I have tried switching play to playstream. This worked originally, but doesn't help, only outputting that it is not defined.
Here is the command:
if (!message.member.voiceChannel) return message.channel.send("You must be connected to a voice channel.");
if (!args[0]) return message.channel.send("You must supply a __valid__ URL.");
let validate = await ytdl.validateURL(args[0]);
if (!validate) return message.channel.send("You must supply a __valid__ URL.");
let info = await ytdl.getInfo(args[0]);
let data = active.get(message.guild.id) || {};
if (!data.connection) data.connection = await message.member.voiceChannel.join();
if (!data.queue) data.queue = [];
data.guildID = message.guild.id;
data.queue.push ({
songTitle: info.title,
requester: message.author.tag,
url: args[0],
announceChannel: message.channel.id
});
if (!data.dispatcher) play();
else {
message.channel.send(`Added song to queue: ${info.title} || Requested by: ${message.author.id}`);
active.set(message.guild.id, data);
I'd like to be able to still follow the tutorial to fully integrate the queuing.
You didn't define the play() function in previous code, so you also can't use it.
Here is an example of how your play() function could look:
const queue = msg.client.queue;
const ytdl = require('ytdl-core');
async function play(guild, song) {
const serverQueue = await queue.get(guild.id);
if (!song) {
await serverQueue.voiceChannel.leave();
await queue.delete(guild.id);
return;
}
const stream = await ytdl(song.url, {
filter: 'audioonly'
});
const dispatcher = await serverQueue.connection.playStream(stream)
.on('end', async reason => {
if (reason === 'Stream is not generating quickly enough.');
serverQueue.songs.shift('Stream is not generating quickly enough');
await play(guild, serverQueue.songs[0]);
})
.on('error', error => console.error(error));
dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
}
My queue is constructed as following:
const queueConstruct = {
textChannel: msg.channel,
voiceChannel: voiceChannel,
connection: null,
songs: [],
volume: 2,
playing: true
};
It could be that you have to change some lines of code, so that it works for your bot!