How to read a JSON object that currently stringifies as "Object Promise" - node.js

My Discord bot continuously sends [Object Promised] when I use
const DabiImages = require("dabi-images");
const DabiClient = new DabiImages.Client();
DabiClient.sfw.real.random().then(json => {
console.log(json);
}).catch(error => {
console.log(error);
});
I was wondering how I can fix this, as I'm not sure.

I think the comments on this already answer the question but you could..
const DabiImages = require('dabi-images')
const DabiClient = new DabiImages.Client()
const main = async () => {
const dabiJson = await DabiClient.sfw.real.random()
console.log(dabiJson)
}
main()
Also worth mentioning, that the sfw doesn't exist

Related

Uncaught (in promise) TypeError: "nameMyFunction" is not a function in useEffect React

I'm sorry for my English. I'm using a translator. I have the following problem. I'm trying to use a function from another component, but it gives me the following error.
I will leave the code extract:enter image description here
I used useEffect to display the data for an id depending if that id has records:
export async function getOrderByTableApi(idTable, status= "", ordering= ""){
try {
const tableFilter = `table=${idTable}`;
const statusFilter = `status=${status}`;
const closeFilter = "close=false";
const url = `${BASE_API}/api/orders/?${tableFilter}&${statusFilter}&${closeFilter}&${ordering}`;
const response = await fetch(url);
const result = await response.json();
return result;
} catch (error) {
throw error;
}
}
the function comes from another component as follows:
import { getOrderByTableApi } from "../api/orders";
export function useOrder(){
const [setLoading] = useState(true);
const [setError] = useState(false);
const [setOrders] = useState(null);
const getOrderByTable = async (idTable, status, ordering) => {
try {
setLoading(true);
const response = await getOrderByTableApi(idTable, status, ordering);
setLoading(false);
setOrders(response);
} catch (error) {
setLoading(false);
setError(error);
}
};
return{
getOrderByTable,
};
}
and when using it, the console tells me that getOrderByTable is not a function
import { useTables } from "../../hooks";
export function OrdersHistory() {
const [idTable, setIdTable] = useState(null);
const { getOrdersByTable } = useOrder();
const { getTableByNumber } = useTables();
useEffect(() => {
(async () => {
const table = await getTableByNumber(tableNumber);
const idTableTemp = table[0].id;
setIdTable(idTableTemp);
**getOrdersByTable(idTableTemp, "", "ordering=-status,-created_at");**
})();
}, []);
return (
<p>Help please</p>
);
}
adjunto imagen
There is a typing mistake in your code. You're exporting the function as getOrderByTable from your custom hook useOrder but you're importing it as getOrdersByTable instead of getOrderByTable in your OrdersHistory component.
If you want to rename your function, you can do it as below
const { getOrderByTable as getOrdersByTable } = useOrder();
I appreciate the review, due to fatigue I did not notice that the name of the function did not match a letter and that is why it gave me an error, I will take the recommendation to copy and paste the names of the functions in the future, I consider this question closed. Thank you so much.

onValue triggering multiple times

I'm using Node.js v18.12.1 and Discord.js v14. for developing the Discord bot. I need to read some data from Firebase. I'm confused because I'm used to how Java with Hibernate fetches data differently. Here, I need to use onValue() listener.
My onValue() acts strange. Instead of just reading the data from Firebase, it skips entirely, then it triggers multiple times, each time skipping the body block of its code, and then it actually does the code after.
I've read somewhere on this forum that this can happen because there are more onValue() listeners that are subscribed and they are all fired up. Someone mentioned I need to use the off() function somewhere "before" the onValue(). This confuses me because I'm using this listener in many locations. I need it in each command file, in execute(interaction) functions. You know, when you need to execute slash commands in Discord. I have it something like this:
async execute(interaction) {
const infographicRef = ref(db, '/infographics/arena/' + interaction.options.getString("arena-team"));
var imageUrl = null;
var postUrl = null;
onValue(infographicRef, (snapshot) => {
imageUrl = snapshot.child("image-url").val();
interaction.reply(imageUrl);
})
},
And I planned for each command, in each command.js file to have onValue(). I'm not sure exactly what to do.
Also, I tried to work around this with once() method, I see it in Firebase documentation, but I got the error: ref.once() is not a function.
It seems that after first triggering of onValue method when the body is not executed, my code in interactionCreate.js is triggered as well, it points for a command to be executed again:
const { Events } = require('discord.js');
module.exports = {
name: Events.InteractionCreate,
async execute(interaction) {
if (!interaction.isChatInputCommand()) return;
const command = interaction.client.commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(`Error executing ${interaction.commandName}`);
console.error(error);
}
},
};
my bot.js (which is in my case an index file)
const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Events, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const filePath = path.join(eventsPath, file);
const event = require(filePath);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
client.commands.set(command.data.name, command);
}
client.once(Events.ClientReady, () => {
console.log('Ready!');
});
client.on(Events.InteractionCreate, async interaction => {
if (!interaction.isChatInputCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
client.login(token);
The onValue function registers a realtime listener, that continues to monitor the value on the database.
If you want to read a value once, that'd be done with get() function in v9 (which is the equivalent of the once method in earlier SDK versions). Have a look at the code sample in the documentation on reading data once.

channel.send is not a function? (Discord.JS)

Normally I wouldn't ask for help, but I've tried almost everything and I'm stumped. Here is my code,
const Discord = require('discord.js');
const client = new Discord.Client();
const timedResponses = ["Test"]
const token = '';
client.on('ready', () =>{
console.log('the doctor is ready');
client.user.setActivity('medical documentaries', { type: 'WATCHING'}).catch(console.error);
const channel = client.channels.fetch('691070971251130520')
setInterval(() => {
const response = timedResponses [Math.floor(Math.random()*timedResponses .length)];
channel.send(response).then().catch(console.error);
}, 5000);
});
client.login(token);
The code seems to be working fine on my other bots, but for some reason it refuses to work on this one.
Edit: I tried to add console.log(channel) but I got an error. "Channel" is not defined.
ChannelManager#fetch returns a Promise Check the return type in the documentation
You could fix your issue by using async / await
client.once("ready", async () => {
// Fetch the channel
const channel = await client.channels.fetch("691070971251130520")
// Note that it's possible the channel couldn't be found
if (!channel) {
return console.log("could not find channel")
}
channel.send("Your message")
})
I am assuming you copied the ID manually from a text based channel, if this ID is dynamic you should check if the channel is a text channel
const { TextChannel } = require("discord.js")
if (channel instanceof TextChannel) {
// Safe to send in here
}

Cannot read property 'From' of undefined at /user_code/index.js

I am working on sending notification between two applications. I have tried to do this through node.js but now I am stuck at this error for 1 month but found no solution to it.please help me out in it. this is very important for me.I will be very thankful for any kind of help.
"use-strict"
const functions = require('firebase-functions');
const admin= require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification= functions.firestore.document('Users/{user_id}/Notifications/{notification_id}').onWrite((change, context) => {
const user_id= context.params.user_id;
const notification_id= context.params.notification_id;
return admin.firestore().collection("ServiceProviders").doc(user_id).collection("Notifications").doc("notification_id").get().then(querySnapshot => {
const from_user_id= querySnapshot.data().From;
const from_message= querySnapshot.data().message;
const from_data= admin.firestore.collection("Users").doc(from_user_id).get();
const to_data= admin.firestore.collection("Users").doc(user_id).get();
return Promise.all([from_data, to_data]).then(result => {
const from_name=result[0].data().name;
const to_name=result[1].data().name;
const token_id= result[1].data().token_id;
const payload= {
notifications:{
title: "Notification from : " + from_name,
body: from_message,
icon:"default"
}
};
return admin.messaging().sendToDevice(token_id, payload).then(result => {
return console.log("Notification Sent");
});
});
});
here is the monstrous error`
Your firestore query isn't returning anything; probably because either the document/collection doesn't exist.
Right off the bat, it stands out that your "notification_id" is queried as string, rather than the const you set earlier. It's kind of a gamble, but changing line 10 to this may help:
return admin.firestore().collection("ServiceProviders").doc(user_id).collection("Notifications").doc(notification_id).get().then(querySnapshot => {

Sqlite Discord.js: Cannot read property 'run' of null

So I am trying to make a SQLite database for my Discord.js bot, but I keep getting this error (Cannot read property of 'run' of null) when I try to use SQLite. Non of my friends seem to have this problem, so I thought to come here. Sorry if this is like a noobish question.. I'm still a little new to this
Here is my code:
const Discord = require("discord.js");
const client = new Discord.Client();
const bot = new Discord.Client();
const sql = require("sqlite")
const fs = require("fs");
const staff = ["97122523086340096", "450241616331145217", "283438590875402240", "288755621787074560"]
const config = require("./config.json");
client.on("ready", async () => {
console.log(`${client.user.username} is ready to help servers!`)
console.log ("Warning: I am being locally hosted. During high usage times, the bot may crash.")
console.log(`I am available in 1 shard! I am in ${client.guilds.size} guilds and serving ${bot.users.size}`)
client.user.setActivity("For sat!help", {type: "WATCHING"}, {status:"dnd"});
client.user.setPresence( {status:"idle"} )
sql.run("CREATE TABLE IF NOT EXISTS guild (guildId TEXT, language INTEGER, links INTEGER)")
});
fs.readdir("./events/", (err, files) => {
if (err) return console.error(err);
files.forEach(file => {
let eventFunction = require(`./events/${file}`);
let eventName = file.split(".")[0];
client.on(eventName, (...args) => eventFunction.run(client, ...args));
});
});
client.on("message", message => {
if (message.author.bot) return;
if(message.content.indexOf(config.prefix) !== 0) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
try {
let commandFile = require(`./commands/${command}.js`);
commandFile.run(bot, message, args);
} catch (err) {
return
}
});
client.on("guildCreate", guild => {
let guildp = guild.owner
guildp.send("Thanks for adding me to your server! \n To save you some time I would suggest you run the command 'sat!setup' to create the nessecary roles and channels for the bot. \n Please note that the channel is not made with perms.\n ***[PLEASE NOTE!] - I am still in beta so any issues with any part of the bot please tell us with sat!bug! \n Thanks!")
})
client.login(config.token);
You need to open connection with the database and then run the SQL query.
const sql = require("sqlite")
const db = sql.open('./database.sqlite', { Promise });
db.run("CREATE TABLE IF NOT EXISTS guild (guildId TEXT, language INTEGER, links INTEGER)");

Resources