Discord.js snekfetch body undefined problem - javascript

const Discord = require("discord.js")
const snekfetch = require("snekfetch")
const client = new Discord.Client({disableEveryone: false});
//const CSGO = require("csgo-api"); // Import the npm package.
//const jb = new CSGO.Server('185.198.75.5', '27015') // Set the IP with port.
var prefix2 = "!"
client.on('ready', async ()=> {
snekfetch.get("http://query.li/api/csgo/185.198.75.5/27015").then(r => console.log(r.body.game.players.name));
//jb.getOnlinePlayers().then(data => console.log(data)) // Get & log the data
});
Hello friends, I'm trying to print the players section on http://query.li/api/csgo/185.198.75.5/27015 to message.channel.send but it gives undefined can you help me?
I'm using Google Translate sorry my English so bad :/

You are trying to get the body of the result. But it is null. Your result contains these children: game, whois, status, banner_url, and cached.
And also, your players are an array. So you should select an index to console.log().
Try this:
snekfetch.get("http://query.li/api/csgo/185.198.75.5/27015").then(r => console.log(r.game.players[0].name));
You can use this web site to beautify your response JSON.
EDIT:
If you want to print the names of all players then you can use a foreach() loop for players. Like this:
snekfetch.get("http://query.li/api/csgo/185.198.75.5/27015").then(r => {
r.game.players.forEach(player => {
console.log(player.name)
});
}
);

Related

Firebase function error: Cannot convert undefined or null to object at Function.keys (<anonymous>)

Description of the problem:
My App aim is to store family spending in Firebase Realtime Database. I want that, when a new spending is stored, a notification is sent to all other devices.
I try to send a notification to a single device and it works fine, but when I try to get all the tokens in an array, I have an error:
TypeError: Cannot convert undefined or null to object at Function.keys ().
code of index.js :
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.androidPushNotification = functions.database
.ref("{nodo}/spese/{spesaPush}")
.onCreate(async (snapshot, context) => {
const original = snapshot.val();
const getDeviceTokensPromise = admin.database()
.ref(`/utenti/{tutti}/token`).once('value');
let tokensSnapshot;
let tokens;
tokensSnapshot = await getDeviceTokensPromise;
// This is the line generating the errors.
// If I get only a specific token and
// use tokens = tokensSnapshot.val(); anything works fine
tokens = Object.keys(tokensSnapshot.val());
const result = original.chi + " ha speso " +
original.costo + " € per acquistare " +
original.desc;
console.log(result);
const payload = {
notification: {
title: 'New spending inserted!',
body: result,
}
};
const response = await admin.messaging().sendToDevice(tokens, payload);
return result;
});
It seems that values are not reached yet, but I thought that the keyword await lets system to wait until all data are available. From the log I noticed that the value I need is null and I don't understand why.
If I use this line of code:
const getDeviceTokensPromise = admin.database()
.ref(`/utenti/SpecificUser/token`).once('value');
....
//then
tokens = tokensSnapshot.val();
The notification is sent to the device that has the token under the name of "SpecificUser"
EDIT:
I provide a pic of my db. I notice that none of the field is null, so I don't know why I see this error
Thank you to anyone that helps me
i had same error and it is solve by database...
when i saw my database values unfortunately i stored undefined value so my whole result got error like you...
see your whole values and fields that store values properly.

Extracting value from an object

I'm working on a discord bot, using discord.js.
I've been working on this command for too long without finding a solution, so I come here to ask for help.
Here is my problem, maybe it's really simple to solve to you, and that would be great :D
I want to create a command that sends a random gif, based on a keyword.
I'm using a node module called giphy-random.
(async () => {
const API_KEY = "hidden";
const gif = await giphyRandom(API_KEY, {
tag: "kawaii"
});
console.log(gif)
}
I would like to be able to get only the value 'url' of the const which is defined by the function (i'm maybe wrong in my words, I'm a beginner) in order to send it in a channel.
You simply want gif.data.url In fact if you change your console.log like this:
console.log(gif.data.url);
You'll see the url printed to the console.
According to the docs, the link is returned in data.url property of the resulting object. So your code should look like:
(async () => {
const API_KEY = "hidden";
const gif = await giphyRandom(API_KEY, {
tag: "kawaii"
});
console.log(gif.data.url)
}
You can simply access field like this:
const API_KEY = "hidden";
const gif = await giphyRandom(API_KEY, {
tag: "kawaii"
});
const {url} = gif.data; // equal to const url = gif.data.url
console.log(gif);
}

Can I treat items found through a Promise.all as a firebase collection?

I am stuck in what I thought was a very simple use case: I have a list of client ids in an array. All I want to do is fetch all those clients and "watch" them (using the .onSnapshot).
To fetch the client objects, it is nice and simple, I simply go through the array and get each client by their id. The code looks something like this:
const accessibleClients = ['client1', 'client2', 'client3']
const clients = await Promise.all(
accessibleClients.map(async clientId => {
return db
.collection('clients')
.doc(clientId)
.get()
})
)
If I just needed the list of clients, it would be fine, but I need to perform the .onSnapshot on it to see changes of the clients I am displaying. Is this possible to do? How can I get around this issue?
I am working with AngularFire so it is a bit different. But i also had the problem that i need to listen to unrelated documents which can not be queried.
I solved this with an object which contains all the snapshot listeners. This allows you to unsubscribe from individual client snapshots or from all snapshot if you do not need it anymore.
const accessibleClients = ['client1', 'client2', 'client3'];
const clientSnapshotObject = {};
const clientDataArray = [];
accessibleClients.forEach(clientId => {
clientSnapshotArray[clientId] = {
db.collection('clients').doc(clientId).onSnapshot(doc => {
const client = clientDataArray.find(client => doc.id === client.clientId);
if (client) {
const index = clientDataArray.findIndex(client => doc.id === client.clientId);
clientDataArray.splice(index, 1 , doc.data())
} else {
clientDataArray.push(doc.data());
}
})
};
})
With the clientIds of the accessibleClients array, i create an object of DocumentSnapshots with the clientId as property key.
The snapshot callback function pushes the specific client data into the clientDataArray. If a snapshot changes the callback function replaces the old data with the new data.
I do not know your exact data model but i hope this code helps with your problem.

How Find Emojis By Name In Discord.js

So I have been utterly frustrated these past few days because I have not been able to find a single resource online which properly documents how to find emojis when writing a discord bot in javascript. I have been referring to this guide whose documentation about emojis seems to be either wrong, or outdated:
https://anidiots.guide/coding-guides/using-emojis
What I need is simple; to just be able to reference an emoji using the .find() function and store it in a variable. Here is my current code:
const Discord = require("discord.js");
const config = require("./config.json");
const fs = require("fs");
const client = new Discord.Client();
const guild = new Discord.Guild();
const bean = client.emojis.find("name", "bean");
client.on("message", (message) => {
if (bean) {
if (!message.content.startsWith("#")){
if (message.channel.name == "bean" || message.channel.id == "478206289961418756") {
if (message.content.startsWith("<:bean:" + bean.id + ">")) {
message.react(bean.id);
}
}
}
}
else {
console.error("Error: Unable to find bean emoji");
}
});
p.s. the whole bean thing is just a test
But every time I run this code it just returns this error and dies:
(node:3084) DeprecationWarning: Collection#find: pass a function instead
Is there anything I missed? I am so stumped...
I never used discord.js so I may be completely wrong
from the warning I'd say you need to do something like
client.emojis.find(emoji => emoji.name === "bean")
Plus after looking at the Discord.js Doc it seems to be the way to go. BUT the docs never say anything about client.emojis.find("name", "bean") being wrong
I've made changes to your code.
I hope it'll help you!
const Discord = require("discord.js");
const client = new Discord.Client();
client.on('ready', () => {
console.log('ready');
});
client.on('message', message => {
var bean = message.guild.emojis.find(emoji => emoji.name == 'bean');
// By guild id
if(message.guild.id == 'your guild id') {
if(bean) {
if(message.content.startsWith("<:bean:" + bean.id + ">")) {
message.react(bean.id);
}
}
}
});
Please check out the switching to v12 discord.js guide
v12 introduces the concept of managers, you will no longer be able to directly use collection methods such as Collection#get on data structures like Client#users. You will now have to directly ask for cache on a manager before trying to use collection methods. Any method that is called directly on a manager will call the API, such as GuildMemberManager#fetch and MessageManager#delete.
In this specific situation, you need to add the cache object to your expression:
var bean = message.guild.emojis.cache?.find(emoji => emoji.name == 'bean');
In case anyone like me finds this while looking for an answer, in v12 you will have to add cache in, making it look like this:
var bean = message.guild.emojis.cache.find(emoji => emoji.name == 'bean');
rather than:
var bean = message.guild.emojis.find(emoji => emoji.name == 'bean');

JS SDK, Thrift error code 12 when getting SharedNotebooksList

It's the first time that I work with evernote,
Like the example given in the JS SDK, I create my client with the token that I get from the OAuth and I get all the notebooks of my current user so it was good for me.
But I'm facing a problem that I can't understand, when I use any method of my shared store it throw an Thrift exception with error code 12 and giving the shard id in the message.
I know that 12 error code is that the shard is temporary unavailable..
But I know that it's another thing because it's not temporary...
I have a full access api key, it work with the note store, did I miss something ?
// This is the example in the JS SDK
var linkedNotebook = noteStore.listLinkedNotebooks()
.then(function(linkedNotebooks) {
// just pick the first LinkedNotebook for this example
return client.getSharedNoteStore(linkedNotebooks[0]);
}).then(function(sharedNoteStore) {
// /!\ There is the problem, throw Thrift exception !
return sharedNoteStore.listNotebooks().then(function(notebooks) {
return sharedNoteStore.listTagsByNotebook(notebooks[0].guid);
}).then(function(tags) {
// tags here is a list of Tag objects
});
});
this seems to be an error with the SDK. I created a PR (https://github.com/evernote/evernote-sdk-js/pull/90).
You can work around this by using authenticateToSharedNotebook yourself.
const client = new Evernote.Client({ token, sandbox });
const noteStore = client.getNoteStore();
const notebooks = await noteStore
.listLinkedNotebooks()
.catch(err => console.error(err));
const notebook = notebooks.find(x => x.guid === guid);
const { authenticationToken } = await client
.getNoteStore(notebook.noteStoreUrl)
.authenticateToSharedNotebook(notebook.sharedNotebookGlobalId);
const client2 = new Evernote.Client({
token: authenticationToken,
sandbox
});
const noteStore2 = client2.getNoteStore();
const [notebook2] = await noteStore2.listNotebooks();
noteStore2.listTagsByNotebook(notebook2.guid)

Categories

Resources