const Invites = new Collection();
const guildInvites = new Map()
client.on('inviteCreate', async invite => {
const invites = await invite.guild.invites.fetch();
const codeUses = new Map();
invites.each(inv => codeUses.set(inv.code, inv.uses, inv.inviter));
guildInvites.set(invite.guild.id, codeUses);
})
client.once('ready', () => {
client.guilds.cache.forEach(guild => {
guild.invites.fetch()
.then(invites => {
const codeUses = new Map();
invites.each(inv => codeUses.set(inv.code, inv.uses, inv.inviter));
guildInvites.set(guild.id, codeUses);
})
.catch(err => {
console.log("OnReady Error:", err)
})
})
})
client.on('guildMemberAdd', async member => {
const cachedInvites = guildInvites.get(member.guild.id)
const newInvites = await member.guild.invites.fetch();
try {
const usedInvite = newInvites.find(inv => cachedInvites.get(inv.code) < inv.uses < inv.inviter);
const embed0 = new MessageEmbed()
.setTitle("Invite Logs")
.setColor("GREEN")
.setDescription(`Ο/Η ${member} (${member.user.username}) μπήκε στον server από την πρόσκληση (${usedInvite.code || "δεν υπάρχει πλέον"}) του ${usedInvite.inviter} (${usedInvite.inviter.username}) **αλλά είναι Fake**`)
var fake22 = (Date.now() - member.user.createdAt < 1000*60*60*config.invite_faketime*1) //return client.channels.cache.get(config.invite_logs).send({embeds: [embed0] }),db.add(`total_${usedInvite.inviter.id}`, 1),db.add(`fake_${usedInvite.inviter.id}`, 1)
const embed = new MessageEmbed()
.setTitle("Invite Logs")
.setColor("GREEN")
.setDescription(`Ο/Η ${member} (${member.user.username}) μπήκε στον server από την πρόσκληση (${usedInvite.code || "δεν υπάρχει πλέον"}) του ${usedInvite.inviter} (${usedInvite.inviter.username})`)
client.channels.cache.get(config.invite_logs).send({embeds: [embed] })
if (usedInvite.inviter) {
db.set(`invites_${member.guild.id}.${member.id}.inviter`, usedInvite.inviter.id);
if (fake22) {
total = db.add(`invites_${member.guild.id}.${usedInvite.inviter.id}.total`, 1);
_fake = db.add(`invites_${member.guild.id}.${usedInvite.inviter.id}.fake`, 1);
}
else {
total = db.add(`invites_${member.guild.id}.${usedInvite.inviter.id}.total`, 1);
regular = db.add(`invites_${member.guild.id}.${usedInvite.inviter.id}.regular`, 1);
}}
//console.log(`The code ${usedInvite.code} was just used by ${member.user.username}. ${usedInvite.inviter.username}`)
} catch(err) {
}
newInvites.each(inv => cachedInvites.set(inv.code, inv.uses));
guildInvites.set(member.guild.id, cachedInvites);
});
**
we have user 1
user 2
user 3
i am user 1
i invite user 2 and i see in logs that user 1 invites user 2
but after i make invite link from user 2 and i invite user 3
but i see in logs tha user 1 invites user 3
**
can someone help me to cashed the right invite ?
Related
I'm creating a message with buttons as reaction roles but do the reaction role handling in another file so it stays loaded after a reset but it either says "interaction.deferUpdate() is not a function, or in discord it says "this interaction failed" but it gave/removed the role
my code for creating the message:
const { ApplicationCommandType, ActionRowBuilder, ButtonBuilder, EmbedBuilder } = require('discord.js');
module.exports = {
name: 'role',
description: "reactionroles",
cooldown: 3000,
userPerms: ['Administrator'],
botPerms: ['Administrator'],
run: async (client, message, args) => {
const getButtons = (toggle = false, choice) => {
const row = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setLabel('member')
.setCustomId('member')
.setStyle(toggle == true && choice == 'blue' ? 'Secondary' : 'Primary')
.setDisabled(toggle),
new ButtonBuilder()
.setLabel('member2')
.setCustomId('member2')
.setStyle(toggle == true && choice == 'blue' ? 'Secondary' : 'Primary')
.setDisabled(toggle),
);
return row;
}
const embed = new EmbedBuilder()
.setTitle('Wähle eine rolle')
.setDescription('Wähle die rolle, die du gern haben möchtest')
.setColor('Aqua')
message.channel.send({ embeds: [embed], components: [getButtons()] })
.then((m) => {
const collector = m.createMessageComponentCollector();
collector.on('collect', async (i) => {
if (!i.isButton()) return;
await i.deferUpdate();
});
});
}
};
code for the reaction role:
const fs = require('fs');
const chalk = require('chalk')
var AsciiTable = require('ascii-table')
var table = new AsciiTable()
const discord = require("discord.js");
table.setHeading('Events', 'Stats').setBorder('|', '=', "0", "0")
module.exports = (client) => {
client.ws.on("INTERACTION_CREATE", async (i) => {
let guild = client.guilds.cache.get('934096845762879508');
let member = await guild.members.fetch(i.member.user.id)
let role = guild.roles.cache.find(role => role.name === i.data.custom_id);
if (!member.roles.cache.has(role.id)) {
member.roles.add(role);
} else {
member.roles.remove(role);
}
return i.deferUpdate()
})
};
The client.ws events give raw data (not discord.js objects), so the .deferUpdate() method doesn't exist there. You should be using client.on("interactionCreate")
client.on("interactionCreate", async (i) => {
// ...
return i.deferUpdate()
})
I am getting the interaction has already been acknowledged error. Basically when the command is called the first time, the button and the modal work just fine. The second time, the button appears but then shows the modal and throws the "DiscordAPIError: Interaction has already been acknowledged." error. I am in a real slump.
} else if (order == "edit") {
let shelfNameSpaces = "";
for (let i = 1; i < args.length; i++) {
shelfNameSpaces += args[i] + " ";
}
let shelfName = shelfNameSpaces.trim();
let shelfObj = await Shelves.findOne({name: shelfName})
if (shelfObj) {
const embed = new MessageEmbed()
.setColor("#0099ff")
.setThumbnail(profileImage)
.setTitle(`${shelfObj["name"]}`)
.setDescription("Displaying shelf info")
.addField("Owner", `<#${shelfObj["owner"]}>`)
if (shelfObj["info"].length <= 0) {
embed.addField("Info", "No information added")
} else {
embed.addField("Info", shelfObj["info"])
}
let m = await message.channel.send({ embeds: [embed] })
const row = new MessageActionRow();
row.addComponents(
new MessageButton()
.setCustomId(`edit-shelf`)
.setLabel('Edit Shelf')
.setStyle("PRIMARY")
)
var buttons = await message.channel.send({ components: [row] })
setTimeout(() => {
if (buttons.deletable)
buttons.delete()
}, 60000);
// client.on("interactionCreate", async (interaction) => {
// module.exports = {
// name: 'interactionCreate',
// async execute (interaction) {
// }
// }
var editInfo, modal, editRow;
client.on("interactionCreate", async (interaction) => {
if (!interaction.isButton() || interaction.isModalSubmit()) return;
if (interaction.customId == "edit-shelf") {
// interaction.reply("Editing")
if (buttons.deletable)
buttons.delete()
modal = new Modal()
.setCustomId(`editModal`)
.setTitle('Edit Info')
editInfo = new TextInputComponent()
.setCustomId(`editInput`)
.setLabel("Input your edit")
.setValue(shelfObj["info"])
.setStyle("PARAGRAPH")
editRow = new MessageActionRow().addComponents(editInfo)
modal.addComponents(editRow)
await interaction.showModal(modal)
modalCheck++;
}
})
client.on("interactionCreate", async (inter) => {
if (!inter.isModalSubmit()) return;
inter.deferUpdate()
const editval = inter.fields.getTextInputValue('editInput')
// console.log(editval);
shelfObj["info"] = editval
const updatedShelf = new Shelves(shelfObj);
await updatedShelf.save()
const embed2 = new MessageEmbed()
.setColor("#0099ff")
.setThumbnail(profileImage)
.setTitle(`${shelfObj["name"]}`)
.setDescription("Displaying shelf info")
.addField("Owner", `<#${shelfObj["owner"]}>`)
if (shelfObj["info"].length <= 0) {
embed2.addField("Info", "No information added")
} else {
embed2.addField("Info", shelfObj["info"])
}
m.edit({ embeds: [embed2] })
// inter.reply("Shelf edited successfully")
// await inter.deleteReply()
// if (buttons.deletable)
// buttons.delete()
})
} else {
const embed = new MessageEmbed()
.setColor("#ff0000")
.setTitle("Shelves")
.setDescription("Unknown Shelf")
.addField("Error", "Shelf not found");
message.channel.send({ embeds: [embed] });
}
I've experienced this error multiple times, and I finally found out how to fix this error.
To start off, you need to install a package called nanoid (npm i nanoid in terminal).
At the top of your file, include const { nanoid } = require("nanoid");. This package is used for creating unique IDs for anything you'd like.
now, make a variable, and make it the following:
let id = `button-${nanoid()}`;
Make your .setCustomId() equal .setCustomId(id).
Lastly, make your if (interaction.customId == "edit-shelf") equal if (interaction.customId == id).
Note: If you have another error, try changing your nanoid package in your package.json to version ^3.3.4, and uninstall and install it again.
I'm developing a discord.js moderation bot, but when I run it I get this error.
Here is the code:
var Discord = require('discord.js')
const fs = require("fs")
const { PREFIX } = require("../../config")
const db = require('quick.db')
const { stripIndents } = require("common-tags");
module.exports = {
config: {
name: "help",
description: "Help Menu",
usage: "1) m/help \n2) m/help [module name]\n3) m/help [command (name or alias)]",
example: "1) m/help\n2) m/help utility\n3) m/help ban",
aliases: ['h']
},
run: async (bot, message, args) => {
let prefix;
if (message.author.bot || message.channel.type === "dm") return;
try {
let fetched = await db.fetch(`prefix_${message.guild.id}`);
if (fetched == null) {
prefix = PREFIX
} else {
prefix = fetched
}
} catch (e) {
console.log(e)
};
if(message.content.toLowerCase() === `${prefix}help`){
var log = new Discord.MessageEmbed()
.setTitle("**Help Menu: Main**")
.setColor(`#d9d9d9`)
.addField(`**👑Moderation**`, `[ \`${prefix}help mod\` ]`, true)
.addField(`**⚙️Utility**`, `[ \`${prefix}help utility\` ]`, true)
message.channel.send(log);
}
else if(args[0].toLowerCase() === "mod") {
var commandArray = "1) Ban \n2) Kick\n3) Whois\n4) Unban\n5) Warn\n6) Mute\n7) Purge\n8) Slowmode \n9) Nick \n10) Roleinfo"
var commandA2 = "11) Rolememberinfo\n12) Setmodlog\n13) Disablemodlog\n14) Lock (Lock the channel)\n15) Unlock (Unlock the channel)\n16) Lockdown (Fully Lock the whole server. [FOR EMRGENCIES ONLY]) \n17) Hackban\\forceban <id>"
pageN1 = "**\n💠Commands: **\n`\`\`js\n" + commandArray + "\`\`\`";
pageN2 = "**\n💠Commands: **\n`\`\`js\n" + commandA2 + "\`\`\`";
let pages = [pageN1, pageN2]
let page = 1
var embed = new Discord.MessageEmbed()
.setTitle('**Help Menu: [Moderation]👑**')
.setColor("#d9d9d9") // Set the color
.setFooter(`Page ${page} of ${pages.length}`, bot.user.displayAvatarURL())
.setDescription(pages[page-1])
message.channel.send({embed}).then(msg => {
msg.react('⬅').then( r => {
msg.react('➡')
// Filters
const backwardsFilter = (reaction, user) => reaction.emoji.name === '⬅' && user.id === message.author.id
const forwardsFilter = (reaction, user) => reaction.emoji.name === '➡' && user.id === message.author.id
const backwards = msg.createReactionCollector(backwardsFilter, {timer: 6000})
const forwards = msg.createReactionCollector(forwardsFilter, {timer: 6000})
backwards.on('collect', (r, u) => {
if (page === 1) return r.users.remove(r.users.cache.filter(u => u === message.author).first())
page--
embed.setDescription(pages[page-1])
embed.setFooter(`Page ${page} of ${pages.length}`, bot.user.displayAvatarURL())
msg.edit(embed)
r.users.remove(r.users.cache.filter(u => u === message.author).first())
})
forwards.on('collect', (r, u) => {
if (page === pages.length) return r.users.remove(r.users.cache.filter(u => u === message.author).first())
page++
embed.setDescription(pages[page-1])
embed.setFooter(`Page ${page} of ${pages.length}`, bot.user.displayAvatarURL())
msg.edit(embed)
r.users.remove(r.users.cache.filter(u => u === message.author).first())
})
})
})
}
else if(args[0].toLowerCase() === "util") {
var embed = new Discord.MessageEmbed()
.setTitle('**Help Menu: [Utility]**')
.setColor("#d9d9d9") // Set the color
.setDescription("```js" + `1) Prefix [${prefix}help prefix for more info]\n 2) Help [${prefix}help for more info]` + "```")
} else {
const embed = new Discord.MessageEmbed()
.setColor("#d9d9d9")
.setAuthor(`${message.guild.me.displayName} Help`, message.guild.iconURL())
.setThumbnail(bot.user.displayAvatarURL())
let command = bot.commands.get(bot.aliases.get(args[0].toLowerCase()) || args[0].toLowerCase())
if (!command) return message.channel.send(embed.setTitle("**Invalid Command!**").setDescription(`**Do \`${prefix}help\` For the List Of the Commands!**`))
command = command.config
embed.setDescription(stripIndents`
** Command -** [ \`${command.name.slice(0, 1).toUpperCase() + command.name.slice(1)}\` ]\n
** Description -** [ \`${command.description || "No Description provided."}\` ]\n
** Usage -** [ \`${command.usage ? `\`${command.usage}\`` : "No Usage"}\` ]\n
** Examples -** [ \`${command.example ? `\`${command.example}\`` : "No Examples Found"}\` ]\n
** Aliases -** [ \`${command.aliases ? command.aliases.join(" , ") : "None."}\` ]`)
embed.setFooter(message.guild.name, message.guild.iconURL())
return message.channel.send(embed)
}
}
}
If someone could help with this issue it would be great because I don't know what to do. I already searched on internet but I still don't know what I need to do to solve this error. All this code is for help function, when someone calls -pks help the bot should show embed telling all his functions
Here is my index.js file:
const { Client, Collection } = require('discord.js');
const { PREFIX, TOKEN } = require('./config');
const bot = new Client({ disableMentions: 'everyone' });
const fs = require("fs");
const db = require('quick.db');
bot.commands = new Collection();
bot.aliases = new Collection();
["aliases", "commands"].forEach(x => bot[x] = new Collection());
["console", "command", "event"].forEach(x => require(`./handler/${x}`)(bot));
bot.categories = fs.readdirSync("./commands/");
["command"].forEach(handler => {
require(`./handler/${handler}`)(bot);
});
bot.on('message', async message => {
let prefix;
try {
let fetched = await db.fetch(`prefix_${message.guild.id}`);
if (fetched == null) {
prefix = PREFIX
} else {
prefix = fetched
}
} catch {
prefix = PREFIX
};
try {
if (message.mentions.has(bot.user.id) && !message.content.includes("#everyone") && !message.content.includes("#here")) {
message.channel.send(`\nMy prefix for \`${message.guild.name}\` is \`${prefix}\` Type \`${prefix}help\` for help`);
}
} catch {
return;
};
});
bot.login(TOKEN);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I decided to use this discord.js guide to create my economy discord bot. Apparently something went wrong as I was about to run the bot. It had this error message and it said :
Reflect.defineProperty(currency, 'add', {
^
ReferenceError: currency is not defined
I have no idea what was wrong with it. Here's my index.js:
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
Reflect.defineProperty(currency, 'add', {
/* eslint-disable-next-line func-name-matching */
value: async function add(id, amount) {
const user = currency.get(id);
if (user) {
user.balance += Number(amount);
return user.save();
}
const newUser = await Users.create({ user_id: id, balance: amount });
currency.set(id, newUser);
return newUser;
},
});
Reflect.defineProperty(currency, 'getBalance', {
/* eslint-disable-next-line func-name-matching */
value: function getBalance(id) {
const user = currency.get(id);
return user ? user.balance : 0;
},
});
client.once('ready', () => {
console.log('Ready!');
});
});
client.on('message', async message => {
if (message.author.bot) return;
currency.add(message.author.id, 1);
if (!message.content.startsWith(PREFIX)) return;
const input = message.content.slice(PREFIX.length).trim();
if (!input.length) return;
const [, command, commandArgs] = input.match(/(\w+)\s*([\s\S]*)/);
if (command === 'balance') {
const target = message.mentions.users.first() || message.author;
return message.channel.send(`${target.tag} has ${currency.getBalance(target.id)}💰`);
} else if (command === 'inventory') {
const target = message.mentions.users.first() || message.author;
const user = await Users.findOne({ where: { user_id: target.id } });
const items = await user.getItems();
if (!items.length) return message.channel.send(`${target.tag} has nothing!`);
return message.channel.send(`${target.tag} currently has ${items.map(t => `${t.amount} ${t.item.name}`).join(', ')}`);
} else if (command === 'transfer') {
const currentAmount = currency.getBalance(message.author.id);
const transferAmount = commandArgs.split(/ +/).find(arg => !/<#!?\d+>/.test(arg));
const transferTarget = message.mentions.users.first();
if (!transferAmount || isNaN(transferAmount)) return message.channel.send(`Sorry ${message.author}, that's an invalid amount`);
if (transferAmount > currentAmount) return message.channel.send(`Sorry ${message.author} you don't have that much.`);
if (transferAmount <= 0) return message.channel.send(`Please enter an amount greater than zero, ${message.author}`);
currency.add(message.author.id, -transferAmount);
currency.add(transferTarget.id, transferAmount);
return message.channel.send(`Successfully transferred ${transferAmount}💰 to ${transferTarget.tag}. Your current balance is ${currency.getBalance(message.author.id)}💰`);
} else if (command === 'buy') {
const item = await CurrencyShop.findOne({ where: { name: { [Op.like]: commandArgs } } });
if (!item) return message.channel.send('That item doesn\'t exist.');
if (item.cost > currency.getBalance(message.author.id)) {
return message.channel.send(`You don't have enough currency, ${message.author}`);
}
const user = await Users.findOne({ where: { user_id: message.author.id } });
currency.add(message.author.id, -item.cost);
await user.addItem(item);
message.channel.send(`You've bought a ${item.name}`);
} else if (command === 'shop') {
const items = await CurrencyShop.findAll();
return message.channel.send(items.map(i => `${i.name}: ${i.cost}💰`).join('\n'), { code: true });
} else if (command === 'leaderboard') {
return message.channel.send(
currency.sort((a, b) => b.balance - a.balance)
.filter(user => client.users.cache.has(user.user_id))
.first(10)
.map((user, position) => `(${position + 1}) ${(client.users.cache.get(user.user_id).tag)}: ${user.balance}💰`)
.join('\n'),
{ code: true }
);
}
});
client.login(`[TOKEN]`);
I presume the only probelm of this code is Reflect.defineProperty(currency, 'add', { as it can't define what is currency. I hope someone can help...
You're attempting to use the currency variable but you haven't defined it so JavaScript is rightfully complaining because it doesn't know what currency is.
The following line from the guide is missing from your code:
const currency = new Discord.Collection();
You have to define currency.
Basic js-
I'm trying to make a 'random meme' command for my Discord Bot. I'm new to working with APIs, but I've tried my best.
The problem is, when I type the command, nothing happens. There are no errors, but the bot doesn't send anything in discord.
This is my code:
if (command === "meme")
async (client, message, args) => {
const subReddits = ["dankmeme", "meme", "me_irl"];
const random = subReddits[Math.floor(Math.random() * subReddits.length)];
const img = await randomPuppy(random);
const embed = new Discord.MessageEmbed()
.setColor(16776960)
.setFooter("test")
.setImage(img)
.setTitle(`Random Meme requested by <#${message.author.tag}>`)
.setURL(`https://reddit.com/r/${random}`)
message.channel.send(embed);
}
Here Is One That Will Show Info About The Meme
if(command === "meme") {
const subReddits = ["dankmeme", "meme", "me_irl"];
const random = subReddits[Math.floor(Math.random() * subReddits.length)];
try {
const { body } = await snekfetch
.get('https://www.reddit.com/r/${random}.json?sort=top&t=week')
.query({ limit: 800 });
const allowed = message.channel.nsfw ? body.data.children : body.data.children.filter(post => !post.data.over_18);
if (!allowed.length) return message.channel.send('It seems we are out of memes');
const randomnumber = Math.floor(Math.random() * allowed.length)
const embed = new Discord.RichEmbed()
.setColor(0x00A2E8)
.setTitle(allowed[randomnumber].data.title)
.setDescription("Posted by: " + allowed[randomnumber].data.author)
.setImage(allowed[randomnumber].data.url)
.addField("Other info:", "Up votes: " + allowed[randomnumber].data.ups + " / Comments: " + allowed[randomnumber].data.num_comments)
.setFooter("r/" + random)
message.channel.send(embed)
} catch (err) {
return console.log(err);
}
}
Let Me Know If It Don't Work, But I Should
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (command === "meme") {
async (client, message, args) =>
const subReddits = ["dankmeme", "meme", "me_irl"];
const random = subReddits[Math.floor(Math.random() * subReddits.length)];
const img = await randomPuppy(random);
const embed = new Discord.MessageEmbed()
.setColor(16776960)
.setFooter("test")
.setImage(img)
.setTitle(`Random Meme requested by <#${message.author.tag}>`)
.setURL(`https://reddit.com/r/${random}`)
message.channel.send(embed);
}
});
This should work, not quite sure, haven't tested it. (You can put in a command handler your self)
if (command === "meme")
async (client, message, args) => {
const fetch = require('node-fetch');
let userAvatar = message.author.avatarURL({ format: "png", dynamic: true, size: 2048 }); // this is just the users icon, u can remove it if you want.
fetch(`https://meme-api.herokuapp.com/gimme`)
.then(res => res.json())
.then(async json => {
const embed = new MessageEmbed()
.setAuthor(`${json.title}`, `${userAvatar + "?size=2048"}`, `${json.postLink}`)
.setImage(`${json.url}`)
.setFooter(`👍${json.ups} | ${json.subreddit}`)
.setColor("RANDOM")
message.channel.send(embed).catch((error) => {
console.log("An error has occured on the \"meme\" command\n", error)
})
}
Here you go! I've tested this on my own command handler.