How to use a timeout in Discord.js - javascript

I am working on a Discord bot that needs to update someone's nickname, and then reset it back to normal after 2 hours.
I have the code all set up and working when the timeout is set to a few seconds, but when I push the timeout to 2 hours I get a failed request to the discord server. I'm thinking this is because that channel doesn't stay connected that long -- not sure.
Here is the error:
UnhandledPromiseRejectionWarning: FetchError: request to https://discord.com/api/v7/guilds/297251675616444416/members/711322838556213319 failed, reason: getaddrinfo ENOTFOUND discord.com
at RequestHandler.execute (C:\Users\japhy\projects\enhanced\node_modules\discord.js\src\rest\RequestHandler.js:93:15)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async RequestHandler.push (C:\Users\japhy\projects\enhanced\node_modules\discord.js\src\rest\RequestHandler.js:39:14)
at async GuildMember.edit (C:\Users\japhy\projects\enhanced\node_modules\discord.js\src\structures\GuildMember.js:312:5)
Here is the code itself:
function nicknameTimeout(memberID, memberGuildID) {
guildVar = client.guilds.cache.get(memberGuildID);
member = guildVar.members.cache.get(memberID);
setTimeout(() => {
guildVar = client.guilds.cache.get(memberGuildID);
member = guildVar.members.cache.get(memberID);
nickname = member.nickname;
if (typeof nickname === "object") {
nickname = member.user.username;
}
if (nickname.endsWith("UPDATED***")) {
nickname = nickname.slice(0, -11);
member.setNickname(nickname, "");
}
}, 7200000);
}
Any ideas on how to forcibly reconnect to the client after the timeout, or any other workaround would be much appreciated.

Related

Twilio Error - ConnectionError (31005): Error sent from gateway in HANGUP

Trying to connect two users to the same conference call, but getting this error first:
error: ConnectionError: ConnectionError (53000): Raised whenever a signaling connection error occurs that is not covered by a more specific error code.
and then getting this error:
Received an error from the gateway: ConnectionError: ConnectionError (31005): Error sent from gateway in HANGUP
at ConnectionError.TwilioError [as constructor]
In my TwiML error logs this is what I see:
TwiML response body too large
For full context, users are first matched together, this happens in the 'waiting room' component:
function createTwilioConference(username, matchedUser){
const pairedUsers ={}
pairedUsers['roomName'] = sortUsersAlphabetically([username,matchedUser]).join('')
pairedUsers['participantLabel'] = sortUsersAlphabetically([username,matchedUser])
pairedUsers['currUser'] = username
pairedUsers['matchedUser'] = matchedUser
axios.post(`${profileURL}voice_chat/rooms`,pairedUsers)
.then(res =>{
console.log('twilio call created', res.data)
})
}
This function is wrapped in a useEffect that has an empty dependency array. Both users who have been matched together receive an XML object creating a twilio conference call
<?xml version="1.0" encoding="UTF-8"?><Response><Dial><Conference participantLabel="['emmanuelS21', 'testingUser']" startConferenceOnEnter="true">emmanuelS21testingUser</Conference></Dial></Response>
The conference room name is the same for both users (sort their names alphabetically and concatenating them to create the room name).
Both users are then redirected to the pair programming session where the call is initiated:
useEffect(() => {
console.log('!!!*** how many times is twilio being called ***!!!')
const params = {
roomName: roomName, participantLabel: user.username
};
if (!call) {
const callPromise = device.connect({ params });
callPromise.then((call) => {
console.log(' ***what is call', call)
setCall(call);
});
}
if (!participants.current.includes(user.username)) {
participants.current.push(user.username);
}
}, []);
I'm not sure how big an issue this is, but I noticed that my useEffect is being called four times

Discord.js: AbortError: The user aborted a request

I have been working on my ticket system and its transcript logging process, and one day this error started showing up and transcripts started to fail sending. This didn't use to be a thing before.
The full error is:
[Error Handling System] Multiple Resolves
reject Promise {
<rejected> AbortError: The user aborted a request.
at abort (/PC/Bot/bot/node_modules/discord.js/node_modules/node-fetch/lib/index.js:1448:16)
at EventTarget.abortAndFinalize (/PC/Bot/bot/node_modules/discord.js/node_modules/node-fetch/lib/index.js:1463:4)
at EventTarget.[nodejs.internal.kHybridDispatch] (node:internal/event_target:460:20)
at EventTarget.dispatchEvent (node:internal/event_target:405:26)
at abortSignal (node:internal/abort_controller:97:10)
at AbortController.abort (node:internal/abort_controller:122:5)
at Timeout.<anonymous> (/PC/Bot/bot/node_modules/discord.js/src/rest/APIRequest.js:72:49)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7) {
type: 'aborted'
}
}
My code is:
setTimeout(() => {
interaction.channel.delete({ reason: `[Ticket System] Ticket Closed` }).then(async ch => {
const mdb = require('./../models/tickets')
mdb.findOne({ Channel: ch.id }, async (err, data) => {
if (err) throw err;
if (data) {
const openedBy = interaction.guild.members.cache.get(ch.topic.split(" ").splice(1).toString())
fs.writeFileSync(`../${ch.name} - ${ch.id}.txt`, data.Content.join("\n\n"))
let embed = new Discord.MessageEmbed()
.setTitle("Ticket Closed")
.addField("<:ticket1:872962350473433089> Ticket Name", `${ch.name} (${ch.id})`)
.addField(`<:person:890913045457563718> Opened By`, `${openedBy}`)
.addField("<:admin:872930262516908113> Closed By", `${interaction.user} (${interaction.user.id})`)
.addField(`<:open:914148680959934514> Open Time`, `<t:${moment(ch.createdTimestamp).format("X")}>`)
.setTimestamp()
.setFooter({ text: `ID: ${uuidv4()}` })
const atta = new Discord.MessageAttachment(fs.createReadStream(`../${ch.name}-${ch.id}.txt`))
const logChannel = client.channels.cache.get(transcripts_channel);
logChannel.send({ embeds: [embed], files: [atta] })
mdb.findOneAndDelete({ Channel: ch.id })
}
})
})
}, 10000)
I have tried removing MongoDB parts, tried decreasing the timeout and many more... None of those helped.
Thanks in advance!
That's Discord API error, Discord receives a request from discord.js but takes too long to process so it's aborted. For more information this issue and this discord.js pull request.
Tag from official discord.js server:
AbortError: The user aborted a request.
A request took longer than the specified restRequestTimeout (15 seconds default), and was aborted to not lock up the request handler.
• This can be caused by an internal server error on Discord's side, or just a slow connection.
• In case of a slow connection, the restRequestTimeout option in ClientOptions can be increased to prevent future AbortErrors.
Check that your internet is stable, and that Discord isn't having any issues (status page). Can you visit https://discord.com/app in your browser? Do you have a proxy or VPN enabled?
If it's still happening, you can try the second option, which is to change the restRequestTimeout in your Client constructor.
const client = new Client({
restRequestTimeout: 60000 // change the timeout to 1 minute
// other options like your intents...
});

Discord.JS strange issue when attempting to update VoiceChannel

So I'm getting the error 'Type: value "voice" is not int.' when attempting to update a voice channel name but only on Ubuntu.
message.guild.channels.cache.get('863162796262031410').setName('testing')
Please note, this is happening on Ubuntu but works fine on windows
If anyone can provide some insight it would be greatly appreciated.
Uncaught Promise Error: DiscordAPIError: Invalid Form Body
type: Value "voice" is not int.
at RequestHandler.execute (/home/NodeJS/node_modules/discord.js/src/rest/RequestHandler.js:152:13)
at processTicksAndRejections (node:internal/process/task_queues:93:5)
at async RequestHandler.push (/home/NodeJS/node_modules/discord.js/src/rest/RequestHandler.js:37:14)
at async VoiceChannel.edit (/home/NodeJS/node_modules/discord.js/src/structures/GuildChannel.js:357:21) {
method: 'patch',
path: '/channels/863162796262031410',
code: 50035,
httpStatus: 400
}
A way you can do this and it will work is:
Option One
const voiceChannel = message.guild.channels.resolve('channel_id')
voiceChannel.setName('new_channel_name');
Option 2
const voiceChannel = message.guild.channels.resolve('channel_id');
voiceChannel.edit({
name: 'testing',
})

UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT] - setInterval & Axios.post error handling

I've tried to handle this warning via Googling. However, as I couldn't solve this warning, I'm asking this question.
The following warning is what I'm facing now:
(node:39452) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:485:11)
at ServerResponse.header
...
at ServerResponse.send
...
at ServerResponse.json
...
at ServerResponse.send
...
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async Timeout.priceAlarm [as _onTimeout]
(node:39452) 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: 3)
When "priceAlarm" is called, it is okay. However, when "intervalPriceAlarm = setInterval(priceAlarm, 3000, res, chatId);" is done, it shows the warning at axios.post ... catch(error) part.
Does anyone have good idea to handle it?
Thank you.
function priceAlarm(res, chatId) {
axios
.get(url)
.then((response) => {
currentBtcBitfinexUsd = getPrice(
response.data.tickers,
"BTC",
"USD",
"bitfinex"
);
axios
.post( `${telegramBotUrl}${apiToken}/sendMessage`, {
chat_id: chatId,
text:
"\nBitfinex- BTC(USD):" +
currentBtcBitfinexUsd,
})
.then((response) => {
res.status(200).send(response);
})
.catch((error) => {
res.send(error); //****this part shows an error!*****
});
})
.catch((error) => {
console.log(error);
});
}
function intervalAlarm(res,chatId){
if (alarmFlag == 1 && intervalPriceAlarm == null) {
intervalPriceAlarm = setInterval(priceAlarm, 3000, res, chatId);
console.log(intervalPriceAlarm); //need to remove it
}else{
console.log("doing nothing");
}
}
app.post("/", (req,res) =>{
const chatId = req.body.message.chat.id;
const sentMessage = req.body.message.text;
if (sentMessage.match(/price/gi)) {
priceAlarm(res, chatId); //No problem at all
} else if (sentMessage.match(/start/gi)) {
alarmFlag=1;
res.status(200).send({});
} else if(sentMessage.match(/stop/gi)){
alarmFlag=0;
res.status(200).send({});
} else {
res.status(200).send({});
}
intervalAlarm(res,chatId); // here setInterval part.
});
This is a server-side error due to the fact that the server can't re-write HTTP headers of a response it already sent to the client. Consequently, you can't res.send() twice the same res, but you do it in your code
// here the first time
priceAlarm(res, chatId); //No problem at all
// here the second time
intervalAlarm(res,chatId); // here setInterval part.
You'll have to rewrite your code, because that's a base behavior of HTTP that the server can't send data to the client after sending a response already. So that's not an express problem, that's an HTTP limitation. If you want your server to be able to "push" data to your client, you'll have to use websockets instead.

Waiting for multiple async calls using async.each

I need to wait for few async calls to complete before resuming execution. I tried the following code using async.
asana.getUsers(null, function(error, resp){
async.each(resp.data, function(user, cb) {
console.log("Get info for user : ", user.id);
asana.getUser(user.id, null, function(error, userResp){
console.log("user response: ", userResp.data.id);
userEmailList.push({
id : userResp.data.id,
name: userResp.data.name,
email : userResp.data.email
});
cb(null);
});
//cb(null); Should the call be here??
}, function(err){
console.log("getUsers is done now");
});
});
The log that i get is:
Get info for user : xxxxxxxxxxxx
Get info for user : yyyyyyyyyyyy
Get info for user : zzzzzzzzzzzz
Get info for user : aaaaaaaaaaaa
user response: yyyyyyyyyyyy
/Code/javaScript/NodeWorkspace/asana-api/mail.js:23
console.log("user response: ", userResp.data.id);
^
TypeError: Cannot read property 'data' of null
at /Code/javaScript/NodeWorkspace/asana-api/mail.js:23:43
at Request._callback (/Code/javaScript/NodeWorkspace/asana-api/lib/asana.js:77:13)
at Request.self.callback (/Code/javaScript/NodeWorkspace/asana-api/node_modules/request/main.js:119:22)
at Request. (/Code/javaScript/NodeWorkspace/asana-api/node_modules/request/main.js:525:16)
at Request.EventEmitter.emit (events.js:95:17)
at IncomingMessage. (/Code/javaScript/NodeWorkspace/asana-api/node_modules/request/main.js:484:14)
at IncomingMessage.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:883:14
at process._tickCallback (node.js:415:13)
I understand the first logs, but why is the console.log("user response: ", userResp.data.id); line getting called with userResp as null.
I hope its not some silly mistake. Thanks in advance.
P.S: Basically i need to get Asana users and then get info of each user and store in a var userEmailList.
The issue was that userEmailList was undefined.

Categories

Resources