Get The Member Who Invited Bot - javascript

I'm trying to get the GuildMember object of whoever invited the bot using the guildCreate event.
const fetchedLogs = await message.guild.fetchAuditLogs({
limit: 1,
type: ''
})
Not sure if I'm on the right path, however, if I am, what argument do I pass for type?

here's the code I use to find the user who invited the bot, which is good enough for my purposes
bot.on('guildCreate', (guild) => {
console.log(`event guildCreate: ${guild.name} ${guild.id}`);
guild.fetchAuditLogs({ limit: 1, type: 28 }) // type 28 is "add bot"
.then(audit => {
let userID = audit.entries.first().executor.id;
// do something here
})
.catch(console.error);
});

Related

How can i get my discord.js v14 bot to stop saying "The application did not respond" if the slash command works?

i have multiple commands that work perfectly fine but i always get this message in return.
here is the code for that command. it works perfectly fine i guess it just doesn't respond to the interaction even though i feel like it should be?
how can i get it to ignore this message or reply properly?
const Discord = require('discord.js');
const { EmbedBuilder, SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
// command name
.setName('totalfrozencheckouts')
// command description
.setDescription('Add up every message in the frozen checkouts channel after a specific message ID')
.addStringOption(option =>
option.setName('messageid')
.setDescription('The message ID')
.setRequired(true)),
async execute(interaction) {
const channel = '<#' + process.env.FROZENCHECKOUTS + '>';
const messageId = interaction.options.getString("messageid");
// Check if the channel mention is valid
if (!channel.startsWith('<#') || !channel.endsWith('>')) {
return interaction.channel.send(`Invalid channel mention. Please use the format: ${this.usage}`);
}
// Extract the channel ID from the channel mention
const channelId = channel.slice(2, -1);
// Try to fetch the messages from the requested channel and message ID
interaction.guild.channels.cache.get(channelId).messages.fetch({ after: messageId })
.then(messages => {
// Create an array of the message contents that are numbers
const numbers = messages.map(message => message.content).filter(content => !isNaN(content));
// Check if there are any messages
if (numbers.length === 0) {
return interaction.channel.send(`No messages were found in ${channel} after message ID https://discord.com/channels/1059607354678726666/1060019655663689770/${messageId}`);
}
// Adds up the messages
const sum = numbers.reduce((accumulator) => accumulator + 1, 1);
// Create an embed object
const embed = new EmbedBuilder()
.setColor(0x4bd8c1)
.setTitle(`Total Checkouts in #frozen-checkouts for today is:`)
.addFields(
{name: 'Total Checkouts', value: sum.toString() , inline: true},
)
.setThumbnail('https://i.imgur.com/7cmn8uY.png')
.setTimestamp()
.setFooter({ text: 'Frozen ACO', iconURL: 'https://i.imgur.com/7cmn8uY.png' });
// Send the embed object
interaction.channel.send({embeds: [embed]});
})
.catch(error => {
console.error(error);
interaction.channel.send('An error occurred while trying to fetch the messages. Please try again later.');
});
}
}
I don't really know what to try because it literally works I just don't know how to get it to either ignore that message or respond with nothing. It doesn't break the bot its just annoying to look at.
Use interaction.reply instead of interaction.channel.send to reply.

Discord js v12 Add rights to a channel if user reacts to a specific message

I have a problem that I can't solve:
Every time someone reacts to a specific message a channel gets created, and then the person who reacted first is the only one who has the permissions to see this channel. I set the max amount of reactions to "2", and I want it so that the second person who reacts with the message also gets permissions to see the created channel, but I don't know how to do it. Does somebody has an example?
This is what I currently have:
message.guild.channels.create("Busfahrer", {
type: "text",
parent: category,
permissionOverwrites: [
{
id: message.guild.id,
allow: ['SEND_MESSAGES', 'EMBED_LINKS', 'ATTACH_FILES', 'READ_MESSAGE_HISTORY'],
deny: ['VIEW_CHANNEL'],
}
]
})
Keep track of who reacts first and second and only give it to the second person:
const collector = reactionMessage2p.createReactionCollector(filter2p, {max: 2, time: 20000, errors: ['time'] })
let reactedUsers = []
collector.on("collect", (reaction, user) => {
reactedUsers.push(user.id)
})
collector.on("end", async () => {
let targetUser = reactedUsers[1]
// channel is the channel you create
channel.updateOverwrite(targetUser, {
VIEW_CHANNEL: true
})
})
I got some of this code from your other question

cannot read property of 'channels' of undefined discord.js

const reason = args.slice(0).join(" ");
if (!reason) return message.channel.send('Reason for ticket?');
const user = message.guild.member(message.author);
const ticket = db.fetch(`Ticket_user_${user.id}`)
if(ticket) message.channel.send("You already made a ticket senpai! Close your old ticket.");
const channel = message.guild.channels.cache.find
(channel => channel.name === 'ticket')
if (!channel)
guild.channels.create('ticket', {
type: 'text',
permissionOverwrites: [
{
id: message.guild.id,
deny: ['VIEW_CHANNEL'],
},
{
id: message.author.id,
allow: ['VIEW_CHANNEL'],
},
],
})
.then(console.log)
.catch(err => {
message.channel.send("An error occurred while running the command. Please report this error to the support server:"+ err)
return;
})
db.add(`Ticket_user_${user.id}`)
const time = "3"
setTimeout(() => {
const embed = new Discord.MessageEmbed()
.setTitle(`Ticket#0001`)
.setDescription(`Reason: ${reason}`)
.addField("Welcome to my ticket senpai!! We are waiting for staff")
.setColor("PURPLE")
message.channel.send(embed)
}, ms(time))
}
}
I'm making a ticket system for my bot and ik you people smart because top.gg won't help
Thank you for the help this will help my bot and my code and make me smart plus I'm removing the dot becccause of downvote ig
Here in this code
if (!channel){
guild.channels.create('ticket', { //...... rest of the code
You didn't define guild. Try replacing guild with message.guild
Like this:
if (!channel){
message.guild.channels.create('ticket', { //.... rest of the code
Also, please remove the unnecessary part (dots) from the question

I'm trying to create a channel named like user args. [DISCORD.JS V12]

It just gives me an error that the function message.guild.channels.create does not work because it's not a correct name.
My intention is to create a command where you will be asked how the channel you want to create be named. So it's ask you this. After this you send the wanted name for the channel. Now from this the bot should name the channel.
(sorry for bad english and low coding skills, im a beginner)
module.exports = {
name: "setreport",
description: "a command to setup to send reports or bugs into a specific channel.",
execute(message, args) {
const Discord = require('discord.js')
const cantCreate = new Discord.MessageEmbed()
.setColor('#f07a76')
.setDescription(`Can't create channel.`)
const hasPerm = message.member.hasPermission("ADMINISTRATOR");
const permFail = new Discord.MessageEmbed()
.setColor('#f07a76')
.setDescription(`${message.author}, you don't have the permission to execute this command. Ask an Admin.`)
if (!hasPerm) {
message.channel.send(permFail);
}
else if (hasPerm) {
const askName = new Discord.MessageEmbed()
.setColor(' #4f6abf')
.setDescription(`How should the channel be called?`)
message.channel.send(askName);
const collector = new Discord.MessageCollector(message.channel, m => m.author.id === message.author.id, { max: 1, time: 10000 });
console.log(collector)
var array = message.content.split(' ');
array.shift();
let channelName = array.join(' ');
collector.on('collect', message => {
const created = new Discord.MessageEmbed()
.setColor('#16b47e')
.setDescription(`Channel has been created.`)
message.guild.channels.create(channelName, {
type: "text",
permissionOverwrites: [
{
id: message.guild.roles.everyone,
allow: ['VIEW_CHANNEL','READ_MESSAGE_HISTORY'],
deny: ['SEND_MESSAGES']
}
],
})
.catch(message.channel.send(cantCreate))
})
}
else {
message.channel.send(created)
}
}
}
The message object currently refers to the original message posted by the user. You're not declaring it otherwise, especially seeing as you're not waiting for a message to be collected before defining a new definition / variable for your new channel's name.
NOTE: In the following code I will be using awaitMessages() (Message Collector but promise dependent), as I see it more fitting for this case (Seeing as you're more than likely not hoping for it to be asynchronous) and could clean up the code a little bit.
const filter = m => m.author.id === message.author.id
let name // This variable will later be used to define our channel's name using the user's input.
// Starting our collector below:
try {
const collected = await message.channel.awaitMessages(filter, {
max: 1,
time: 30000,
errors: ['time']
})
name = collected.first().content /* Getting the collected message and declaring it as the variable 'name' */
} catch (err) { console.error(err) }
await message.guild.channels.create(name, { ... })

How to check who edited the channel on Discord through channelUpdate event

I'm creating the updateChannel event, however, as I go through the Discord.JS Docs I couldn't seem to find or figure out who edited the channel; or is that even possible? I will provide the current code that I have below this message.
Discord.JS: v12.2.0
client.on("channelUpdate", async(oldChannel, newChannel) => {
if(oldChannel.type === "dm") return undefined;
const embed = new Discord.MessageEmbed()
.setAuthor("Channel Updated", oldChannel.guild.iconURL({ dynamic: true }))
oldChannel.send(embed)
});
Yes, it's possible, you need to fetch audit logs:
oldChannel.guild.fetchAuditLogs({ type: 11, limit: 1 }) // CHANNEL_UPDATE
.then((logs) => {
embed.setDescription(logs.entries.first().executor); // Get First from Collection of GuildAuditLogs, and its executor.
oldChannel.send(embed);
})
.catch(console.error);

Categories

Resources