Cannot read properties of null (reading ‘data’) - node.js

This is what the error looks like
I tried to run a command on my discord bot (I have a language system for it and that’s from where i think the error came from), then my bot crashed then sent that error message in console
I thought it would work like it normally does but the bot just continues to crash everytime i run that command.
The part where the error came from according to console:
const guild_settings = require('../database/models/guild-settings.js');
const findLang = await guild_settings.findOne({ guild: interaction.guild.id });
const lang = require(`../langs/${findLang.data.language || "en"}.js`);

Related

Discord bot not answering messages

i've been trying a new project which is to code a discord bot with discord.js in node. The source code for interactions in the discord.js documentation works but, when i followed online tutorials, the bot does not reply to my messages in the discord server. please do correct me!, the bot seems to go online as my console does work. but the rest is history
const Discord = require('discord.js');
const env = require("./botconfig.json"); //json file containing tokens & IDs
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
let prefix = env.prefix;
client.on("ready", ()=>{
console.log(`${client.user.tag} is online in ${client.guilds.cache.size} servers`)
console.log(`the prefix is ${prefix}`);
})
client.on("messageCreate", Message => {
if (Message === "ping") {
Message.channel.send('Pong.');
}
});
client.login(env.token);
On the client.on("messageCreate", the second argument is a function that takes a Message object, NOT the message as a string! (check the class here https://discord.js.org/#/docs/discord.js/stable/class/Message). You may wanna try the following:
// Access the `content` property of the message
if (Message.content === "ping") {
Message.channel.send('Pong.');
}
Also seems the tutorials you're seeing are kind of deprecated. Discord.js has a lot of new stuff to make those easier and more organized. I would suggest you to try building your bot while following the official docs which are pretty good :) https://discord.js.org/#/docs/discord.js/stable/general/welcome
The messageCreate event does not pass a string, it passes a Discord.js Message class instance, as DJS is object-oriented. Just access the .content property such as message.content.

'FIRESTORE INTERNAL ASSERTION FAILED: Unexpected state' when unit testing with Jest

I'ḿ setting up a jest test suite for a Node.js and Express REST API i'm building, i'm using #firebase/testing module to initialize a testing app, however when i try to perform any sort of operation to the database this error comes out:
FIRESTORE (7.17.2) INTERNAL ASSERTION FAILED: Unexpected state
at fail (/home/cardonapablo/Documentos/Proyectos/Optica (Ilicit)../../../../../node_modules/#firebase/testing/node_modules/#firebase/firestore/src/util/assert.ts:39:9)
at hardAssert (/home/cardonapablo/Documentos/Proyectos/Optica (Ilicit)../../../../../node_modules/#firebase/testing/node_modules/#firebase/firestore/src/util/assert.ts:53:5)
at fromBytes (/home/cardonapablo/Documentos/Proyectos/Optica (Ilicit)../../../../../node_modules/#firebase/testing/node_modules/#firebase/firestore/src/remote/serializer.ts:270:5)
at fromWatchChange (/home/cardonapablo/Documentos/Proyectos/Optica (Ilicit)../../../../../node_modules/#firebase/testing/node_modules/#firebase/firestore/src/remote/serializer.ts:486:25)
at PersistentListenStream.onMessage (/home/cardonapablo/Documentos/Proyectos/Optica (Ilicit)../../../../../node_modules/#firebase/testing/node_modules/#firebase/firestore/src/remote/persistent_stream.ts:576:25)
at /home/cardonapablo/Documentos/Proyectos/Optica (Ilicit)../../../../../node_modules/#firebase/testing/node_modules/#firebase/firestore/src/remote/persistent_stream.ts:456:21
at /home/cardonapablo/Documentos/Proyectos/Optica (Ilicit)../../../../../node_modules/#firebase/testing/node_modules/#firebase/firestore/src/remote/persistent_stream.ts:509:18
at /home/cardonapablo/Documentos/Proyectos/Optica (Ilicit)../../../../../node_modules/#firebase/testing/node_modules/#firebase/firestore/src/util/async_queue.ts:369:14
I also tried connecting to my regular firestore database with the credentials i have been using to develop the endpoints and same error pops out even tho it's the app i use daily
Weird thing is, data is being written to the database, but error still stops testing
Here is firebase setup:
(src/db/functions.js)
let app = initializeTestApp({
projectId: "illicit"
})
db = app.firestore()
module.exports = { db }
Function throwing the error
(tests/fixtures/db.js)
const { db } = require('../../src/db/functions')
const bcrypt = require('bcrypt');
const createAdmin = async function() {
// Encrypt password
let encPass = await bcrypt.hash("admin", 8)
let admin = {
name: "Admin Test User",
email: "admin#test.com",
password: encPass,
tokens: []
}
// Add to db
let docRef = await db.collection('admins').add(admin) // <- This line throws the error
return;
}
module.exports = {
createAdmin
}
And finally testing file
(tests/glasses.test.js)
const supertest = require('supertest');
const app = require('../src/app')
const functions = require('./fixtures/db')
let adminToken;
let glassesId;
//Executes before any test, here is where error occurs, before any tests
beforeAll( async () => {
await functions.createAdmin()
return
})
test('Should log in an admin', async () => {
let response = await supertest(app)
.post('/admins/login')
.send({
email: 'admin#test.com',
password: 'admin'
})
.expect(200);
expect(response.body.token).toEqual(expect.any(String))
adminToken = response.token;
});
This only happens only when i try to test, regular app works just fine
Things i've tried:
Firestore rules are read and write true, so it's not a rules error
Mocked Firestore with firebase-mock and Jest seems to work fine, however this is not a
solution, since i need to test data inside the database
Hope you can help me :)
You should change Jest's test environment from the default jsdom to node using jest --env=node or by setting the testEnvironment option to node in your Jest config.
Solved the problem myself, i was using the Firebase web client, I switched to the Admin SDK made specifically for servers, i guess it was some sort of auth problem, because the admin sdk automatically authenticates you in the db
This is a open issue on GitHub. I'm pasting my comment from that issue here to hopefully help some other people:
I experienced the same error message on 9.6.6 with NextJS. I believe
this error message could be presented due to a range of errors - as I
see 100+ Stackoverflow questions with this error message.
After lots of debugging I realized I accidently used SQL
capitalization:
.orderBy('time', 'ASC') = "INTERNAL ASSERTION FAILED: Unexpected state" .orderBy('time', 'asc') = No Errors!
This was a pain to debug, and my mistake was so small. Maybe better
error reporting is needed in cases like this? When you get then Google
this error message it easily leads you down a path of debugging things
completely irrelevant to the real error.
So pretty much - a tiny syntax error can cause the error message and lead you down a road of debugging the wrong things. To solve this you have to find exactly where it is happening and narrow in your debuging.
execute this command with what is indicated a little above yarn test jest --env=node
after this the error disappears

Slack bot ALWAYS gives missing_scope error

I'm new to Slack bots so I went through their documentation and followed some tutorials on the internet but nothing seems to help. I'm trying to add a simple bot to a workspace I've just created, all I want is to make the bot post a message once it starts. Here is my code:
const SlackBot = require('slackbots');
const botToken = 'xoxp-XXXXXXXXXXXXX-XXXXXXXXXXXX-XXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXX'
const bots = async () => {
const bot = await new SlackBot({
token: botToken,
name: 'orderbot'
});
console.log('adding event listener...');
await bot.on('start', () => {
console.log('posting message...');
bot.postMessage('general', 'Feeling hungry?');
});
};
bots();
And in the OAuth & Permissions page, I've added ALL permissions to the token's scopes. Running the bot, here is my output:
adding event listener...
/home/mohammed/OrderBot/node_modules/vow/lib/vow.js:105
throw e;
^
Error: missing_scope
at /home/mohammed/OrderBot/node_modules/slackbots/index.js:46:33
So apparently, the error is coming from the .on listener which is quite confusing and I can't understand why this is happening. What exactly am I missing?
It seems like the module slackbots which I was using is not working properly (at least for me). I solved this issue by using #slack/web-api instead.

TypeError: Cannot read property 'avatarURL' of null | Trying to export the help command

I've been cleaning my index.js file, and decided I wanted to have the help command somewhere a little more practical. Only problem: in the footer I have the bots avatar, but it comes up with TypeError: Cannot read property 'avatarURL' of null
//code in help.js
const Discord = require('discord.js');
const client = new Discord.Client();
var version = process.env.VERSION;
module.exports = {
name: 'help',
execute(message, args){
const Discord = require('discord.js');
const helpcommands = new Discord.RichEmbed()
.setTitle('Akasuki Command List')
.addField('Info Commands', 'userinfo, version, ping, invite, avatar')
.addField('Moderation Commands', 'kick, ban, clear')
.addField('Fun Commands', 'samwise, say')
.setColor(0xFF8AFF)
.setFooter(`Akasuki ${version}`, client.user.avatarURL)
message.channel.send(helpcommands);
}
}
//code in index.js
if (command === 'help') {
client.commands.get('help').execute(message, args);
}
I'm also wondering if there is a way to export multiple commands at once, or if all have to be done one-by-one?
If anyone can help me with this error I would be very grateful <3 Thank you for checking this out.
I've been cleaning my index.js file, and decided I wanted to have the help command somewhere a little more practical. Only problem: in the footer I have the bots avatar, but it comes up with TypeError: Cannot read property 'avatarURL' of null
The error TypeError: Cannot read property 'avatarURL' of null is clear. It's saying that you're attempting to access a property of an object that is null.
To debug this error, you can try logging the object in question: console.log(client.user); If null comes up, this may be due to not being logged in with your Discord.js client.
Based on your code, it seems that you've not logged in your Discord.js' Client instance. I'd recommend for you to checkout the login method, which is what you'd want to use to login to Discord. You want to login to Discord first before accessing your Client's user's properties.
Additionally, to view or create your bot applications, visit your Discord applications.
I'm also wondering if there is a way to export multiple commands at once, or if all have to be done one-by-one?
A simple way to export multiply commands is by using an array. You could define and export multiple commands like so:
module.exports = [
{
// command 1 ...
},
{
// command 2 ...
]
];
Then you could use a loop to access them.

Why telegram does not send message to webhook?

Using node-telegram-bot-api on my VPS, I'm trying to get message from a telegram channel.
Here is the code:
var TelegramBot = require ( 'node-telegram-bot-api');
var token = '1793xxxxxxxxxxxxxxxxxxxxx';
var __dirname ='/etc/nginx/ssl'
var options = {
webHook: {
port: 443,
key: __dirname+'/key.pem',
cert: __dirname+'/crt.pem'
}
};
var bot = new TelegramBot(token, options);
bot.setWebHook('1.3.4.5:443/bot1793xxxxxxxxxxxxxxxxxxxxx', __dirname+'/crt.pem');
bot.on ( 'message', function (msg) {
var chatId = msg.chat.id;
console.log (msg);
bot.sendMessage (chatId, "Hello!", {caption: "I'm a bot!"});
});
When I get this link the browser:
https://telegram.me/MyExampleBot?start=abcd
I expect the bot to receive a message from the channel containing abcd when user clicks on start button, but I receive nothing in the bot's console.
The problem occured when I added bot.setWebHook to the code. Without that, I could receive a message whenever user typed something in the channel.
My code is following the the example here so I really have no idea what is wrong with it. Really appreciate your hints.
I had the same problem. Telegram didn't send anything to my bot...
Because of incorrect certificate. Generate your cert according to this:
https://core.telegram.org/bots/self-signed
just replace "YOURDOMAIN.EXAMPLE" with valid for you value. I used just my IP, after that it works.
Additionaly you can see debug info from node-telegram-bot-api to understand what happening:
npm install debug
DEBUG=node-telegram-bot-api node bot.js
It will produce debug output for you.
Hope it helps.

Resources