This error has appeared after I added a .catch statement to Promises after sending messages to guilds.
Quick Explanation: My bot is trying to retrieve data from a guild it no longer belongs to.
Here's my code:
Filename: roleDelete.js
'use strict';
const Discord = require('discord.js');
const Error = require('debug')('Event:roleDelete:Error');
/**
* #param {object} client - The client instance
* #param {object} role - The deleted role object
*/
module.exports.run = (client, role) => {
let embed = new Discord.RichEmbed();
const guildID = role.guild.id;
const guildName = role.guild.name;
const guildIcon = role.guild.iconURL;
const modLog = client.guilds.get(guildID).channels.find('name', client.config.modLog);
const tempIcon = 'https://images-ext-2.discordapp.net/external/ouGhEoGzz1ZyBG9mMFrYClvdv9V0FZ0jGSEHa_kLLYk/https/discordapp.com/assets/0e291f67c9274a1abdddeb3fd919cbaa.png';
if (!modLog) return;
embed = new Discord.RichEmbed()
.setAuthor(guildName, guildIcon ? guildIcon : tempIcon)
.addField('Role Name', role.name, true)
.addField('Role Color', role.hexColor, true)
.addField('Role Hoisted', role.hoist, true)
.setFooter('Role Deleted At')
.setTimestamp()
.setColor(client.config.colors.red);
return modLog.send(embed).catch(err => Error(err));
};
Additional Info:
bufferutil: 3.0.3
chalk: 2.3.0
clear: 0.0.1
debug: 3.1.0
discord.js: 11.3.0
dotenv: 4.0.0
firebase-admin: 5.8.1
moment: 2.20.1
opusscript: 0.0.6
Expected Result:
Discord.JS ignores and no error is thrown.
Current Result:
2018-01-23T12:34:05.029Z Event:guildDelete Left Guild: 395928739201941506, removed into database.
2018-01-23T12:34:05.212Z Event:roleDelete:Error DiscordAPIError: Missing Access
at item.request.gen.end (/app/node_modules/discord.js/src/client/rest/RequestHandlers/Sequential.js:71:65)
at then (/app/node_modules/snekfetch/src/index.js:218:21)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
2018-01-23T12:34:05.255Z Event:guildMemberRemove:Error DiscordAPIError: Missing Access
at item.request.gen.end (/app/node_modules/discord.js/src/client/rest/RequestHandlers/Sequential.js:71:65)
at then (/app/node_modules/snekfetch/src/index.js:218:21)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7
Is there any way to ignore the fact that it has left and completely ignore it?
This sounds like an error with multiple events running asynchronously. If that is the case, a simple check if the client is still in the guild should fix the issue. An example of one of the few ways to do this can be found below.
const guild = bot.guilds.get(myguildid); // Should return null if the guild is not found
if (!guild) // The guild does not exist.
The property used can be found here in the documentation. Of course, there are other ways to do this, but this also sounds like a bug with the library and caching. If this causes any further bugs and the above does not fix the issue, try reporting the issue in more detail on the Discord (to find and identify the bug). From there, they'll direct you to report it to their GitHub if it does turn out to be a bug. Happy coding!
Related
I wanted to know how I could add a role to a specific user within DMs.
With the new Discord.js update, it's tricky, and can't find a way around it.
Thanks.
My attempt:
var guild = client.guilds.cache.get("[GUILDID]")
var buyerRole = guild.roles.cache.get("[ROLE ID]")
console.log(message.author.id) // Works
var guildMember = guild.members.fetch(message.author.id)
console.log(guildMember.displayName) // Returns 'undefined'
guildMember.setNickname(guildMember.username+" | Buyer") // Error
console.log(buyerRole.color) // Works
Output: guildMember.setNickname is not a function
That's because you fetch the member but never await it. .fetch returns a promise so the right way to get guildMember is like this:
const guildMember = await guild.members.fetch(message.author.id)
I'm trying to create a command where if you say a slash command with a use parameter then it will give that user the role. I keep receiving this error even though I know that the member exists.
TypeError: Cannot read properties of undefined (reading 'roles')
My code:
const { commandName, options } = interaction;
const user = options.getUser('user');
if (commandName == 'givebetatester'){
console.log(user);
const role = interaction.guild.roles.cache.get('917609388154425374');
interaction.reply('Success');
user.member.roles.add(role);
}
I've double-checked that I have the role and the user exist and I have no idea what's wrong at this point. Any help would be appreciated.
You can only go from a GuildMember to User and not the other way around. You're trying to go from a User to a GuildMember by using user.member
Either change your slash command options to accept a Member instead of a User
Or ensure you have the Guild Member's Intent enabled and fetch the GuildMember object with the User id:
// Async/Await
const member = await interaction.guild.members.fetch(user.id);
Fixed! I switched from user to mentionable which might break if someone tries to type something other than a role but it does the trick.
Code:
const { commandName, options } = interaction;
const user = options.getMentionable('user');
if (commandName == 'givebetatester'){
const role = interaction.guild.roles.cache.get('917609388154425374');
user.roles.add(role);
interaction.reply('<a:ncheckmark:917609071195074600>');
}
I am trying to send a message through discord.js and I am getting the following error:
(node:10328) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of undefined
Here is my code:
// Init
const Discord = require("discord.js");
const bot = new Discord.Client();
const channel = bot.users.cache.get('4257');
// Vars
// Code
bot.on("ready", () => {
console.log("The Bot is ready!");
channel.send("Test");
});
// Login
bot.login(" "); // I will hide this.
What is wrong? Is it the id on the channel variable? I just put in the id of my bot since I didn't know what to put in it.
At first I gave it all the permissions under "Text Permissions", but I also tried giving him admin privs. It still didn't work. What am I doing wrong?
The problem is this line:
const channel = bot.users.cache.get('4257');
Here's what's wrong with it:
const channel = bot.users.cache // this returns a collection of users, you want channels.
.get('4257'); // this is a user discriminator, you want a channel ID
Here's how to fix it:
const id = <ID of channel you want to send the message to>
const channel = bot.channels.cache.get(id)
// ...
channel.send('Test')
Here's an example:
const channel = bot.channels.cache.get('699220239698886679')
channel.send('This is the #general channel in my personal Discord')
How to get a Channel ID
ChannelManager Docs
const channel is empty here. You need to make sure value should be assigned in it.
channel.send("Test");
If its not mendatory that value will come then use try-catch.
try {
channel.send("Test");
} catch(e) {
console.log(e)
}
Please support with vote or answered if it helps, thanks.
I have an android app and want people (authenticated users) to send push notification each other from a message box. I'm using node.js with firebase cloud functions and I got this error on logs:
TypeError: Cannot read property 'userId' of undefined
at exports.sendNotification.functions.database.ref.onWrite.event (/user_code/index.js:10:33)
...
The message is successfully written to real-time database but the notification is not delivered to the receiver(user).
I read so many docs and same/similar problems so I'm aware that there are so many topics related to this but I couldn't solve the problem. I use index.js as the source code but changed some parts like onWrite section according to the documents I read.
The error indicates this line in the following code:
const receiverId = context.params.userId;
Something about params go wrong. Here is the small part of the code(with my changings):
let functions = require('firebase-functions');
let admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.database.ref('/messages/{userId}/{messageId}').onWrite((change,context) => {
//get the userId of the person receiving the notification because we need to get their token
const receiverId = context.params.userId;
console.log("receiverId: ", receiverId);
//get the user id of the person who sent the message
const senderId = change.child('user_id').val();
console.log("senderId: ", senderId);
//get the message
const message = change.child('message').val();
console.log("message: ", message);
//get the message id. We'll be sending this in the payload
const messageId = context.params.messageId;
console.log("messageId: ", messageId);
...
Get lastest version of node
And see this: https://firebase.google.com/docs/functions/database-events#handle_event_data for usage of onWrite(event...) and onCreate(.....)
That'll help you
im trying to implement my bot a function. Function that if the channel write any message it will be forwarded to the groups where the bot already is.
Trying to use scope method that worked like a charm on welcome message when new user joined the group.
//index.js
const Telegram = require('telegram-node-bot'),
tg = new Telegram.Telegram('MYAPI', {
workers: 1
});
const ForwardController = require('./controllers/forward')
tg.router.when(new Telegram.TextCommand('/info', 'infoCommand'), new InfoController())
.otherwise(new ForwardController());
//forward.js
const Telegram = require('telegram-node-bot');
class ForwardController extends Telegram.TelegramBaseController {
handle(scope) {
if ('channel' == scope.message.chat._type) {
scope.api.forwardMessage(scope.message._chat._id, _forwardFromChat._text);
}
}
}
module.exports = ForwardController;
I tried many combinations but the message is never forwarded... The bot is already administrator on the channel and is also putted in the groups. (Have also private message opened with bot so i think it should forward also there)
Take a look at the API reference for the library, the documentation page appears to be down so Github is your friend.
The forwardMessage call you are making has incorrect arguments and is accessing the private class variables. It is also returning a promise so you should await the promise or chain a .then to it. You can use the class methods on the Scope instance itself.
It should be more like:
// using async/await - note the containing function must be async for this approach
const result = await forwardMessage(<id of chat here>, scope.message().id());
// or to chain a .then
forwardMessage(<id of chat here>, scope.message().id())
.then(result => /* do something with result */)
.catch(err => /* handle the error */);
This will use the Scopes instance method and handle sending the id of the current chat for you, all you need is the id of the chat you want to send the message to and then replace the <id of chat here> with that id.