RangeError [BITFIELD_INVALID]: Invalid bitfield flag or number. when I try to save a channel in my command - discord.js

if(!message.guild.me.hasPermission("SEND_MESSAGES")) {
return
}
if(!message.guild.me.hasPermission("VIEW_CHANNEL")) {
return message.channel.send("I don't have `VIEW_CHANNEL` permission.")
}
if(!message.member.hasPermission("ADMINISTRATOR")) {
return message.channel.send("You don't have permissions to do that.")
}
const e = args[0]
const ER = message.mentions.channels.first()
if(!e) {
//return message.channel.send("You must enter a channel.")
}
if(ER) {
db.set(`${message.guild.id}.mch`,ER.id)
//message.channel.send("Channel has been set.")
} else {
if(message.guild.channels.cache.get(e)) {
const channel = message.guild.channels.cache.get(e)
db.set(`${message.guild.id}.wch`,e)
// message.channel.send("Channel has been successfully set.")
}
}
Hi, I'm trying to make a data command that saves channel's ID but whenever I execute this command it gives the error (title of the question), how can I solve it?

Related

Discord.js - How to send YouTube url after searching for a video

So basically, my idea for a new command for my discord bot is a "link searcher", which will be a searching command that sends the url of the video that is chosen by the user. Something like in the image attached.
What I already have made is a searching command with embed, but im not quite sure how to send the video url that gets chosen via reaction. Any ideas/solutions?
I have found a solution after some tries, so here's the final code.
//////CONFIG LOAD///////////
////////////////////////////
const ytsr = require("youtube-sr")
const { Client, Collection, MessageEmbed } = require("discord.js");
const { attentionembed } = require("../util/attentionembed"); //attentionembed is an embed i pre-made for errors/attention cases for when the user gets one
const { approveemoji, denyemoji, PREFIX, } = require(`../config.json`); //my config contains the definitions for "yes" and "no" emojis, together with the bot token
////////////////////////////
//////COMMAND BEGIN/////////
////////////////////////////
module.exports = {
name: "linkfor",
aliases: ["searchlink","findlink","link","lf"], //optional
cooldown: 3, //optional
async execute(message, args, client) {
//if its not in a guild return
if (!message.guild) return;
//react with approve emoji
message.react(approveemoji).catch(console.error);
//if the argslength is null return error
if (!args.length)
return attentionembed(message, `Usage: ${message.client.prefix}${module.exports.name} <Video Name>`)
//if there is already a search return error
if (message.channel.activeCollector)
return attentionembed(message, "There is a search active!");
//define search
const search = args.join(" ");
//define a temporary Loading Embed
let temEmbed = new MessageEmbed()
.setAuthor("Searching...", "put a gif link here if you want")
.setColor("#F0EAD6")
//define the Result Embed
let resultsEmbed = new MessageEmbed()
.setTitle("Results for ")
.setDescription(`\`${search}\``)
.setColor("#F0EAD6")
.setAuthor("Search results:", "put a gif link here if you want")
.setFooter("Respond with the right number", "put a gif link here if you want")
//try to find top 9 results
try {
//find them
const results = await ytsr.search(search, { limit: 9 });
//map them and sort them and add a Field to the ResultEmbed
results.map((video, index) => resultsEmbed.addField(video.url, `${index + 1}. ${video.title}`));
//send the temporary embed aka Loading... embed
const resultsMessage = await message.channel.send(temEmbed)
//react with 9 Numbers
await resultsMessage.react("1️⃣");
await resultsMessage.react("2️⃣");
await resultsMessage.react("3️⃣");
await resultsMessage.react("4️⃣");
await resultsMessage.react("5️⃣");
await resultsMessage.react("6️⃣");
await resultsMessage.react("7️⃣");
await resultsMessage.react("8️⃣");
await resultsMessage.react("9️⃣");
//edit the resultmessage to the resultembed (you can also try deleting and sending the new one, if you need to)
await resultsMessage.edit(resultsEmbed)
//set the collector to true
message.channel.activeCollector = true;
//wait for a response
let response;
await resultsMessage.awaitReactions((reaction, user) => user.id == message.author.id,
{ max: 1, time: 60000, errors: ['time'], }).then(collected => {
//if its one of the emoji set them to 1 / 2 / 3 / 4 / ...
if (collected.first().emoji.name == "1️⃣") { return response = 1; }
if (collected.first().emoji.name == "2️⃣") { return response = 2; }
if (collected.first().emoji.name == "3️⃣") { return response = 3; }
if (collected.first().emoji.name == "4️⃣") { return response = 4; }
if (collected.first().emoji.name == "5️⃣") { return response = 5; }
if (collected.first().emoji.name == "6️⃣") { return response = 6; }
if (collected.first().emoji.name == "7️⃣") { return response = 7; }
if (collected.first().emoji.name == "8️⃣") { return response = 8; }
if (collected.first().emoji.name == "9️⃣") { return response = 9; }
//otherwise set it to error
else {
response = "error";
}
});
//if response is error return error
if (response === "error") {
//send error message
attentionembed(message, "Please use the right emoji symbol.");
//try to delete the message
return resultsMessage.delete().catch(console.error);
}
//get the response link
const URL = resultsEmbed.fields[parseInt(response) - 1].name;
//set collector to false aka off
message.channel.activeCollector = false;
//send the collected url
message.channel.send(URL);
//delete the search embed (optional, for better displaying)
resultsMessage.delete().catch(console.error);
//catch any errors while searching
} catch (error) {
//log them
console.error(error);
//set collector false, just incase its still true
message.channel.activeCollector = false;
}
}
};

discordjs Embed won't show up

Ok, so i'm trying to make a push notification for my discord.
i found this script online.
but it will not post the embed....
This is my monitor code:
TwitchMonitor.onChannelLiveUpdate((streamData) => {
const isLive = streamData.type === "live";
// Refresh channel list
try {
syncServerList(false);
} catch (e) { }
// Update activity
StreamActivity.setChannelOnline(streamData);
// Generate message
const msgFormatted = `${streamData.user_name} is nu live op twitch <:bday:967848861613826108> kom je ook?`;
const msgEmbed = LiveEmbed.createForStream(streamData);
// Broadcast to all target channels
let anySent = false;
for (let i = 0; i < targetChannels.length; i++) {
const discordChannel = targetChannels[i];
const liveMsgDiscrim = `${discordChannel.guild.id}_${discordChannel.name}_${streamData.id}`;
if (discordChannel) {
try {
// Either send a new message, or update an old one
let existingMsgId = messageHistory[liveMsgDiscrim] || null;
if (existingMsgId) {
// Fetch existing message
discordChannel.messages.fetch(existingMsgId)
.then((existingMsg) => {
existingMsg.edit(msgFormatted, {
embed: msgEmbed
}).then((message) => {
// Clean up entry if no longer live
if (!isLive) {
delete messageHistory[liveMsgDiscrim];
liveMessageDb.put('history', messageHistory);
}
});
})
.catch((e) => {
// Unable to retrieve message object for editing
if (e.message === "Unknown Message") {
// Specific error: the message does not exist, most likely deleted.
delete messageHistory[liveMsgDiscrim];
liveMessageDb.put('history', messageHistory);
// This will cause the message to be posted as new in the next update if needed.
}
});
} else {
// Sending a new message
if (!isLive) {
// We do not post "new" notifications for channels going/being offline
continue;
}
// Expand the message with a #mention for "here" or "everyone"
// We don't do this in updates because it causes some people to get spammed
let mentionMode = (config.discord_mentions && config.discord_mentions[streamData.user_name.toLowerCase()]) || null;
if (mentionMode) {
mentionMode = mentionMode.toLowerCase();
if (mentionMode === "Nu-Live") {
// Reserved # keywords for discord that can be mentioned directly as text
mentionMode = `#${mentionMode}`;
} else {
// Most likely a role that needs to be translated to <#&id> format
let roleData = discordChannel.guild.roles.cache.find((role) => {
return (role.name.toLowerCase() === mentionMode);
});
if (roleData) {
mentionMode = `<#&${roleData.id}>`;
} else {
console.log('[Discord]', `Cannot mention role: ${mentionMode}`,
`(does not exist on server ${discordChannel.guild.name})`);
mentionMode = null;
}
}
}
let msgToSend = msgFormatted;
if (mentionMode) {
msgToSend = msgFormatted + ` ${mentionMode}`
}
let msgOptions = {
embed: msgEmbed
};
discordChannel.send(msgToSend, msgOptions)
.then((message) => {
console.log('[Discord]', `Sent announce msg to #${discordChannel.name} on ${discordChannel.guild.name}`)
messageHistory[liveMsgDiscrim] = message.id;
liveMessageDb.put('history', messageHistory);
})
.catch((err) => {
console.log('[Discord]', `Could not send announce msg to #${discordChannel.name} on ${discordChannel.guild.name}:`, err.message);
});
}
anySent = true;
} catch (e) {
console.warn('[Discord]', 'Message send problem:', e);
}
}
}
liveMessageDb.put('history', messageHistory);
return anySent;
});
This is the embed code:
const Discord = require('discord.js');
const moment = require('moment');
const humanizeDuration = require("humanize-duration");
const config = require('../data/config.json');
class LiveEmbed {
static createForStream(streamData) {
const isLive = streamData.type === "live";
const allowBoxArt = config.twitch_use_boxart;
let msgEmbed = new Discord.MessageEmbed();
msgEmbed.setColor(isLive ? "RED" : "BLACK");
msgEmbed.setURL(`https://twitch.tv/${(streamData.login || streamData.user_name).toLowerCase()}`);
// Thumbnail
let thumbUrl = streamData.profile_image_url;
if (allowBoxArt && streamData.game && streamData.game.box_art_url) {
thumbUrl = streamData.game.box_art_url;
thumbUrl = thumbUrl.replace("{width}", "288");
thumbUrl = thumbUrl.replace("{height}", "384");
}
msgEmbed.setThumbnail(thumbUrl);
if (isLive) {
// Title
msgEmbed.setTitle(`:red_circle: **${streamData.user_name} is live op Twitch!**`);
msgEmbed.addField("Title", streamData.title, false);
} else {
msgEmbed.setTitle(`:white_circle: ${streamData.user_name} was live op Twitch.`);
msgEmbed.setDescription('The stream has now ended.');
msgEmbed.addField("Title", streamData.title, true);
}
// Add game
if (streamData.game) {
msgEmbed.addField("Game", streamData.game.name, false);
}
if (isLive) {
// Add status
msgEmbed.addField("Status", isLive ? `Live with ${streamData.viewer_count} viewers` : 'Stream has ended', true);
// Set main image (stream preview)
let imageUrl = streamData.thumbnail_url;
imageUrl = imageUrl.replace("{width}", "1280");
imageUrl = imageUrl.replace("{height}", "720");
let thumbnailBuster = (Date.now() / 1000).toFixed(0);
imageUrl += `?t=${thumbnailBuster}`;
msgEmbed.setImage(imageUrl);
// Add uptime
let now = moment();
let startedAt = moment(streamData.started_at);
msgEmbed.addField("Uptime", humanizeDuration(now - startedAt, {
delimiter: ", ",
largest: 2,
round: true,
units: ["y", "mo", "w", "d", "h", "m"]
}), true);
}
return msgEmbed;
}
}
module.exports = LiveEmbed;
But it won't post the embed, only the msg. as you can see it updates teh msg aswell.
enter image description here
i'm stuck on this for four days now, can someone help?

Use for of loop to iterate the array

Assignment task4: Add the listStudents() method
In this task, you will add a method to the Bootcamp class that lists all the registered students' names and emails.
Create a method in the Bootcamp class named listStudents().
In the method body:
Check if the this.students array is empty.
If so, console.log() the message:
No students are registered to the ${this.name} bootcamp.
Then return the boolean value of false.
Otherwise, console.log() the line:
The students registered in ${this.name} are:
Then iterate through the entire this.students array and console.log() the name and email of each student on one line for each student. See the Testing section below for an example of the expected output.
You can do this with the for...of loop.
Finally, return the boolean value of true.
Testing code:
const runTest = (bootcamp, student) => {
const attemptOne = bootcamp.registerStudent(student);
const attemptTwo = bootcamp.registerStudent(student);
const attemptThree = bootcamp.registerStudent(new Student("Babs Bunny"));
if ( attemptOne && !attemptTwo && !attemptThree) {
console.log("TASK 3: PASS");
}
bootcamp.registerStudent(new Student('Babs Bunny', 'babs#bunny.com'));
if (bootcamp.listStudents()) {
console.log("TASK 4: PASS 1/2");
}
bootcamp.students = [];
if (!bootcamp.listStudents()) {
console.log("TASK 4: PASS 2/2");
}
};
My code below does not work. Please help me review. Thanks
class Bootcamp {
constructor(name, level, students = []){
this.name = name;
this.level = level;
this.students = students;
}
registerStudent(studentToRegister){
if (!studentToRegister.name || !studentToRegister.email) {
console.log("Invalid name or email");
return false;
} else if(this.students.filter(s => s.email === studentToRegister.email).length) {
console.log("This email is already registered");
return false;
} else {
this.students.push(studentToRegister)
console.log(`Successful registration ${studentToRegister.name} ${Bootcamp.name}`)
return true;
}
}
listStudent(registerStudent){
if(this.students.length === 0)
{
console.log(`No students are registered to the ${this.name} bootcamp.`);
return false;
}
else
{
console.log(`The students registered in ${this.name} are:`);
for(const registerStudent of this.students)
{
console.log("Name:" + registerStudent[name] + "Email:" + registerStudent[email]);
return true;
}
}
}
}
listStudents() {
if (this.students.length == 0) {
console.log("No students are registered to the ${this.name} bootcamp");
return false;
} else {
console.log("The students registered in ${this.name} are:");
for (let student of this.students) {
console.log(`Name: ${student.name} Email: ${student.email}`);
}
return true;
}
}
}

Discord.JS bot not responding to several commmands

My bot is not responding to any commands except for the .purge command.
Here is my code.
const { Client, MessageEmbed } = require('discord.js');
const client = new Client();
const { prefix, token } = require('./config.json');
client.on('ready', () => {
client.user.setStatus('invisible');
console.log('Bot ready!');
client.user.setActivity('Bot is in WIP Do not expect stuff to work', {
type: 'STREAMING',
url: "https://www.twitch.tv/jonkps4"
});
console.log('Changed status!');
});
client.on('message', message => {
if (message.content.startsWith(".") || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (message === 'apply') {
message.reply("The Small Developers Application form link is:")
message.reply("https://forms.gle/nb6QwNySjC63wSMUA")
}
if (message === 'kick') {
const user = message.mentions.users.first();
// If we have a user mentioned
if (user) {
// Now we get the member from the user
const member = message.guild.member(user);
// If the member is in the guild
if (member) {
member
.kick('Optional reason that will display in the audit logs')
.then(() => {
// We let the message author know we were able to kick the person
message.reply(`Successfully kicked ${user.tag}`);
})
.catch(err => {
message.reply('I was unable to kick the member \n Maybe due to I having missing permissions or My role is not the higher than the role the person to kick has');
// Log the error
console.error(err);
});
} else {
// The mentioned user isn't in this guild
message.reply("That user isn't in this guild!");
}
// Otherwise, if no user was mentioned
} else {
message.reply("You didn't mention the user to kick!");
}
}
if (command === 'purge') {
const amount = parseInt(args[0]) + 1;
if (isNaN(amount)) {
return message.reply('Not a valid number');
} else if (amount > 100) {
return message.reply('Too many messages to clear. \n In order to clear the whole channel or clear more please either ```1. Right click on the channel and click Clone Channel``` or ```2. Execute this command again but more times and a number less than 100.```');
} else if (amount <= 1) {
return message.reply('Amount of messages to clear **MUST** not be less than 1 or more than 100.')
}
message.channel.bulkDelete(amount, true).catch(err => {
console.error(err);
message.channel.send('**There was an error trying to prune messages in this channel!**');
});
}
});
client.login(token);
I need a specific command to work which is the .apply command
and i would like to know why my embeds do not work.
I tried this embed example It didn't work.
const embed = new MessageEmbed()
// Set the title of the field
.setTitle('A slick little embed')
// Set the color of the embed
.setColor(0xff0000)
// Set the main content of the embed
.setDescription('Hello, this is a slick embed!');
.setThumbnail('https://tr.rbxcdn.com/23e104f6348dd71d597c3246990b9d84/420/420/Decal/Png')
// Send the embed to the same channel as the message
message.channel.send(embed);
What did I do wrong? I am quite new to Discord.JS Any help would be needed.
You used the message parameter instead of command. Instead of message === 'xxx' put command === 'xxx'. Simple mistake, I think that was what you meant anyways. Of course the purge command worked because you put command === 'purge' there

(Discord.js) Bot does not respond

I've made a bot, and I have this purge function, it worked before i added the if that checked for the user's role. It gives me no errors and doesnt reply at all, no matter if i have the roles or not.
Code:
client.on("message", message => {
if (message.content.startsWith(prefix("purge"))) {
if (!message.guild.member.roles.cache.get('703727486009213048') || !message.guild.member.roles.cache.get('702847833241550859') || !message.guild.member.roles.cache.get('703727579328151562')) {
console.log('ssadd')
return message.reply('you can\'t use that command!')
};
const args = message.content.slice(prefix.length).split(" ");
const amount = args[1];
if (!amount) {
return message.reply("please specify the number of messages to purge!");
}
if (isNaN(amount * 1)) {
return message.reply(
"you'll need to specify a number, not whatever \"" +
`${amount}` +
'" is.'
);
}
message.delete();
message.channel.bulkDelete(amount * 1 + 1);
};
});
client.login(process.env.token);```
If it never replied to anything that either means the bot didn't log in or it never passed the first if condition. To check if the bot logged in, just do client.on("ready", () => console.log("ready"))
But I think it's more likely it just failed the first condition, is prefix a function?
prefix("purge") should be prefix + "purge".
There are some other flaws in your code too. Heres just the redo, if you need me to explain anything just lmk.
client.on("message", msg => {
if (msg.author.bot || !msg.content.startsWith(prefix)) return;
const args = msg.content.slice(1).split(" ");
//later on you should move to modules but for now this is fine ig
if (args[0] === "purge") {
//other flags here https://discord.js.org/#/docs/main/stable/class/Permissions?scrollTo=s-FLAGS
if (!msg.member.hasPermission("ADMINISTRATOR")) {
return msg.reply("you can't use that command!")
}
const amount = args[1] && parseInt(args[1]);
if (!amount) {
return msg.reply("please specify an integer of messages to purge!");
}
msg.delete();
msg.channel.bulkDelete(amount);
};
});
client.login(process.env.token);

Resources