Create invite from server 1 and send to user DMS in server 2 - javascript

So I am trying to create a type of command that will generate 1 single use in server 1. Now if I were to input this command into a general text in server 2, !dminvite #user, it would send the mentioned user the single created invite from server 1 and send it to the mentioned user in server 2, via DMs.
Some Notes:
1. I have the 2 server id's saved in my config.json file and this invite command requires config.json. In this commands file base
2. This command is running over discord.js v12, but if anyone wants to help out in discord.js v13, It would be amazing as well.
3. I am no way in trying to advertise anything, I own both servers
I have a code written down but it's not working, just a view point:
message.delete();
message.mentions.members.first() ||
message.guild.members.cache.get(args[0]);
const Options = {
temporary: false,
maxAge: 0,
maxUses: 1,
unique: true
};
const channel = message.guild.channels.cache.get('(Channel ID)');
let invite = message.channels.createInvite(Options).then(function(Invite) {
message.mentions.members.first().send({embed: {
title: `**INVITE**`,
description: `Invite:\nhttps://discord.gg/` + Invite.code
}});
message.channel.send(new Discord.MessageEmbed()
.setAuthor(message.author.tag, message.author.displayAvatarURL({ dynamic: true }))
.setDescription(`${message.author.tag}, invite was sent to DMs`)
.setColor('BLUE')
);
});

To accomplish your goal we do this:
Get the mentioned user from the message.
Fetch the other guild we want to invite the user to.
Create an invite to the other guild's system channel (it doesn't have to be systemChannel).
Send the invite to the mentioned user's DMs.
// Id of the other guild
const otherGuildId = "guild id";
client.on("message", async (message) => {
// Don't reply to itself
if (message.author.id == client.user.id) return;
// Check if the message starts with our command
if (message.content.startsWith("!dminvite")) {
// Get the mentioned user from the message
const user = message.mentions.users.first();
if (!user) {
message.channel.send("You need to mention the user to send the invitation to.");
return;
}
// Fetch the other guild we want to invite the user to
const otherGuild = await client.guilds.fetch(otherGuildId);
// Create invite to the other guild's system channel
const invite = await otherGuild.systemChannel.createInvite({
maxAge: 0,
maxUses: 1,
unique: true
});
// Send the invite to the mentioned user's DMs
user.send({
embed: {
title: "**INVITE**",
description: `${invite}`
}
});
}
});
Note that if you don't want to use the systemChannel, you can simply get any channel you want from the otherGuild by its id for example.
// Resolve channel id into a Channel object
const channel = otherGuild.channels.resolve("channel id");
Using discord.js ^12.5.3.

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 Webhooks 10 limit on channel

Every time a user send messages a webhook edits its name and shows message.author.username but after After some time maybe because of an error the webhook creates 2 or more webhooks and keeps showing message author names.
How to use only 1 webhook?
let webhook = await client.channels.cache.get(smchannel[i]).fetchWebhooks();
webhook = webhook.find(x => x.name === message.member.nickname ? message.member.nickname : message.author.username);
webhook = await client.channels.cache.get(smchannel[i]).createWebhook('Chat Guy', {
avatar: client.user.displayAvatarURL({ dynamic: true })});
await webhook.edit({
name: message.member.nickname ? message.member.nickname : message.author.username,
avatar: message.author.displayAvatarURL({ dynamic: true })})
webhook.send( content ).catch(err => { })
}
});
You are always creating a new webhook.
First of all, you don't need to find an exact name with author because you can customize webhooks before you sent a message.
let webhooks = await client.channels.cache.get(smchannel[i]).fetchWebhooks();
let webhook = webhooks.first()
if(!webhook){
// create new webhook if not exists in channel
} else {
// edit your webhook in here and send!
}

I am trying to make a guild add message

I am trying to make it so when my bot is added to another server, it will send an embed saying how many servers it's in now and the guild name and also the guild owner. I am also trying to make another embed so it tells me when it leaves a server and tells me when it joined the server first and then when it was removed and the guild name and guild owner. I use discord.js. Could someone help, please? This is my current script:
bot.on("guildCreate", guild => {
const joinserverembed = new Discord.MessageEmbed()
.setTitle("Joined a server!")
.addField("Guild name:", `${guild.name}`)
.addField("Time of join:", `${Discord.Guild.createdTimestamp()}`)
.setColor("GREEN")
.setThumbnail(guild.displayAvatarURL())
if (guilds.channel.id = 740121026683207760) {
channel.send(joinserverembed)
}
guild.channel.send("Thank you for inviting Ultra Bot Premium! Please use up!introduction and up!help for the new perks and more!")
})
bot.on("guildDelete", guild => {
const leftserverembed = new Discord.MessageEmbed()
.setTitle("Left a server!")
.addField("Guild name:", `${guild.name}`)
.addField("Time of removal:", `${createdTimestamp()}`)
.setColor("RED")
.setThumbnail(guild.displayAvatarURL())
if (guilds.channel.id = 740121026683207760) {
channel.send(leftserverembed)
}
})
I have resolved your first issue for you in the code below.
You were doing guild.channel.send(), in this case, guild represents a Discord.Guild however you're using it like it represents an instance of Message, which it does not.
You can use guild.channels.cache.find(x => x.name == 'general').send("Thanks for inviting me to this serverĀ¬!") will send a message to a channel named general in that server.
bot.on("guildCreate", (guild) => {
const joinserverembed = new Discord.MessageEmbed()
.setTitle("Joined a server!")
.addField("Guild name:", guild.name)
.addField("Time of join:", Date.now())
.setColor("GREEN")
.setThumbnail(guild.iconURL({ dynamic: true }));
bot.channels.cache.get("740121026683207760").send(joinserverembed);
guild.channels.cache
.filter((c) => c.type === "text")
.random()
.send(
"Thank you for inviting Ultra Bot Premium! Please use up!introduction and up!help for the new perks and more!"
);
});
I filter the channels in the guild, ensuring that they are not categories or voice channels, then send the welcome message to a random one.
As for your second query, you need to use a database, store the Date.now timestamp of when it was added, then once the bot has left the guild it must get the value and display its time. I haven't done this for you, but I have fixed your code:
bot.on("guildDelete", (guild) => {
const leftserverembed = new Discord.MessageEmbed()
.setTitle("Left a server!")
.addField("Guild name:", guild.name)
.addField("Time of removal:", Date.now())
.setColor("RED")
.setThumbnail(guild.iconURL({ dynamic: true }));
bot.channels.cache.get("740121026683207760").send(leftserverembed);
});

How do you mass create channels on Discord.js

Hello I am making a bot that will basically make a whole discord server and I just can't figure out how to mass create channels so could someone tell me, please
const Channels = ["Example Channel", "Example Channel 2"]; // Example of channel names.
const Guild = await client.guilds.create("My Guild"); // Creating the guild.
Channels.forEach(channelName => { // Looping through Channels array to get the channels names.
Guild.channels.create(channelName); // Creating the channels.
});
const GuildChannel = Guild.channels.cache.filter(c => c.type === "text").find(x => x.position == 0); // Getting the first channel in the guild.
const Invite = await GuildChannel.createInvite({maxAge: 0, maxUses: 1}); // Creating and invite.
message.channel.send(`I created the guild ${Guild.name}. Invite Link: ${Invite.url}`); // Sending the invite link to the current channel.
// Warning: client.guilds.create() is only available to bots in fewer than 10 guilds.guilds!

How do I fetch the creator of a channel in discord?

bot.on('channelCreate', async channel => {
if (!channel.guild) return;
const fetchedLogs = await channel.guild.fetchAuditLogs({
limit: 1,
type: 'CHANNEL_CREATE',
});
const logbook = channel.guild.channels.cache.get("ChannelID")
const deletionLog = fetchedLogs.entries.first();
if (!deletionLog) return logbook.send(`A channel was updated but no relevant autid logs were found`);
const { executor, user } = deletionLog;
if (user.id) {
logbook.send(`${executor.tag} created a channel`);
} else {
logbook.send(`A channel was created but idk who did.`);
}
});
I am a newbie when it comes to fetching actions through Discord Audit Logs; so I am experimenting and somehow came up with this code. However, when I create a channel, it does not send any messages saying that a channel has been created by #user. I have no idea what my next step will be. All I wanted to do was to know who created the channel.
Discord.JS: v12.2.0
client.on("channelCreate", async channel => {
if (!channel.guild) return false; // This is a DM channel.
const AuditLogFetch = await channel.guild.fetchAuditLogs({limit: 1, type: "CHANNEL_CREATE"}); // Fetching the audot logs.
const LogChannel = client.channels.cache.get("722052103060848664"); // Getting the loggin channel. (Make sure its a TextChannel)
if (!LogChannel) return console.error(`Invalid channel.`); // Checking if the channel exists.
if (!AuditLogFetch.entries.first()) return console.error(`No entries found.`);
const Entry = AuditLogFetch.entries.first(); // Getting the first entry of AuditLogs that was found.
LogChannel.send(`${Entry.executor.tag || "Someone"} created a new channel. | ${channel}`) // Sending the message to the logging channel.
});
If the code I provided is not working, please make sure the bot has access to view AuditLogs.

Categories

Resources