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
Related
I'm trying to get an image (served to the client from an express server) to display. I've received the data from the server and have parsed this from binary, to blob, to datauri. I, however, am still getting a broken image on my page.
Below is my code:
const [imageUrl, setImageUrl] = useState('');
const [profilePic, setProfilePic] = useState('');
const [errors, setErrors] = useState('');
const binaryToBase64 = () => {
contentType = contentType || '';
var sliceSize = 1024;
var byteCharacters = base64Data.toString("base64");
var bytesLength = byteCharacters.length;
var slicesCount = Math.ceil(bytesLength / sliceSize);
var byteArrays = new Array(slicesCount);
for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
var begin = sliceIndex * sliceSize;
var end = Math.min(begin + sliceSize, bytesLength);
var bytes = new Array(end - begin);
for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}
useEffect(() => {
// Get all customer media
let tempPhoto = '';
await actions.getMediaReference(customerId)
.then(resp => {
// Set profile pic via reference from DB
tempPhoto = resp.data.find(({ isprofile }) => isprofile);
})
.catch(err => errors.push(err));
await actions.getMediaSource(tempPhoto.key)
.then(resp => {
// console.log("specific data: ", typeof resp.data); // Not sure of the format: ����
const blob = binaryToBase64(resp.request.response, "image/jpg"); // convert to base 64 - I assume I'm getting binary code
const url = URL.createObjectURL(blob);
console.log('blob: ', blob); // prints this which also isn't accepted: blob:http://localhost:3000/1231233234
console.log('url: ', url);
// setImageUrl(url)
// My thinking is that it needed to be further processed (got this from another stackoverflow page)
fileToDataUri(blob)
.then(dataUri => {
setImageUrl(dataUri)
})
setProfilePic({ ...profilePic, image : resp.data });
})
.catch(err => errors.push(err));
}
return(
<>
<img src={imageUrl} />
</>
)
Trying this api out via Postman works - I get the image after a very tiny delay. I can't say that I see the error here but I've tried a few things. After running the base64 code in a converter I can see that something isn't translating correctly. I feel like this shouldn't be that complicated and that I've over-complicated the solution so any help/advice would be much appreciated!
Thanks
I try to split more than 2000 chars from a file, but the
{ split: true }
seem not to work, any here know what I'm doing wrong.. here my full code:
const Discord = require("discord.js");
const fs = require('fs');
const date = require('date-and-time');
const readLastLines = require('read-last-lines');
const bot = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
const now = new Date();
var settings = require("./settings.js");
var channel = require("./settings.js");
var playlist = "text.txt"
bot.on("ready", function () {
console.log("ready");
// console.log("Stream ready - Starting live Playlist...." + date.format(now, 'DD/MM/YYYY'));
// bot.channels.cache.get(settings.discord_channel).send("Stream ready - Starting live Playlist...." + date.format(now, 'DD/MM/YYYY'));
});
fs.watchFile(playlist, (eventType, filename) => {
readLastLines.read(playlist, 255)
.then((lines) => bot.channels.cache.get(settings.discord_channel).send(lines, { split: true }));
});
bot.login(settings.bot_token);
The split option for MessageOptions was removed in v13. You now have to import the Util class and use it's splitMessage() method.
You'll need to split the message into chunks and then asynchronously loop through each chunk, awaiting the sending of each.
const { Util } = require('discord.js');
// Your code
readLastLines.read(playlist, 255)
.then(async lines => {
const channel = bot.channels.cache.get(settings.discord_channel);
// Splitting and sending
const messageChunks = Util.splitMessage(lines, {
maxLength: 2000,
char: ' '
});
messageChunks.forEach(async chunk => {
await channel.send(chunk);
});
});
I'm trying to make a transcript button, but when it run gives me the error:
TypeError: msgs.forEach is not a function
I don't know how to resolve it.. Someone know a solution?
I tried everything and search very much but don't find nothing
if (interaction.customId === 'trs') {
let messageCollection = new Collection();
let channelMessages = await interaction.channel.messages.fetch({
limit: 100
}).catch(err => console.log(err));
messageCollection = messageCollection.concat(channelMessages);
while(channelMessages.size === 100) {
let lastMessageId = channelMessages.lastKey();
channelMessages = await interaction.channel.messages.fetch({ limit: 100, before: lastMessageId }).catch(err => console.log(err));
if(channelMessages)
messageCollection = messageCollection.concat(channelMessages);
}
let msgs = messageCollection.array().reverse();
let data = await fs.readFile('./template.html', 'utf8').catch(err => console.log(err));
if(data) {
await fs.writeFile(`${interaction.channel.name}.html`, data).catch(err => console.log(err));
let guildElement = document.createElement('div');
let guildText = document.createTextNode(interaction.guild.name);
let guildImg = document.createElement('img');
guildImg.setAttribute('src', interaction.guild.iconURL);
guildImg.setAttribute('width', '150');
guildElement.appendChild(guildImg);
guildElement.appendChild(guildText);
console.log(guildElement.outerHTML);
await fs.appendFile(`${interaction.channel.name}.html`, guildElement.outerHTML).catch(err => console.log(err));
msgs.forEach(async msg => {
let parentContainer = document.createElement("div");
parentContainer.className = "parent-container";
let avatarDiv = document.createElement("div");
avatarDiv.className = "avatar-container";
let img = document.createElement('img');
img.setAttribute('src', msg.author.displayAvatarURL);
img.className = "avatar";
avatarDiv.appendChild(img);
parentContainer.appendChild(avatarDiv);
let messageContainer = document.createElement('div');
messageContainer.className = "message-container";
let nameElement = document.createElement("span");
let name = document.createTextNode(msg.author.tag + " " + msg.createdAt.toDateString() + " " + msg.createdAt.toLocaleTimeString() + " EST");
nameElement.appendChild(name);
messageContainer.append(nameElement);
if(msg.content.startsWith("```")) {
let m = msg.content.replace(/```/g, "");
let codeNode = document.createElement("code");
let textNode = document.createTextNode(m);
codeNode.appendChild(textNode);
messageContainer.appendChild(codeNode);
}
else {
let msgNode = document.createElement('span');
let textNode = document.createTextNode(msg.content);
msgNode.append(textNode);
messageContainer.appendChild(msgNode);
}
parentContainer.appendChild(messageContainer);
await fs.appendFile(`${interaction.channel.name}.html`, parentContainer.outerHTML).catch(err => console.log(err));
})
client.channels.cache.get('886342088864698408').send({
files:[`./${interaction.channel.name}.html`]
})
interaction.channel.send({
content: 'Ticket transcrito e logado no chat <#886342088864698408>...'
})
}
}
If you are using Discord.JS version 13.0.0 or higher messageCollection.array() will not work. Try using [...messageCollection.values()]
Example:
let msgs = [...messageCollection.values()].reverse();
Discord.JS Guide for Collections
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);
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.