Gametracker Scraper discord.js - discord

So I'm trying to script something that shows how many players are on a Server using gametracker. I found this module. I successfully can log those information in my terminal but i want to display. So when somebody types .info that this information are in the channel.
My Code:
case 'info':
const module = require ('gametracker-scraper')
async function output() {
let info = await module.get('My Link')
message.channel.send('Our Server Info:' + info)
}
output()
The text that is posted in the Channel when you write .info:
Our Server Info: [object Object]
Other scraper alternatives are welcome!

It is outputting "[object Object]" because you're concatenating a string and an object.
If you want to output the actual info, you could loop over the object (with, as an example, a for in loop), like this example:
let infoString = 'Our Server Info:\n';
for (const element in info) {
infoString += `${element}: ${info[element]}\n`;
}
message.channel.send(infoString);
Which would produce something like this:
Our Server Info:
Map: (your map)
Online: (your player count)
// etc...

info is an Object. Trying to concatenate an object with a string will return "[object Object]", unless it has a custom toString() method. You can access primitives from that object (using variable.property or variable["property"]) and it should concatenate properly. Another way, not as readable, is using JSON.stringify(). This will turn the object into a string
message.channel.send('Our Server Info:\n' + JSON.stringify(info))

Related

Adding simple array to JSON payload in Bot Framework Composer

I have a simple problem where I am not able to insert an array in json payload to call graph api to update user profile while using Bot Framework Composer.
Example:
Step1. I created a property Conversation.UpdatedSkills which holds following value
["SharePoint","Dotnet","Analytics"]
Now I want to build JSON object for MS Graph service and working sample payload looks like this.
{
"skills":["SharePoint","Dotnet","Analytics"]
}
Step2. Now to build this JSON dynamically, I need pass body as JSON Object in Send an HTTP Request activity and I have folllowing code to generate payload.
{
"skills":"${conversation.UpdatedSkills}"
}
The output from Step2 looks something like this.
{
“skills”: “[\r\n “SharePoint”,\r\n “Dotnet”,\r\n “Analytics”\r\n]”
}
DESIRED JSON WAS THIS:
{
"skills":["SharePoint","Dotnet","Analytics"]
}
My question is, How do I pass my array from step 1 such a way so that it creates json object that works in service. The object created using step 2 is not the right object that service takes.
Any idea?
I tried different string manipulations but I think this is basic and there has to be something.
Don't use the string interpolation ${ }, but use an expression (=). For your example above, it should be:
{
"skills": "=conversation.UpdatedSkills"
}

Save an array to device

I am trying to save certain data on the device that is running my app. The code for saving the data looks like this:
Future<File> writeContent() async {
final file = await _localFile;
// Write the file
return file. ...;
}
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
print(directory.path);
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/UserData.txt');
}
My problem is that I don't simply want to save a String I want to save a list (array) to the Phone. Is there a way to do so?
There has to come something where you see the ....
Thanks for your answers in advance!
You should use local database like SQLite to handle this problem, you can use this package Link
You can use pref_dessert package to achieve this..
You can create a custom class with what are all the details you want to store..
And everytime you want to store something..create an object for it same that object..
Similarly.. whenever you need the stored details...you can get the object and read details from it.
You can get to know more from an example here.

CSDL format to JSON

How can I transform the data received in CSDL format from an Oracle DB to JSON format in NODE JS
export async function getRecepFarma(req: Request, res: Response): Promise<Response> {
const conn = await connect();
const result = await conn.execute(
`SELECT * FROM IVMOV`
)
return res.json(result);
}
enter image description here
The driver is not returning CSDL format unless that's just a coincidence. The driver returns a JavaScript object with properties, such as metadata (with info about the columns) and rows (the actual data).
The easiest way to convert a JavaScript object to JSON is with JSON.stringify(object). However, you're calling res.json, which will do this for you. If you just want to send the data as JSON, you can call return res.json(result.rows);.
The resulting JSON will be an array of arrays by default. However, if you want an array of objects, then you can the outFormat property, either at the global level (oracledb) or as an execute option.
Here's your code modified to do that:
export async function getRecepFarma(req: Request, res: Response): Promise<Response> {
const conn = await connect();
const result = await conn.execute(
`SELECT * FROM IVMOV`,
[], // no binds
{
outFormat: oralcedb.OUT_FORMAT_OBJECT
}
)
return res.json(result);
}
If you want to stream a large result set, rather than use the buffered rows property, then that does take just a little more code. Let me know if that's something you need.
Finally, you might find this series on creating a REST API with Node.js and Oracle Database useful:
https://jsao.io/2018/03/creating-a-rest-api-with-node-js-and-oracle-database/

JSON stored into an array not callable by specific index

I am trying to develop an app for my fantasy baseball league to use for our draft (we some kind of quirky stuff all the major sites don't account for) - I want to pull some player data to use for the app by using MLB's API. I have been able to get the response from MLB, but can't do anything with the data after I get it back. I am trying to store the JSON into an array, and if I console.log the array as a whole, it will give me the entire chunk of data, but if I try to call the specific index value of the 1st item, it comes back as undefined.
let lastName = 'judge';
let getData = new XMLHttpRequest;
let jsonData = [];
function getPlayer () {
getData.open('GET', `http://lookup-service-
prod.mlb.com/json/named.search_player_all.bam?
sport_code='mlb'&active_sw='Y'&name_part='${lastName}%25'`, true)
getData.onload = function() {
if (this.status === 200) {
jsonData.push(JSON.parse(this.responseText));
}
}
getData.send();
console.log(jsonData);
}
When I change the above console.log to console.log(jsonData[0]) it comes back as undefined. If I go to the console and copy the property path, it displays as [""0""] - Either there has to be a better way to use the JSON data or storing it into an array is doing something abnormal that I haven't encountered before.
Thanks!
The jsonData array will be empty after calling getPlayer function because XHR loads data asynchronously.
You need to access the data in onload handler like this (also changed URL to HTTPS to avoid protocol mismatch errors in console):
let lastName = 'judge';
let getData = new XMLHttpRequest;
let jsonData = [];
function getPlayer () {
getData.open('GET', `https://lookup-service-
prod.mlb.com/json/named.search_player_all.bam?
sport_code='mlb'&active_sw='Y'&name_part='${lastName}%25'`, true)
getData.onload = function() {
if (this.status === 200) {
jsonData.push(JSON.parse(this.responseText));
// Now that we have the data...
console.log(jsonData[0]);
}
}
getData.send();
}
First answer from How to force a program to wait until an HTTP request is finished in JavaScript? question:
There is a 3rd parameter to XmlHttpRequest's open(), which aims to
indicate that you want the request to by asynchronous (and so handle
the response through an onreadystatechange handler).
So if you want it to be synchronous (i.e. wait for the answer), just
specify false for this 3rd argument.
So, you need to change last parameter in open function as below:
getData.open('GET', `http://lookup-service-
prod.mlb.com/json/named.search_player_all.bam?
sport_code='mlb'&active_sw='Y'&name_part='${lastName}%25'`, false)
But from other side, you should allow this method to act asynchronously and print response directly in onload function.

Cloud Endpoints not accepting JSON array

I want to build my endpoint, which accept JSON array of below format:
[
{
"test":"Math",
"result":"Pass"
},
{
"test":"Science",
"result":"FirstClass"
}
]
It will be a POST call with the above JSON to my endpoint.
I tried it with servlet too but did not get the required result, and also tried to with list and inserting in a new class and posting to that class. Thanks in advance.
Is that an accurate representation of the JSON object which is being sent over? Because one does not simply send a a POST request with a JSON object of their param object to a cloud endpoint. See here for a thorough guide to Endpoint API interaction from a javascript perspective - notice how the client library exposes an object "gapi" through which calls are made. If you're sending this JSON from an iOS or Android app, there are similar client libraries which can be generated for you by a cloud endpoints build tool.
After much frustration, I resorted to reading the docs more carefully. In that quest, I found an important note in the doc:
https://cloud.google.com/endpoints/docs/frameworks/java/parameter-and-return-types
"Any type except a parameter or injected type is considered an entity type. ... Entity types cannot be annotated with #Named"
With all examples showing named parameters, I was stumped as the docs don't explain further, but then found a solution. It ends up that if you do not have named parameters, everything is just passed in as a LinkedHashMap. Usually, you can do any work you need to with just that data structure, but if you HAVE to have it in JSON, you can convert it. Here are some examples:
#ApiMethod(name = "endpointIterfaceName.createItems", httpMethod = "post", path = "test/items")
public WhateverReturnType createItems(LinkedHashMap<String, Object> itemsMap) {
// Do Stuff with map values
return whateverReturnValue;
}
With this, you need to be sure that you post your data with the Content-Type of json (i.e. Content-Type:application/json; charset=UTF-8). So, for example, when testing, with a jquery ajax call you would need to set dataType to "json" or with Postman, you would select "Raw" then JSON (application/json).
If you really want to convert this to a JSON object in Java because for whatever reason you can not use a hash map, you can do the following in your method:
// Use gson library to convert the map to a string
Gson gson = new Gson();
String mapAsJsonString = gson.toJson(itemsMap);
// create a JSON object from the new string representation
JSONObject obj = new JSONObject(mapAsJsonString);
As a side note, if this is passed as Content-Type:text then the whole body will be in the map as the first key of the map. You could do some inadvisable things here and just get that key and avoid converting the map to a string and then to a json object, but, like I said, that is inadvisable. :)

Resources