Transferring API information from console log to bot - javascript

I am working with the Geolocation API on my discord.js bot. I have the api working properly and i receive the info i wanted into the console log but i have been unable to integrate the data i receive from the console to the actual bot embed. Any help is appreciated
var IPGeolocationAPI = require('ip-geolocation-api-javascript-sdk');
var ipgeolocationApi = new IPGeolocationAPI("8c402b955bfb4b82a7353abc99c9dca9", false);
const Discord = require('discord.js');
module.exports = {
name: 'ip',
execute(message, args) {
var inp = args[0]
// Function to handle response from IP Geolocation API
function handleResponse(json) {
console.log(json);
message.author.send(json);
/*
//create embed
const embed = new Discord.MessageEmbed()
.setTitle(`**${inp}**`)
json.forEach((data, value) => {
embed.addField(data, value)
}) //end for each
message.author.send({
embed
});
*/
} //end handle
var GeolocationParams = require('ip-geolocation-api-javascript-sdk/GeolocationParams.js');
// Get complete geolocation in English for IP address input by argument
var geolocationParams = new GeolocationParams();
geolocationParams.setIPAddress(inp);
geolocationParams.setLang('en');
ipgeolocationApi.getGeolocation(handleResponse, geolocationParams);
}
}
Errors:
for normal send: DiscordAPIError: Cannot send an empty message
for embed: json.forEach is not a function
console output:
{
ip: '123.456.789(ip removed)',
continent_code: 'NA',
continent_name: 'North America',
country_code2: 'US',
country_code3: 'USA',
country_name: 'United States',
country_capital: 'Washington',
state_prov: 'Georgia',
district: '',
city: 'Marietta',
zipcode: '30060',
latitude: '33.92530',
longitude: '-84.48170',
is_eu: false,
calling_code: '+1',
country_tld: '.us',
languages: 'en-US,es-US,haw,fr',
country_flag: 'https://ipgeolocation.io/static/flags/us_64.png',
geoname_id: '4207783',
isp: 'Total Server Solutions L.L.C.',
connection_type: '',
organization: 'Total Server Solutions L.L.C.',
currency: { code: 'USD', name: 'US Dollar', symbol: '$' },
time_zone: {
name: 'America/New_York',
offset: -5,
current_time: '2020-05-07 12:21:15.314-0400',
current_time_unix: 1588868475.314,
is_dst: true,
dst_savings: 1
}
}

the json variable in your code is an object. Rather than forEach (which is meant for arrays) try
for (var key in json){
//loop through all , pick what you want
}

Related

SmartContracts - how to run function with "Erc.json" (javascript) (update)

Hello guys,
I have a question
I try to smart contract functions from erc.json standarts with JavaScript. To example: I need a random number function with metamask user address(account number) referance for backend
To basicly:
Example JSON values:
{
inputs: [{ internalType: 'address', name: 'UserKey', type: 'address' }],
name: 'RandomNumber',
outputs: [{ internalType: 'uint256', name: '', type: 'uint256' }],
stateMutability: 'view',
type: 'function',
},
Example smart contract function:
const daiToken = new web3.eth.Contract(
ContractABI, // ABI
address, // Sender address
chainId
)
daiToken.methods
.RandomNumber(address)
.call(ContractABI)
.then(function (result) {
console.log(result)
})
.catch(function (err) {
console.log(err, 'err')
})
And here is the console prints:
i hope i explained :)
and happy weekends..
(updated new error)
Are you tried to change <React.StrictMode><App /><React.StrictMode> to <App /> in your index.js file?

Upload Intent function Dialogflow V2

I am trying to develop an API to upload the intent to Dialogflow V2. I have tried below snippet, which it is not working however if trying to communicate with Dialogflow it does work (detect intent)and does get a reply from the Dialogflow for queries.
PERMISSION
I AM & ADMIN > SERVICE ACCOUNTS > DIALOGFLOW ADMIN
ERROR
Error: 7 PERMISSION_DENIED: IAM permission 'dialogflow.entityTypes.create' on 'projects/dexter-47332/agent' denied.
BLOGS/ REFERENCES
Dialogflow easy way for authorization
https://github.com/dialogflow/dialogflow-nodejs-client-v2/blob/master/samples/resource.js#L26
https://www.npmjs.com/package/dialogflow
https://developers.google.com/apis-explorer/
https://cloud.google.com/docs/authentication/production
//------- keys.json (test 1)
{
"type": "service_account",
"project_id": "mybot",
"private_key_id": "123456asd",
"private_key": "YOURKEY",
"client_email": "yourID#mybot.iam.gserviceaccount.com",
"client_id": "098091234",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/yourID%40mybot.iam.gserviceaccount.com"
}
//--------------------- ** (test 2) ** ---------
let privateKey = 'key';
let clientEmail = "email";
let config = {
credentials: {
private_key: privateKey,
client_email: clientEmail
}
}
function createEntityTypes(projectId) {
// [START dialogflow_create_entity]
// Imports the Dialogflow library
const dialogflow = require('dialogflow');
// ******** Instantiates clients (Test 1)********
const entityTypesClient = new dialogflow.EntityTypesClient({
'keyFilename': './keys.json'
});
const intentsClient = new dialogflow.IntentsClient({
'keyFilename': './keys.json'
});
// ******** Instantiates clients (Test 2)********
const entityTypesClient = new dialogflow.EntityTypesClient(config);
const intentsClient = new dialogflow.IntentsClient(config);
// The path to the agent the created entity type belongs to.
const agentPath = intentsClient.projectAgentPath(projectId);
const promises = [];
// Create an entity type named "size", with possible values of small, medium
// and large and some synonyms.
const sizeRequest = {
parent: agentPath,
entityType: {
displayName: 'test',
kind: 'KIND_MAP',
autoExpansionMode: 'AUTO_EXPANSION_MODE_UNSPECIFIED',
entities: [{
value: 'small',
synonyms: ['small', 'petit']
},
{
value: 'medium',
synonyms: ['medium']
},
{
value: 'large',
synonyms: ['large', 'big']
},
],
},
};
promises.push(
entityTypesClient
.createEntityType(sizeRequest)
.then(responses => {
console.log('Created size entity type:');
logEntityType(responses[0]);
})
.catch(err => {
console.error('Failed to create size entity type ----->:', err);
})
);
}
createEntityTypes(projectId);
You can use JWT(JSON Web Tokens) for authenticating with service accounts like in this example
const serviceAccount = { }; // JSON key contents {"type": "service_account",...
const serviceAccountAuth = new google.auth.JWT({
email: serviceAccount.client_email,
key: serviceAccount.private_key,
scopes: 'https://www.googleapis.com/auth/calendar'
});
For more OAuth2.0 scopes for Google APIs you can see the full list here.
I encountered the same error. I corrected it by deleting the current service account and creating a new one and selected the "owner" option for the role.
The associated service-account has to have the role "Dialogflow API Admin" to be able to create intents and entities.
I think you must provide a name parameter there in the sizeRequest and make it equal to an empty string.
Take a look at the code snippet.
let request = {
parent: `projects/${PROJECID}/agent`,
entityType: {
name: '',
autoExpansionMode: 'AUTO_EXPANSION_MODE_DEFAULT',
displayName: 'size_type',
enableFuzzyExtraction: false,
entities: [
{
value: 'Big',
synonyms: ['big', 'large', 'huge']
},
{
value: 'Medium',
synonyms: ['medium', 'not big']
}
],
kind: 'KIND_MAP'
},
languageCode: 'en'
};
Please let me know if this helps.

How to send mandrill emails to array of emails?

I'm building an app in Node and I'm using mandrill to send emails every time there is a new user to a predefined array of emails. I have an array of emails:
And I have this function where
newUserEmail(user_name, email) {
emailArray = [example1#ex.com, example2#ex.com, example3#ex.com]
const message = {
html: '<p>Name: *|NAME|* <br> Email: *|EMAIL|*</p>',
text: 'Name: *|NAME|*, Email: *|EMAIL|*',
subject: 'New person arrived',
from_email: 'newperson#example.com',
from_name: 'New',
to: [{
email: emailArray,
type: 'to'
}],
merge: true,
merge_vars: [{
rcpt: emailArray,
vars: [{
name: 'NAME',
content: user_name
}, {
email: 'EMAIL',
content: email
}]
}]
};
mandrill_client.messages.send({ message }, function(result) {
console.log(result);
}, function(e) {
console.log(`A mandrill error occurred: ${e.name} - ${e.message}`);
});
}
I get this on my console:
[ { email: 'Array',
status: 'invalid',
_id: '...',
reject_reason: null } ]
If I set only one email, it gets sent without problems.
Do I need to make a loop and run this function as many times as there are emails in the array? I hoped mandrill would recognise emails in the array :(
From what I gathered after a look at the documentation it looks like each object in the "to" array is an individual email address.
I would not run the function for each email address. Just map over the email array.
For example:
const formattedArray = emailArray.map(email => ({ email, type: 'to' }));
// if you're not a fan of arrow functions
const formattedArray = emailArray.map(function(email) {
return { email, type: 'to' };
});
Then in the mandrill message you can just set "to" equal to the formattedArray
to: formattedArray

Merge an Item Fulfillment with an advanced template and email it Netsuite 2.0

So without the merge function below, this code sends an email on save, but I cannot for the life of me get email merge to work in Netsuite 2.0, so how do I merge an advanced pdf template with an item fulfillment and email it?
/**
*#NApiVersion 2.x
*#NScriptType UserEventScript
*/
define(['N/email','N/render', 'N/record', 'N/file'],
function(email, record, file,render) {
function afterSubmit(context) {
function templatemerge() {
var myMergeResult = render.mergeEmail({
templateId: 121,
entity: {
type: 'employee',
id: 18040
},
recipient: {
type: 'employee',
id: 18040
},
supportCaseId: 'NULL',
transactionId: 1176527,
customRecord: 'NULL'
});
}
templatemerge();
function sendEmailWithAttachement() {
var newId = context.newRecord;
var emailbody = 'attachment';
var senderId = 18040;
var recipientEmail = 'email#email.com';
email.send({
author: senderId,
recipients: recipientEmail,
subject: 'Item Fulfillments',
body: emailbody
});
}
sendEmailWithAttachement();
}
return {
afterSubmit: afterSubmit
};
});
Try rearranging the first function signature to function(email, render, record, file)
They are probably in the wrong order.

eBay Trading API addFixedPriceItem Call Error

I'm trying to make a call to addFixedPriceItem in NodeJS. I'm using the NodeJS eBay API. My code is the following:
var ebay = require('ebay-api');
ebay.ebayApiPostXmlRequest({
serviceName: 'Trading',
opType: 'AddFixedPriceItem',
devName: myDevId,
cert: myCertId,
appName: myAppId,
sandbox: true,
title: title,
params: {
'authToken': myClientAuthToken,
version: EBAY_API_VERSION,
Item: {
Country: 'EBAY-US',
Currency: 'USD',
Description: description,
ListingType: 'FixedPriceItem',
PictureDetails: picturesArray,
Quantity: '5',
StartPrice: price
},
}
}, function (error, results) {
if (error) {
console.dir(error);
process.exit(1);
}
console.dir(results);
});
Ultimately, I cannot seem to get it to call. It's not a verification issue or anything, console is stating that No Item.Country exists, and No Item.Currency exists, although I have specifically placed these in my parameters. Any clue why this would occur?
If not, how could I make a call to this in nodeJS without this API? I appreciate any help! :)
Your country code is wrong. It should be 'US' or one of the other CountryCodeType's.

Categories