nodejs always returning null object of from Mandrill /senders/add-domain - javascript

I am using the mandrill api to automate some tasks for domain creation and verification using nodejs. Below is the part of my code that is having issue.
const sendingDomainCommand = mandrill_client.senders.addDomain({domain: domain.join(".")}); // adding a domain in mandrill
await sleep(10000)
const sendingDomainResult = await sendingDomainCommand;
console.log(sendingDomainCommand);
According to below mandrill/transactional api the senders/add-domain should return a json response.
https://mailchimp.com/developer/transactional/api/senders/add-sender-domain/
But in my case when I am printing the sendingDomainCommand it always shows null. I used the typeof to check the the type of this and it is object. can someone help me here please?

Related

Accessing a private Google sheet with a google cloud service account

I have a private Google Spreadsheet and I’m trying to access it programmatically using Google Visualization/Google Charts. I've created the service account, and I have tried using the google-auth-library and googleapis npm packages to create an access token that I can then use to access the spreadsheet. But, when I try to use that access token to read from the spreadsheet, the request fails with HTTP code 401 (Unauthorized). What do I need to do in order to make this work?
This is my code:
const { auth } = require('google-auth-library');
const keys = require('./jwt.keys.json');
const id = '{Spreadsheet ID}';
const sheetId = '{Sheet ID}';
const query = "{Query}";
async function getClient(){
const client = auth.fromJSON(keys);
client.scopes = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
console.log(client);
return client;
}
async function main(){
const client = await getClient();
const token = await client.getAccessToken();
console.log(token);
console.log(token.token);
const url = `https://docs.google.com/spreadsheets/d/${id}/gviz/tq?tqx=out:csv&tq=${encodeURIComponent(query)}&access_token=${token.token}#gid=${sheetId}`;
const res = await client.request({url});
console.log(res);
}
main().catch(console.error);
When I saw your script, I thought that it is required modifying the scope. I had got the same situation as you (the status code 401 using your endpoint). Unfortunately, it seems that your endpoint cannot be used using the scope of https://www.googleapis.com/auth/spreadsheets.readonly. So, for example, how about changing it as follows, and testing it again?
From:
https://www.googleapis.com/auth/spreadsheets.readonly
To:
https://www.googleapis.com/auth/spreadsheets
or
https://www.googleapis.com/auth/drive.readonly
Note:
When I tested your endpoint using the modified scope, I confirmed that no error occurred. But if you tested it and when an error occurs, please check other part, again.

Cannot fetch or get channel?

I'm trying to make something that can detect when there is a mention, and that part works, and sending it does too, somewhat. For some reason, I cannot fetch or get the channel (833856168668561409) in any way. The bot can view the channel and send messages to it, but it can't seem to find it. I'm not sure what's happening, and I can't find anything that will find an answer for this. Thank you for your time, code is displayed below.
if (message.guild.id == 793079701929066517) {
if (message.mentions.members.size) {
var channel = client.channels.fetch("833856168668561409"); //Get log channel.
var webhooks = await channel.fetchWebhooks();
var webhook = webhooks.first();
await webhook.send(`**Ping detected:**\n${Util.cleanContent(message.content, message)}`, {
username: `${message.author.username}`,
avatarURL: `${message.author.avatarURL()}`,
})
}
}
client.channels.fetch returns a Promise. You should await the result.
Without await, channel.fetchWebhooks (channel is a Promise) returns undefined causing the channel.fetchWebhooks is not a function error.
const channel = await client.channels.fetch('833856168668561409')
There's no reason to use var anymore. Use const or let.
Forgot to make the webhook for the channel I was requesting a webhook from.
Basically:
'Bot: I need a webhook for this channel'
'Discord: There is no webhook, so I will give an empty list.'
'Bot: Now I must use this to send a message'
'Bot: I cant...?!?!'
// Basically there is no webhook for it to send with.

How to use an EmbedMessage From a Different File?

I'm having trouble with an embedmessage. I provided my code below of my index.js in which I'm trying to use a function made in "globalspeakfunction.js".
Don't worry about the variables I'm sending they look extra in this but I only provided the relevant code to hopefully reduce confusion.
I'm building up my EmbedMessage in GlobalSpeakFunction.js and then sending it in the channel of the message provided in "index.js".
However my console gives back "cannot send empty message" and when I do a console.log of the EmbedMessage it returns the embed perfectly?
I tried adding a string "test" after my embedmessage in the send() function and then it returned
[object Object]test
I have no idea what's going on here. Am I not able to buildup an EmbedMessage in a different file and then send it back to my bot? Or is there something I'm just overlooking?
index.js
const Discord = require('discord.js');
const client = new Discord.Client();
const speak = require('../GlobalSpeakFunction.js');
client.on('message', message => {
if (message.content.toUpperCase().includes(`test`)){
speak("778978295059972106", message, "test", "Default");
}
}
GlobalSpeakFunction.js
const Discord = require("discord.js")
module.exports = function speak(charID, data, message, emotion){
var EmbedMessage = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('title')
.setURL('https://discord.js.org/')
.setDescription(message)
.setThumbnail('https://drive.google.com/file/d/17J90PzTLBR96wTwk_Wl3U06-or6ZjPW2/view')
.setTimestamp();
message.channel.send(EmbedMessage);
}
I'm not sure where you experienced the 'Cannot send an empty message' error, I can't reproduce it locally. However, there are a few issues here:
Firstly, you're using toUpperCase() on message.content, and later checking whether it includes (lowercase) "test". Thus, this if statement will never execute.
Secondly, the order of arguments in the speak() function is charID, data, message, emotion, but you're passing them as "778978295059972106", message, "test", "Default" (notice how data and message are swapped when calling the function).
Thirdly, the setThumbnail() function expects a direct link to an image (one that ends with a file extension, like .png or .jpg). You're providing a Google Drive link, which is additionally set to private, which makes it unreadable for anyone but you. I'd recommend uploading it to an image host and getting the direct link from there.
Also, [object Object] is just a string representation of an object. JavaScript tries to convert your MessageEmbed (which is an object) to a string (because you're trying to append 'test' to it).

js function calling an api doesn't respond with expected values

I am trying to collect all the market pairs from a crypto exchange using its API, but I'm not sure how to select the proper line in the JSON object as it does not seem to work.
the api : https://ftx.com/api/markets
my code :
requests.js
import axios from 'axios';
import parsers from './parsers';
async function ftxMarkets() {
const ftxResponse = await axios.get('https://ftx.com/api/markets');
return parsers.ftxMarkets(ftxResponse.data);
}
parsers.js
function ftxMarkets(data) {
const [ftxMarketPairs] = data;
let ftxPairs = data.map(d => d.name );
console.log(ftxPairs);
};
I'm not sure about d.name in the parsers.js file, but I tried with another exchange with the same code, changing just that part and it worked, so I guess that's where the problem comes from, although can't be sure and I don't know by what to replace it.
Thanks
I ran the api call and after looking at the response I see a result key with the list of all crypto data. So I am guessing it'll work if you call the parser with the result object like this
return parsers.ftxMarkets(ftxResponse.result);
// try parsers.ftxMarkets(ftxResponse.data.result) if the above one doesnt work
and then in the parser it should work normally
function ftxMarkets(data) {
let ftxPairs = data.map(d => d.name );
console.log(ftxPairs);
};
Update:
Since fxtResponse.data.result works. Your issue should be a CORS issue and to fix that there are two options.
CORS plugin in web browser(not recommended in production)
Proxy it through a server. By requesting the resource through a proxy - The simplest way, what you can do is, write a small node server (or if you already have a back-end associate it with your front-end you can use it) which does the request for the 3rd party API and sends back the response. And in that server response now you can allow cross-origin header.
For 2 If you already have a nodeJs server. You can use CORs Npm package and call the third party api from the server and serve the request to the front end with CORS enabled.

Using MongoDB Stitch webhook service function, how can I convert the returned "insertedId" to string?

I'm creating MongoDB Stitch http services (using the 3rd Party Services > Incoming Webhooks > Function Editor) for a simple CRUD application and I am trying to insertOne() document and then return the document id as a string.
The insertion works as expected and I await the result and store it in a variable.
const result = await collection.insertOne(payload.query)
const id = result.insertedId
The problem is trying to convert this id to string. I'm guessing it's due to my lack of understanding the MongoDB Extended JSON and BSON types, etc. I've read all parts of the documentation that I thought could provide a solution here.
I've tried the following to convert the return value to a string:
id.toString() // logs as a string, but is an object { $oid: '507c7f79bcf86cd7994f6c0e' }
id.valueOf() // logs as a string, but is an object { $oid: '507c7f79bcf86cd7994f6c0e' }
id['$oid'] // undefined
Object.values(id.insertedId) // throws error: {"message":"'values' is not a function"}
id.str // undefined
result.str // undefined
Not sure what else to try and would really appreciate if someone can point me in the right direction here to provide a solution.
Thank you in advance.
Found a solution after noticing this section of the documentation:
MONGODB STITCH > Functions > Reference > JSON & BSON
const result = await collection.insertOne(payload.query)
const id = JSON.stringify(
JSON.parse(
EJSON.stringify(result.insertedId)
).$oid
).replace(/\W/g,'');
Seems a bit hacky just for getting the id of the document into a string, but it will work for now.

Categories