I want to check if a user has a role but when I try to get the user it always returns the bot user, not the wanted user. How can I go about fixing this?
Here's my code:
const member = client.guilds.cache.get(localVars.ServerID).members.cache.find((member) => {
console.log(member.username);
return member.username == localVars.username;
});
const role = client.guilds.cache.get(localVars.ServerID).roles.cache.find((role) => {
return role.name === localVars.RoleName;
});
console.log(member);
if (member.roles.cache.get(role.id)) {
localVars.ReturnValue = 1;
} else {
localVars.ReturnValue = 0;
}
Your code is a little bit overcomplicated and some things are just unneccessary / wrong, e.g. that you call return in the find() and get() functions :D
You could simplify it like this:
const { guilds } = client;
const targetGuild = guilds.cache.get(localVars.ServerID);
const member = targetGuild.members.cache.find(user => user.username === localVars.username);
const role = targetGuild.roles.cache.find(role => role.name === localVars.RoleName);
if(member.roles.cache.has(role.id)) {
localVars.ReturnValue = 1
} else {
localVars.ReturnValue = 0
}
Related
my code
function kanalbackup() {
let guild = client.guilds.cache.get(ayarlar.guildID);
if (!guild) return;
if (guild) {
guild.channels.cache.filter(kanal => kanal.deleted !== true).forEach(channel => {
let permissionss = {};
let sayi = Number(0);
channel.PermissionOverwriteManager.forEach((perm) => {
let thisPermOverwrites = {};
perm.allow.toArray().forEach(p => {
thisPermOverwrites[p] = true;
});
perm.deny.toArray().forEach(p => {
thisPermOverwrites[p] = false;
});
permissionss[sayi] = {permission: perm.id == null ? guild.id : perm.id, thisPermOverwrites};
sayi++;
})
error
Channel#deleted is deprecated,
(Use node --trace-deprecation ... to show where the warning was created)
TypeError: channel.permissionOverwrites.forEach is not a function
Discord js upgrade error v12 to v13 ı need help
Basically the function channel.deleted has been removed from discord.js and you can't use it anymore. Full article on this: https://github.com/discordjs/discord.js/issues/7091. You can simply remove the filter in the channel cache to solve the problem. It also appears that you haven't created a permissionOveriteManager, and it's spelled wrong. The code would then look like the following:
function kanalbackup() {
let guild = client.guilds.cache.get(ayarlar.guildID);
if (!guild) return;
if (guild) {
guild.channels.cache.forEach(channel => {
let permissionss = {};
let sayi = Number(0);
channel.permissionOverwriteManager.create().forEach((perm) => {
let thisPermOverwrites = {};
perm.allow.toArray().forEach(p => {
thisPermOverwrites[p] = true;
});
perm.deny.toArray().forEach(p => {
thisPermOverwrites[p] = false;
});
permissionss[sayi] = {permission: perm.id == null ? guild.id : perm.id, thisPermOverwrites};
sayi++;
})
i get error
let executor = await this.members.fetch(executorID);
^^^^^
SyntaxError: await is only valid in async function
when using the code below (use is to check if user breaks any of set filters and if so remove roles or ban user whatever they set option to)
ive tried my best to lable what parts of code does please not english isnt my first language
ive only recieved this error since trying to add a check whitelist feature - everything else works without the whitelist check code
without the code for whitelist the code works and performs as intended and the whitelist code succesfully logs ids for that guild
if(whitelisted && whitelisted.length) {
whitelisted.forEach(x => {
if (executorID === x.user) return;
const { Structures } = require('discord.js');
let whitelisted = db.get(`whitelist_${message.guild.id}`)
const { limits, defaultPrefix } = require('../config.js');
Structures.extend('Guild', Guild => {
class GuildExt extends Guild {
constructor(...args) {
super(...args);
}
get prefix() {
return this.get('prefix', defaultPrefix);
}
get(key, fallback) {
return this.client.db.get(`${this.id}_${key}`) || fallback;
}
set(key, data) {
return this.client.db.set(`${this.id}_${key}`, data);
}
delete(key) {
return this.client.db.delete(`${this.id}_${key}`);
}
resolveChannel(channelID) {
const channel = this.channels.cache.get(channelID);
return channel;
}
get limits() {
var obj = {};
for (var k in limits) {
obj[k] = {
minute: this.get(
`limits.${k}.minute`,
limits[k].per_minute
),
hour: this.get(`limits.${k}.hour`, limits[k].per_hour)
};
}
return obj;
}
getActions(limit = 10, filter = () => true) {
var obj = {};
var l = limits;
for (var k in limits) {
obj[k] = {
name: this.client.Utils.toProperCase(k),
actions: this.client.Utils.convertEntries(
[
...this.get(
this.client.Utils.convertLimitNameToActionType(
k
),
[]
),
...this.get(
`archive.${this.client.Utils.convertLimitNameToActionType(
k
)}`,
[]
)
]
.filter(filter)
.slice(0, limit)
)
};
}
return obj;
}
find_entry(action, filter) {
let guild = this;
return new Promise(resolve => {
(async function search(iter) {
//console.log(`ACTION = ${action} | ITER = ${iter}`);
if (!guild.me) return resolve(null);
if (guild.me.hasPermission('VIEW_AUDIT_LOG')) {
let logs = await guild.fetchAuditLogs({
limit: 10,
type: action
});
let entries = logs.entries;
let entry = null;
entries = entries.filter(filter);
for (var e of entries)
if (!entry || e[0] > entry.id) entry = e[1];
if (entry) return resolve(entry);
}
if (++iter === 5) return resolve(null);
else return setTimeout(search, 200, iter);
})(0);
});
}
push_entry(entry, displayName) {
const action = ['MEMBER_KICK', 'MEMBER_BAN_ADD'].includes(
entry.action
)
? 'MEMBER_REMOVE'
: entry.action;
const oneHourAgo = Date.now() - 1000 * 60 * 60;
// Fetch Entries for a sepcific action (Last Hour)
let entries = this.get(action, []);
// Filter entries older than one hour to a new variable
let olderThanOneHour = entries.filter(
i => !(i.timestamp > oneHourAgo)
);
// Prepend entries older than one hour to the archive
if (olderThanOneHour.length > 0)
this.set(`archive.${action}`, [
...olderThanOneHour,
...this.get(`archive.${action}`, [])
]);
// Filter entries older than one hour from old variable
entries = entries.filter(i => i.timestamp > oneHourAgo);
// Prepend new entry if not already found
if (
!entries.find(
i =>
i.target.id === entry.target.id &&
i.executor.id === entry.executor.id
)
)
entries.unshift({
timestamp: entry.createdTimestamp,
action: entry.action,
target: {
id: entry.target.id,
displayName,
targetType: entry.targetType
},
executor: {
id: entry.executor.id,
displayName: entry.executor.tag
}
});
// Update entries newer than one hour
return this.set(action, entries);
}
async check_limits(entries, executorID, configAction) {
// Ignore if executor is the owner or is whitelisted
if (executorID === this.ownerID) return;
if(whitelisted && whitelisted.length) {
whitelisted.forEach(x => {
if (executorID === x.user) retrun;
// Filter actions relating to executor
const oneMinuteAgo = Date.now() - 1000 * 60;
let executorActionsHour = entries.filter(
i => i.executor.id === executorID
);
let executorActionsMinute = executorActionsHour.filter(
i => i.timestamp > oneMinuteAgo
);
console.log(
`${configAction}/${executorID}: LAST_HOUR: ${executorActionsHour.length} LAST_MINUTE: ${executorActionsMinute.length} `
);
let limits = this.limits;
let limitReached = null;
if (executorActionsHour.length >= limits[configAction].hour)
limitReached = 'Hour';
if (executorActionsMinute.length >= limits[configAction].minute)
limitReached = 'Minute';
// Check if the amount of actions is greater than or equal to the limit
if (limitReached) {
// Remove all of the executor's roles
let executor = await this.members.fetch(executorID);
executor.roles.remove(executor.roles.cache);
// Handle managed roles
let managed = executor.roles.cache
.filter(r => r.managed)
.array();
for (var i = 0; i < managed.length; i++)
managed[i].setPermissions(0, 'Guardian Action');
// Notify owner, executor, and logging channel
const embed = this.client.util
.embed()
.setTitle(`Limit Reached - ${limitReached}`)
.setDescription(
this.client.Utils.convertEntries(
limitReached === 'Hour'
? executorActionsHour
: executorActionsMinute
)
)
.setColor(0x7289da);
await this.owner.send(
embed.setFooter(
"This message was sent to you because you're the Guild owner."
)
);
await executor.send(
embed.setFooter(
'This message was sent to you because you were the executor.'
)
);
const loggingChannel = this.resolveChannel(
this.get(`loggingChannelID`)
);
if (loggingChannel)
await loggingChannel.send(embed.setFooter(''));
}
})
}
}
}
return GuildExt;
});
i am new to JS and any help would be appreciated
please dont hate if i do have bad syntax !!
i am new - sorry if i dont get things the first time
You forgot to make your forEach function async, just change it to:
/* ... */
whitelisted.forEach(async (x) => {
/* ... */
let executor = await this.members.fetch(executorID);
/* ... */
}
/* ... */
Not part of your question but you misspelled return here
if (executorID === x.user) retrun;
Your line
let executor = await this.members.fetch(executorID);
is inside a non-async anonymous function in:
if (whitelisted && whitelisted.length) {
whitelisted.forEach(x => { // <- This line
if (executorID === x.user) return;
// ...
Try changing it with:
if (whitelisted && whitelisted.length) {
whitelisted.forEach(async (x) => { // <- Use async here
if (executorID === x.user) return;
// ...
Also, avoid using forEach to make asynchronous calls.
for a gaming app, a player can select card types for his/her deck (first eachfor) and amount of each card type (2nd each.for). After this, I want to push this selection in an array.
Following part of my code works well:
//defining card types
let availableRoles = ["werwolf", "dorfbewohner", "seherin", "hexe", "jaeger", "armor", "heiler", "prinz"]
let gameState = {
roles: {}
}
//set card amount 0
;(() => {
availableRoles.forEach(role => gameState.roles[role] = 0)
})()
//adding & subtracting roles
const addRole = role => {
gameState.roles[role]++
document.getElementById(role + "_btn_remove").disabled = false;
document.getElementById(role + '_cnt').innerHTML = gameState.roles[role];
document.getElementById('total_cnt').innerHTML = totalNumberOfRolesInGame();
}
const removeRole = role => {
gameState.roles[role]--
if (gameState.roles[role] <= 0) {
gameState.roles[role] = 0
document.getElementById(role + "_btn_remove").disabled = true;
}
document.getElementById(role + '_cnt').innerHTML = gameState.roles[role];
document.getElementById('total_cnt').innerHTML = totalNumberOfRolesInGame();
}
const totalNumberOfRolesInGame = () => Object.values(gameState.roles).reduce((a,c) => a + c)
Now I want to hit every role and hit every number insider the role by using for each command. But it does not work.
var rollen = []
function Holmir() {
;(() => {
gameState.roles.forEach(element => element.forEach (myRole => rollen.push(myRole))
) })()
{
I'm thankful for any help!
forEach works with an array.
gameState = {
roles: {}
}
gameState.roles gives you an object so forEach won't work with this
I'm trying to dm all users in my private server with all my friends however some of them don't want to be dmed so they turn off their dms. Because of this, I get an error which stops the bot from continuing on to the other users. How can I skip over that user when the error is found and tell my bot to continue to dm the next user after.
heres my code
const commando = require('discord.js-commando');
const app = require('../../app.js');
const config = require('../../config.json');
const Discord = require('discord.js');
class DMallCommand extends commando.Command {
constructor(client){
super(client, {
name: `dmall`,
group: 'dms',
memberName: 'dmall',
description: 'Sends message provided to all members of the guild.',
examples: [ `${config.prefix}dmall Hey everyone! This might reach more people than a mass ping...` ]
});
}
async run(message, args){
let dmGuild = message.guild;
let role = message.mentions.roles.first();
var msg = message.content;
try {
msg = msg.substring(msg.indexOf("dmall") + 5);
} catch(error) {
console.log(error);
return;
}
if(!msg || msg.length <= 1) {
const embed = new Discord.RichEmbed()
.addField(":x: Failed to send", "Message not specified")
.addField(":eyes: Listen up!", "Every character past the command will be sent,\nand apparently there was nothing to send.");
message.channel.send({ embed: embed });
return;
}
let memberarray = dmGuild.members.array();
let membercount = memberarray.length;
let botcount = 0;
let successcount = 0;
console.log(`Responding to ${message.author.username} : Sending message to all ${membercount} members of ${dmGuild.name}.`)
for (var i = 0; i < membercount; i++) {
let member = memberarray[i];
if (member.user.bot) {
console.log(`Skipping bot with name ${member.user.username}`)
botcount++;
continue
}
let timeout = Math.floor((Math.random() * (config.wait - 0.01)) * 1000) + 10;
await sleep(timeout);
if(i == (membercount-1)) {
console.log(`Waited ${timeout}ms.\t\\/\tDMing ${member.user.username}`);
} else {
console.log(`Waited ${timeout}ms.\t|${i + 1}|\tDMing ${member.user.username}`);
}
try {
member.send(`${msg} \n #${timeout}`);
successcount++;
} catch (error) {
console.log(`Failed to send DM! ` + error)
}
}
console.log(`Sent ${successcount} ${(successcount != 1 ? `messages` : `message`)} successfully, ` +
`${botcount} ${(botcount != 1 ? `bots were` : `bot was`)} skipped.`);
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
module.exports = DMallCommand;
I understand I am not handling any errors but I am not sure how to go about this and could really use some help
Also here is my bot.js code
const Discord = require('discord.js');
const figlet = require('figlet');
const colors = require('colors');
const readline = require('readline');
const commando = require(`discord.js-commando`);
const config = require('./config.json');
const bot = new commando.Client({
commandPrefix:'£',
owner: config.id
});
const cmdsArray = [
"dmall <message>",
"dmrole <role> <message>"
];
bot.on("ready", () => {
clear();
console.log('______')
bot.user.setActivity('PRDX');
});
bot.on("error", (error) => {
bot.login(config.token);
});
bot.registry.registerGroup('dms', 'help');
bot.registry.registerDefaults();
bot.registry.registerCommandsIn(__dirname + "/commands");
if (process.env.BOT_TOKEN) bot.login(process.env.BOT_TOKEN);
else bot.login(config.token);
}
Anywhere in your code use an error event listener
client.on("error", () => { client.login(token) });
You'll want to catch the error, basically, if that error happens, you want it to just pass by and ignore the error. In Javascript this is known as try and catch. Read about it below then apply it to wherever the error is being identified.
https://www.w3schools.com/js/js_errors.asp
You can use .catch() block, member.send('Message') return a promise with succes sended message or error. So you can use
member.send('message').catch(console.error)
currently trying to get my code to notice the beginning of a message if its "www" or "https" and then checking if they're associated with either reddit or youtube, I've tried multiple different posts (there arent very many on the discord API for javascript) so Im kinda stumpted at this point
const botconfig = require("./botconfig.json");
const Discord = require("discord.js");
const bot = new Discord.Client();
var protect = false;
const forbidenWords = ['reddit', 'youtube']
const Message = ''
bot.login(botconfig.token);
let prefix = "!";
bot.on("message", (message) => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
if (message.content.startsWith(prefix + "protect")) {
message.channel.send("PROTECT THE KING!!!!");
protect = true;
console.log('protecc is true')
} else
if (message.content.startsWith(prefix + "stop")) {
message.channel.send("I will now stop :(");
protect = false;
}
if(protect == true && message.content.startsWith("www" || "https")){
console.log('isWebsite true')
for (var i = 0; i < forbidenWords.length; i++) {
if (message.content.includes(forbidenWords[i])) {
break;
}
}
}
});
any help on this is greatly appreciated.
Move the additional logic into a helper function.
function startsWithWebsiteToken(message) {
const tokens = ['https', 'www'];
const length = tokens.length;
for (let i = 0; i < length; i++) {
if ( message.startsWith(tokens[i]) )
return true;
}
return false;
}
if (protect === true && startsWithWebsiteToken(message.content)) {
console.log('isWebsite true');
}
You can define a custom function for this
START_TOKENS = ['https','https','www'];
function doesUrlStartWithToken(url) {
return START_TOKENS.reduce((accumulator, currentValue) => {
if (accumulator) {
return true;
}
return currentValue.startsWith(url);
}, false);
}
Alternatively, if you only need to support browser which support new URL(), it becomes easier to detect certain domains
const SPECIAL_DOMAINS = ['youtube.com', 'reddit.com']
function isSpecialDomain(url) {
const deconstructedUrl = new URL(url)
const domain = deconstructedUrl.hostname.replace('www.','');
return SPECIAL_DOMAINS.reduce((e, val) => e || domain === val, false);
}