How can I change a message by its ID? I have the following code:
client.on('message', message => {
if(message.content.startsWith(prefix + 'edit')) {
let msg1 = ['message'];
const desc = msg1.content.split(' ').slice(2).join(' ');
const desc2 = msg1.content.split(' ').slice(3).join(' ');
const desc3 = msg1.content.split(' ').slice(4).join(' ');
let server = client.guilds.cache.get(desc);
if (!server) console.log('Не могу получить сервер')
let channel = server.channels.cache.get(desc2);
if (!channel) console.log('Не могу получить канал')
let message = channel.messages.fetch(desc3).then(msg => {
msg.edit('hello')
})
}
})
And I can't make it so that the user can choose which message to change.
Related
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 ?
Today I tried to start my bot but I got this error :
TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.
[Symbol(code)]: 'CLIENT_MISSING_INTENTS'
And this is my code:
const Discord = require('discord.js'),
client = new Discord.Client(),
nodeHtmlToImage = require('node-html-to-image'),
config = require('./config.json'),
puppeteer = require('puppeteer'),
express = require('express'),
app = express()
var mime = require('mime'),
fs = require('fs'),
path = require('path')
const port = 3e3
async function nitrogenerator(e, t) {
let a = formatAMPM(new Date())
let n = formatAMPM(new Date(Date.now() - 6e4)),
o = await fs.readFileSync(`${__dirname}/testingboost.html`, 'utf8')
;(datatosend = o),
(datatosend = datatosend.replace(
'FIRSTAUTHORURL',
e.author.displayAvatarURL()
)),
(datatosend = datatosend.replace('THEFIRSTAUTHOR', e.author.username)),
(datatosend = datatosend.replace(
'SECONDAUTHORURL',
client.users.cache.random().displayAvatarURL()
)),
(datatosend = datatosend.replace('THESECONDAUTHOR', t.shift())),
(datatosend = datatosend.replace('RESPONSETONITRO', t.join(' '))),
(datatosend = datatosend.replace('FIRSTAUTHORDATE', 'Today at ' + n)),
(datatosend = datatosend.replace('SECONDAUTHORDATE', 'Today at ' + a)),
app.get('/font', function (e, t) {
const a = `${__dirname}/Whitneyfont.woff`
t.sendFile(a)
}),
app.get('/', function (e, t) {
t.send(datatosend)
})
let r = app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
const s = await puppeteer.launch({
args: ['--no-sandbox', '--disable-setuid-sandbox'],
}),
i = await s.newPage()
await i.goto(`http://localhost:${port}`),
await i.waitForSelector('.scrollerInner-2YIMLh')
const d = await i.$('.scrollerInner-2YIMLh')
let c = await d.screenshot({ type: 'png' })
await s.close()
const l = new Discord.MessageAttachment(c, 'NitroProof.png')
e.channel.send(`${e.author}`, l), r.close()
}
function formatAMPM(e) {
var t = e.getHours(),
a = e.getMinutes(),
n = t >= 12 ? 'PM' : 'AM'
return (t = (t %= 12) || 12) + ':' + (a = a < 10 ? '0' + a : a) + ' ' + n
}
client.on('ready', () => {
function randomStatus() {
let status = ['ShadowWLX#0001', 'Hehe Boy'] // You can change it whatever you want.
let rstatus = Math.floor(Math.random() * status.length)
// client.user.setActivity(status[rstatus], {type: "WATCHING"});
// You can change the "WATCHING" into STREAMING, LISTENING, and PLAYING.
// Example: streaming
client.user.setActivity(status[rstatus], {
type: 'LISTENING',
url: 'https://discord.gg/MZUHeefXqx',
})
}
setInterval(randomStatus, 5000) // Time in ms. 30000ms = 30 seconds. Min: 20 seconds, to avoid ratelimit.
console.log('Online.')
})
client.on('message', async (e) => {
if ('dm' === e.channel.type) return
if (e.author.bot) return
if (0 !== e.content.indexOf(config.prefix)) return
const t = e.content.slice(config.prefix.length).trim().split(/ +/g)
'boost' === t.shift().toLowerCase() && (await nitrogenerator(e, t))
}),
client.login(config.token)
I know I need to add intents but I don't know how and what intents to add. I think I need to add the GUILD_PRESENCE intent but I don't know how to add it.
You can add intents to the Client like this-
const client = new Discord.Client({
intents: ["GUILD"] //If you want to add all intents just type 32767 instead of array
})
You must add intents in main.js, where you initialize bot.
const myIntents = new Intents();
myIntents.add(Intents.FLAGS.GUILD_PRESENCES, Intents.FLAGS.GUILD_MEMBERS);
const client = new Client({ intents: myIntents });
List of all intents
GUILDS
GUILD_MEMBERS
GUILD_BANS
GUILD_EMOJIS_AND_STICKERS
GUILD_INTEGRATIONS
GUILD_WEBHOOKS
GUILD_INVITES
GUILD_VOICE_STATES
GUILD_PRESENCES
GUILD_MESSAGES
GUILD_MESSAGE_REACTIONS
GUILD_MESSAGE_TYPING
DIRECT_MESSAGES
DIRECT_MESSAGE_REACTIONS
DIRECT_MESSAGE_TYPING
GUILD_SCHEDULED_EVENTS
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);
Guys I am currently working on a quick.db leaderboard command but it returns the global leaderboard but I want it to return only the Names Of The User Which are in the message.guild.
My current lb code is this
const Discord = require('discord.js')
const db = require('quick.db')
module.exports.run = async (bot, message, args) => {
const ic = '<:mon:834428547064922142>'
let money = db.fetchAll(message.guild.id).filter(data => data.ID.startsWith(`mon_`)).sort((a, b) => (b.data-a.data))
money.length = 25;
var finalLb = "";
for (var i in money) {
finalLb += `**${money.indexOf(money[i])+1}. ${(await bot.users.fetch(money[i].ID.split('_')[1])).username ? (await bot.users.fetch(money[i].ID.split('_')[1])).username : "Unknown User#0000"}** : ${ic} ${parseInt(JSON.stringify(money[i].data))}\n`;
}
const embed = new Discord.MessageEmbed()
.setAuthor(`Leaderboard`, message.guild.iconURL())
.setColor("RANDOM")
.setDescription(finalLb)
.setFooter(bot.user.tag, bot.user.displayAvatarURL())
.setTimestamp()
message.channel.send(embed);
}
module.exports.help = {
name:"rich",
aliases: [""]
}
Try adding this in your code
if(guild.members.cache.has("The UserID")){
//Add the user in leaderboard
//finalLb += `**${money. .........your code
}
const member = message.guild.members.cache.get('user id');
if(!member){
// what to do if member is not provided
}
}
I have the following code:
bot.on('message', msg =>{
if(msg.content === "Hello"){
const hello1 = 'Hello mah boi! or girl... eh'
const hello2 = 'Sup.'
const hello3 = 'Wassup?'
const hello4 = 'HEEEEEELLLLOOOOO BOOOOOIII'
const hello5 = 'Are you sure you wanna say hi??'
const hello6 = '.'
const hello7 = 'Heeeeeyyyyyyyyy ey eyyyyyyyy'
const items = [
hello1,
hello2,
hello3,
hello4,
hello5,
hello6,
hello7
];
const rndString = items[Math.floor(Math.random() * items.length)];
msg.channel.send(rndString);
}
})
I'm trying to make a random message command, but it isn't working. No message is ever sent. It doesn't throw any errors either.
I do the same thing, except with memes. You could try this, this is my code:
const memes = [
'https://tenor.com/LxdC.gif',
'https://tenor.com/Fm1D.gif',
'https://tenor.com/bqltH.gif',
'https://tenor.com/4nHj.gif',
'https://tenor.com/zFEB.gif',
'https://tenor.com/xa3U.gif',
'https://tenor.com/wMSx.gif',
'https://tenor.com/HxIT.gif',
'https://tenor.com/XGES.gif',
'https://tenor.com/bdnvi.gif',
'https://tenor.com/yf4L.gif',
'https://tenor.com/bnU5s.gif',
'https://tenor.com/xjhw.gif',
'https://tenor.com/2Rbt.gif',
'https://tenor.com/bE4YO.gif',
'https://tenor.com/bEOYD.gif'
]
client.on('message', (message) => {
if (message.content.startsWith('!memes')) {
const response = memes[Math.floor(Math.random() * memes.length)];
message.channel.send(response);
}
});
client.on('message', (message) => {
if (message.content.startsWith('!memesdm')) {
const response = memes[Math.floor(Math.random() * memes.length)];
message.author.send(response);
}
});
You can do it like this:
bot.on('message', msg =>{
if(msg.content === "Hello"){
function random() {
const hello1 = 'Hello mah boi! or girl... eh'
const hello2 = 'Sup.'
const hello3 = 'Wassup?'
const hello4 = 'HEEEEEELLLLOOOOO BOOOOOIII'
const hello5 = 'Are you sure you wanna say hi??'
const hello6 = '.'
const hello7 = 'Heeeeeyyyyyyyyy ey eyyyyyyyy'
var rand = [hello1, hello2, hello3, hello4, hello5, hello6, hello7];
return rand[Math.floor(Math.random()*rand.length)];
}
message.channel.send(random())
}
})