Discord.js Missing Permissions while adding user to role - node.js

I am running into an "DiscordAPIError: Missing Permissions " error when trying to add a member to a role. My code is:
const role: Role = await this.getRole(requestingUser, roleId);
const member: GuildMember = await this.getGuildMember(memberId);
await member.roles.add(role);
The client should have the intents it needs. This is the code we use for getting the client instance for the calls:
async getClient () {
if (!this.client) {
// eslint-disable-next-line no-async-promise-executor
this.client = await new Promise(async (resolve, reject) => {
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MEMBERS,
Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS,
Intents.FLAGS.GUILD_MESSAGES
]
});
client.on('error', async (error) => {
reject(error);
});
client.on('ready', async () => {
resolve(client);
});
await client.login(this.botToken);
});
}
return this.client;
}
The bot does have have 'manage roles' permission:
The stack trace once it hits discord.js code:
DiscordAPIError: Missing Permissions
at RequestHandler.execute (/usr/src/app/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/usr/src/app/node_modules/discord.js/src/rest/RequestHandler.js:51:14)
at async GuildMemberRoleManager.add (/usr/src/app/node_modules/discord.js/src/managers/GuildMemberRoleManager.js:124:7)
This is using discord.js 13.6.0 and node.js 16.6.0
Any ideas?

If a role is higher than a user or bot's highest role, it's basically read-only for you, even if you have the ADMINISTRATOR permission. The only thing that bypasses this is being the owner. Either move the bot's role up, the role being given down, or do a check and send an error message if it's higher
if (
role.position >= guild.me.roles.highest.position ||
!guild.me.permissions.has("MANAGE_ROLES")
) return interaction.reply({
content: "I don't have permissions to grant this role!",
ephemeral: true
})

Related

Botkit- controller.trigger() function is crashing the node.js app

controller.hears('hi', 'direct_message', async(bot, message) => {
controller.trigger('test', bot, message);
});
controller.on('test', async (bot,message) => {
await bot.reply(message, 'triggerd test');
});
The above code is working as expected but as soon as I get a reply 'triggered test' on Slack after that the app crashes with this error
C:\Users\Lenovo\Documents\Nodejs Project\chatbots\slackbot\node_modules\botbuilder-core\lib\turnContext.js:387
this.responded = true;
^
TypeError: Cannot perform 'set' on a proxy that has been revoked
at Proxy.<anonymous> (C:\Users\Lenovo\Documents\Nodejs Project\chatbots\slackbot\node_modules\botbuilder-core\lib\turnContext.js:387:36)
at Generator.next (<anonymous>)
at fulfilled (C:\Users\Lenovo\Documents\Nodejs Project\chatbots\slackbot\node_modules\botbuilder-core\lib\turnContext.js:9:58)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
when I use this code then app doesn't crash
controller.hears('hi', 'direct_message', async(bot, message) => {
await bot.reply(message, 'triggerd test');
});
What am I missing in my code?
This can be fixed by using similar code in this link https://github.com/howdyai/botkit/issues/1856
controller.on('test', async (bot,message) => {
await bot.changeContext(message.reference)
await bot.reply(message, 'triggerd test');
});

Firebase Admin SDK network app/network-error

I have the following nodejs script.
const admin = require("firebase-admin")
admin.initializeApp({
credential: admin.credential.cert("./serviceAccountKey.json"),
databaseURL: "https://<ProjectID>.firebaseio.com/"
})
const uid = "5mP5FvjjCKcJ1IBXfV3rpChd3ob2"
admin
.auth()
.setCustomUserClaims(uid, { role: 'admin' })
.then(() => {
// The new custom claims will propagate to the user's ID token the
// next time a new one is issued.
console.log(`Admin claim added to ${uid}`)
})
.catch((err) => console.log(err))
When I run the script I get the following error.
{
errorInfo: {
code: 'app/network-error',
message: 'Error while making request: connect ECONNREFUSED 127.0.0.1:9099. Error code: ECONNREFUSED'
},
codePrefix: 'app'
}
What am I doing wrong here?
Also, my firebase project has the spark plan.

discord.js bot crashes after trying to send a message in a channel it can't send messages

Well discord.js bot crashes after trying to send a message in a channel it sees but can't send messages
well I get a crash after that, how can I fix this? here is the error it shows it shows for other commands too
/home/pi/Desktop/floppa_gaming/node_modules/discord.js/src/rest/RequestHandler.js:298
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Missing Permissions
at RequestHandler.execute (/home/pi/Desktop/floppa_gaming/node_modules/discord.js/src/rest/RequestHandler.js:298:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/pi/Desktop/floppa_gaming/node_modules/discord.js/src/rest/RequestHandler.js:50:14)
at async TextChannel.send (/home/pi/Desktop/floppa_gaming/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:171:15) {
method: 'post',
path: '/channels/785243249072930869/messages',
code: 50013,
httpStatus: 403,
requestData: {
json: {
content: 'You can use get help by saying "floppa help" in the chat :wink:',
tts: false,
nonce: undefined,
embeds: undefined,
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
},
files: []
}
}
and if anyobody wants to see my terrible code here it is
const { Client, Intents, MessageEmbed, Permissions } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES,] });
var fs = require('fs');
var files = fs.readdirSync('./floppa/');
client.on('ready', () => {
client.user.setStatus('invisible') //You can set idle, dnd or invisible
client.user.setActivity("use floppa to get a image!", { type: 'PLAYING' }) // PLAYING , LISTENING , WATCHING , STREAMING
console.log("on discord lol");
});
const { AutoPoster } = require('topgg-autoposter')
const poster = AutoPoster('token', client) // tells topgg amount of servers ur bot is in
// optional
poster.on('posted', (stats) => { // ran when succesfully posted
console.log(`Posted stats to Top.gg | ${stats.serverCount} servers`)
})
client.on('message', msg => {
if (msg.content === 'floppa')
{
imageNumber = files[Math.floor(Math.random()*files.length)]
msg.channel.send ( {files: ["./floppa/" + imageNumber]} )
}
// finds a random image in a folder
The error shown is: DiscordAPIError: Missing Permissions
This means that your bot does not have permission to send messages in that channel. To avoid your bot crashing when this happens, you need to do one of the following:
Catch the error:
msg.channel.send("stuff").catch((err) => {/* handle errors */});
Verify that your bot has the permissions to post before posting:
if (msg.guild && msg.channel.permissionsFor(msg.guild.me).has("SEND_MESSAGES"))) {
msg.channel.send("stuff");
}

creating custom token in cloud function after reteiving data from realtime database

i want to create custom token in cloud function but before that I want to check and compare timestamp from realtime database and with current time.if the timestamp is below 10 min then I want to create custom token and send back to client.please help me to achieve this.i am new to this cloud function firebase.
here is my code
export const authaccount = functions.https.onCall(async (data) => {
try {
const snap= await admin.database().ref("/register/"+data).get();
const time=snap.val().timestamp;
const now=new Date().getDate();
const reg=new Date(time).getDate();
const today=Math.abs(now-reg);
const daydiff=Math.floor(today/1000/60/60/24);
const nowminutes=new Date().getUTCMinutes();
const regminutes=new Date(time).getUTCMinutes();
const timediff=Math.abs(nowminutes-regminutes);
if (timediff<10 && daydiff==0) {
try {
admin.auth().createCustomToken(data).then((customtoken)=>{
console.log("auth created"+" "+timediff+" "+daydiff+" "+customtoken);
return customtoken;
});
} catch (err1) {
throw new functions.https.HttpsError("unknown", err1.message, err1);
}
} else {
console.log("else "+" "+now+" "+reg+" "+time+" "+daydiff);
}
} catch (err2) {
throw new functions.https.HttpsError("unknown", err2.message, err2);
}
});
2:53:20.626 AM
authaccount
Error: Process exited with code 16 at process.<anonymous> (/layers/google.nodejs.functions-framework/functions-framework/node_modules/#google-cloud/functions-framework/build/src/invoker.js:275:22) at process.emit (events.js:314:20) at process.EventEmitter.emit (domain.js:483:12) at process.exit (internal/process/per_thread.js:168:15) at Object.sendCrashResponse (/layers/google.nodejs.functions-framework/functions-framework/node_modules/#google-cloud/functions-framework/build/src/logger.js:37:9) at process.<anonymous> (/layers/google.nodejs.functions-framework/functions-framework/node_modules/#google-cloud/functions-framework/build/src/invoker.js:271:22) at process.emit (events.js:314:20) at process.EventEmitter.emit (domain.js:483:12) at processPromiseRejections (internal/process/promises.js:209:33) at processTicksAndRejections (internal/process/task_queues.js:98:32)
2:53:19.559 AM
authaccount
Error: The caller does not have permission; Please refer to https://firebase.google.com/docs/auth/admin/create-custom-tokens for more details on how to use and troubleshoot this feature. at FirebaseAuthError.FirebaseError [as constructor] (/workspace/node_modules/firebase-admin/lib/utils/error.js:44:28) at FirebaseAuthError.PrefixedFirebaseError [as constructor] (/workspace/node_modules/firebase-admin/lib/utils/error.js:90:28) at new FirebaseAuthError (/workspace/node_modules/firebase-admin/lib/utils/error.js:149:16) at Function.FirebaseAuthError.fromServerError (/workspace/node_modules/firebase-admin/lib/utils/error.js:188:16) at /workspace/node_modules/firebase-admin/lib/auth/token-generator.js:114:53 at processTicksAndRejections (internal/process/task_queues.js:97:5) at async Promise.all (index 1)
2:53:19.558 AM
authaccount
Unhandled rejection
2:53:19.469 AM
authaccount
Function execution took 1386 ms, finished with status code: 200
please help to solve this problem. i don't know where I am making the mistake.
You will need to make sure your Firebase Admin sdk is initiated and running before the function proceeds
if (firebase.apps.length === 0) {
firebase.initializeApp();
}
Resource: https://firebase.google.com/docs/admin/setup#initialize-without-parameters
I doubt you have modified the IAM permissions on your service account but as the comment suggested: https://firebase.google.com/docs/auth/admin/create-custom-tokens#service_account_does_not_have_required_permissions
Once that is confirmed to be working - you will need to ensure that the onCall data is a string and not null, some simple health checks can help you debug your process
console.log(typeof data);
console.warn("Data", data);
from there I would also debug your date times and the realtime database result, these are async and will require the promise to be resolved before you can use it.
Update:
All cloud functions should return a response to the client
onCall uses promises on the client and supports a 'return Object'
example:
return {
token: myCustomToken,
possible: otherValue
};
for comparison, onRequest uses fetch like responses and supports codes
response.status(500)
response.send({name:value})
return;
Source:
https://firebase.google.com/docs/functions/callable#sending_back_the_result
Source:
https://firebase.google.com/docs/functions/http-events#using_express_request_and_response_objects
Update:
all paths and promises need to resolve correctly, this includes awaiting promises to resolve and returning their result or storing the result for any secondary processing - I suggest cleaning up the code, remove the try/catch and use .then().catch()
Example:
if (timediff<10 && daydiff==0) {
return await admin.auth().createCustomToken(data)
.then((customtoken)=>{
console.log("auth created"+" "+timediff+" "+daydiff+" "+customtoken);
return customtoken;
})
.catch (err) {
return new functions.https.HttpsError("unknown", err.message, err);
}
}
else {
console.log("else "+" "+now+" "+reg+" "+time+" "+daydiff);
return "else "+" "+now+" "+reg+" "+time+" "+daydiff;
}

Keep getting the "ConfigError: Missing region in config" error in Node.js no matter what I do

I keep getting the "UnhandledPromiseRejectionWarning: ConfigError: Missing region in config" when trying to make requests to APIs I have set up in Node.js.
I'm new to DynamoDB and after setting up most of my boilerplate code I'm using Postman to test my routes. However I keep getting the same error each time I make a post request. I've checked some solutions on existing threads, namely: Configuring region in Node.js AWS SDK but cannot get it to work.
I am currently developing the app locally and checked the database where the items are being added.
My setup is as follows:
// user_controller.js
const uuid = require('uuid');
const sanitizer = require('validator');
const bcrypt = require('bcryptjs-then');
const AWS = require('aws-sdk');
const config = require('../config/config');
const { signToken, userByEmail, userById } = require('../Helpers/Users');
const isDev = true
Then in my code block I have the following:
// user_controller.js
(...)
if (isDev) {
AWS.config.update(config.aws_local_config);
} else {
AWS.config.update(config.aws_remote_config);
}
const DB = new AWS.DynamoDB.DocumentClient();
const params = {
TableName: config.aws_table_name,
Item: {
userId: await uuid.v1(),
firstName: sanitizer.trim(firstName),
lastName: sanitizer.trim(lastName),
email: sanitizer.normalizeEmail(sanitizer.trim(email)),
password: await bcrypt.hash(password, 8),
level: 'standard',
createdAt: new Date().getTime(),
updatedAt: new Date().getTime(),
},
}
return userByEmail(params.Item.email) // Does the email already exist?
.then(user => { if (user) throw new Error('User with that email exists') })
.then(() => DB.put(params).promise()) // Add the data to the DB
.then(() => userById(params.Item.id)) // Get user data from DB
.then(user => (err, data) => {
console.log("AFTER USER CREATED")
if (err) {
res.send({
success: false,
message: 'Error: Server error'
});
} else {
console.log('data', data);
res.send({
statusCode: 201,
message: 'Success - you are now registered',
data: { token: signToken(params.Item.id), ...user },
});
}
})
(...)
Finally I am importing the config from separate file:
// config.js
module.exports = {
aws_table_name: 'usersTable',
aws_local_config: {
region: 'local',
endpoint: 'http://localhost:8000'
},
aws_remote_config: {}
}
In have already configured the aws-sdk:
AWS Access Key ID [****************foo]:
AWS Secret Access Key [****************bar]:
Default region name [local]:
Default output format [json]:
Here is the output I keep getting:
(node:4568) UnhandledPromiseRejectionWarning: ConfigError: Missing region in config
at Request.VALIDATE_REGION (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/event_listeners.js:92:45)
at Request.callListeners (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/sequential_executor.js:106:20)
at callNextListener (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/sequential_executor.js:96:12)
at /Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/event_listeners.js:86:9
at finish (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/config.js:350:7)
at /Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/config.js:368:9
at SharedIniFileCredentials.get (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/credentials.js:127:7)
at getAsyncCredentials (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/config.js:362:24)
at Config.getCredentials (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/config.js:382:9)
at Request.VALIDATE_CREDENTIALS (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/event_listeners.js:81:26)
(node:4568) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 4)
(node:4568) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Like I said, I've tried a lot of variations on this but to no avail. Would love some help, thanks.
I dont know if this helps, but I used none instead of local for the region and it seemed to work for me
AWS.config.update({ region: 'none' })

Resources