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

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');
});

Related

Discord.js Missing Permissions while adding user to role

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
})

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;
}

Ytdl-core is not working properly - "Could not find player config"

This error has started occurring on songs that worked perfectly previously.
Error:
Error: Could not find player config
at exports.getBasicInfo (/app/node_modules/ytdl-core/lib/info.js:90:13)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:93:5)
at async Map.getOrSet (/app/node_modules/ytdl-at async exports.getInfo (/app/node_modules/ytdl-core/lib/info.js:215:14)
at async Map.getOrSet (/app/node_modules/ytdl-core/lib/cache.js:24:19)
at async Object.execute (/app/commands/play.js:59:20)
For some reason, if I try the same video multiple times eventually it'll work
but now, it is not working forever on any video i play.
play part:
const dispatcher = queue.connection
.play(stream, { type: streamType })
.on("finish", () => {
if (collector && !collector.ended) collector.stop();
if (queue.loop) {
let lastSong = queue.songs.shift();
queue.songs.push(lastSong);
module.exports.play(queue.songs[0], message);
} else {
// Recursively play the next song
queue.songs.shift();
module.exports.play(queue.songs[0], message);
}
})
.on("error", (err) => {
console.error(err);
queue.songs.shift();
module.exports.play(queue.songs[0], message);
});
I have a similar issue, the problem is that this is currently an ongoing issue for everybody that uses the library, check out the open issue on GitHub for progress ytdl-core

Cannot set headers after they are sent to the client - Node/Mongoose/Express

I am working on an fantasy soccer app for my friends and I, but I am getting this age old error and it doesn't seem like any of the other questions answered on here really fit my situation. In the first block of code below, the console.log is returning the correct data, so I am very certain that the res.json(populatedClub) should be working just fine. I cannot find anywhere else in my code that is triggering another res.send() or res.json() in this chain of events.
Is anybody else able to see what I am not?
My route:
fantasyClubRouter.get('/:userId',
(req, res) => {
FantasyClub
.findOne({manager: req.params.userId})
.populate({
path: 'manager',
model: 'User'
})
.exec((error, populatedClub) => {
if (error) {
return () => {throw new Error(error)};
}
console.log('populatedClub:', populatedClub);
res.json(populatedClub);
})
.catch(error => {
throw new Error(error);
});
}
);
The error stack:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:471:11)
at ServerResponse.header (/home/ubuntu/workspace/node_modules/express/lib/response.js:767:10)
at ServerResponse.send (/home/ubuntu/workspace/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/home/ubuntu/workspace/node_modules/express/lib/response.js:267:15)
at FantasyClub.findOne.populate.exec (/home/ubuntu/workspace/server/fantasyClub-routes.js:18:11)
at /home/ubuntu/workspace/node_modules/mongoose/lib/model.js:4187:16
at (anonymous function).call (/home/ubuntu/workspace/node_modules/mongoose/lib/query.js:3128:7)
at process.nextTick (/home/ubuntu/workspace/node_modules/mongoose/lib/query.js:2019:28)
at process._tickCallback (internal/process/next_tick.js:61:11)
Emitted 'error' event at:
at /home/ubuntu/workspace/node_modules/mongoose/lib/model.js:4189:13
at (anonymous function).call (/home/ubuntu/workspace/node_modules/mongoose/lib/query.js:3128:7)
at process.nextTick (/home/ubuntu/workspace/node_modules/mongoose/lib/query.js:2019:28)
at process._tickCallback (internal/process/next_tick.js:61:11)
I figured out what I had done wrong, and it was so simple that I'm almost embarrassed to admit it, but here it goes.
I updated from an older version of Mongoose and forgot to update my code accordingly. Always make sure your code matches what the docs say for the version of the library you are using.
This is the working code:
fantasyClubRouter.get('/:userId',
(req, res) => {
FantasyClub
.findOne({manager: req.params.userId})
.populate({
path: 'manager',
model: 'User'
})
.then(populatedClub => {
res.json(populatedClub);
})
.catch(error => {
throw new Error(error);
});
}
);

How to test a function that throws an error asynchronously, using tape?

I am attempting to test this module (receiver.js) for an error thrown:
var request = require('request')
module.exports = function(url){
request({
url: url,
method: 'POST'
}, function(error) {
if(error){
throw error
}
})
}
using this test (test.js):
var test = require('tape')
test('Receiver test', function(t){
var receiver = require('./receiver')
t.throws(function(){
receiver('http://localhost:9999') // dummy url
}, Error, 'Should throw error with invalid URL')
t.end()
})
but tape runs the assertion before the error is thrown, resulting in the following error message:
TAP version 13
# Receiver test
not ok 1 Should throw error with invalid URL
---
operator: throws
expected: |-
[Function: Error]
actual: |-
undefined
at: Test.<anonymous> (/path/to/tape-async-error-test/test.js:5:4)
...
/path/to/receiver.js:9
throw error
^
Error: connect ECONNREFUSED 127.0.0.1:9999
at Object.exports._errnoException (util.js:856:11)
at exports._exceptionWithHostPort (util.js:879:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1062:14)
Is there a way around this?
Generally, using tape, you have to ensure you call assert.end() after the async call has completed. Using promises (would require request-promise and returning the promise):
test('Receiver test', function(t){
// Tells tape to expec a single assertion
t.plan(1);
receiver('http://localhost:9999')
.then(() => {
t.fail('request should not succeed')
})
.catch(err => {
t.ok(err, 'Got expected error');
})
.finally({
t.end();
});
});
Using async/await:
test('Receiver test', async function(t) {
try {
await receiver('http://localhost:9999');
assert.fail('Should not get here');
} catch (err) {
assert.ok(err, 'Got expected error');
}
t.end();
});
The above example is mostly correct but here's a complete working example that compares async to synchronous side by side and also shows how to check for the error message in a manner similar to the tape examples given on tape's README.md.
test('ensure async function can be tested to throw', async function(t) {
// t.throw works synchronously
function normalThrower() {
throw(new Error('an artificial synchronous error'));
};
t.throws(function () { normalThrower() }, /artificial/, 'should be able to test that a normal function throws an artificial error');
// you have to do this for async functions, you can't just insert async into t.throws
async function asyncThrower() {
throw(new Error('an artificial asynchronous error'));
};
try {
await asyncThrower();
t.fail('async thrower did not throw');
} catch (e) {
t.match(e.message,/asynchronous/, 'asynchronous error was thrown');
};
});

Resources