google-apps-script ContactsApp.getContact(email) migration to People API - google-apps-script

How to write this simple line :
ContactsApp.getContact(email);
with the new People API ?
Thanks a lot !

Workflow:
Use people.connections.list to get the list of contacts of the requested user, specified via resourceName (people/me refers to the authenticated user).
Find the contact who has an email address like the one you are looking for.
Important notes:
Naturally, you won't get exactly the same information as in ContactsApp.getContact, since they are different API's. In this case, you'll get an instance of the Person resource.
You can choose which information should be populated on the retrieved person, using personFields (see the list of available fields here). Request multiple fields by providing a comma-separated string of fields (in the example below, emailAddresses and biographies are requested).
Code sample:
function getPerson(email) {
const resourceName = "people/me";
const optionalArgs = {
personFields: 'emailAddresses,biographies' // Add the person fields you want
}
const response = People.People.Connections.list(resourceName, optionalArgs);
const { connections } = response;
const person = connections.find(connection => {
return connection["emailAddresses"] && connection["emailAddresses"].some(emailAddress => emailAddress["value"] === email);
});
return person;
}

Related

.on("ready") define guild id with mysql

I trying to code a simple customize statistic with command trought data base "mysql" and i have problem about define guildID in "Ready" function is the anyway to define it or i need search other solutions
const Discord = require("discord.js")
const { bot } = require('../index');
const { mysql } = require('../index')
bot.on('ready', async () => {
setInterval(function() {
let sql = 'SELECT * FROM stats WHERE guildID = ?'
mysql.query(sql, [guild.id], (err, results) => {
let allchannels = results.channelID
let guildid = results.guildID
setInterval(() => {
const guild = bot.guild.get(`${guildid}`)
var userCount = guild.memberCount;
const totalUsers = bot.channels.get(`${allchannels}`)
totalUsers.setName(`total members = ${userCount}`)
}, 20000);
})
}, 15000);
})
connection.query(sql, [guild.id], (err, results) => {
ReferenceError: guild is not defined
i want to code a statistic like StartIT v4 bot but idk is it possible in ready? i dont want on any restart my bot use command like !start statistic etc,
im glad if someone know how to fix it or have any solution
You problem is that guild is not defined, the bot Object has no guild only guilds a Collection where all guilds are listed. You can either fetch the id of the specific server and filter the collection, or what i think is better for your case loop throw the hole collection and set the statistics.
As for if its possisble, you can use bot.on guildCreate and guildDelete to listen when a bot joines a new server or leaves a server. I dont know what values you want to have in your statistics, but if you want an overview above all servers your bot is running on i would use the create and delete event.
Here you can see that the client (your bot) has no attribute guild
discord.js Client

Create user data for new Firebase auth accounts in Firestore

I would like to create user data (name, email, phone number) in Firestore. This should be triggered with on create an authenticated user.
at functions-> src-> index.ts
// Sends email to user after signup
export { welcomeEmail } from './send_email';
// Saves user after signup
export { createUserDoc } from './save_user';
at functions-> src-> save_user.ts
// Firebase Config
import * as functions from "firebase-functions";
import * as firebase from "firebase-admin";
import {MD5} from "crypto-js";
export const createUserDoc = functions.auth.user().onCreate(event => {
const firebaseUser = event.data;
// Use gravatar as default if photoUrl isn't specified in user data
let fileEnding = "jpg";
let photoURL = `https://www.gravatar.com/avatar/${MD5(firebaseUser.email).toString().toLowerCase()}.jpg?s=1024&d=robohash`;
if (firebaseUser.photoURL) {
fileEnding = firebaseUser.photoURL.substr(firebaseUser.photoURL.lastIndexOf(".") + 1);
photoURL = firebaseUser.photoURL;
}
const fileName = `users/${firebaseUser.uid}/profile.${fileEnding}`;
const profilePhotoStorageOpts = {
destination: fileName,
metadata: {
contentType: `image/${fileEnding}`
}
};
const user = {
name: firebaseUser.displayName || "No Name",
email: firebaseUser.email,
photoUrl: `gs://${firebase.storage().bucket().name}/${fileName}`
};
return Promise.all([
firebase.storage().bucket().upload(photoURL, profilePhotoStorageOpts),
firebase.firestore().collection("users").doc(firebaseUser.uid).set(user)
]);
});
The goal was, for each created account I would now find a corresponding user document in Firestore and a profile image in the cloud storage.
instead I'm getting:
Property 'data' does not exist on type 'UserRecord'.ts(2339)
'Promise' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the lib compiler option to es2015 or later.ts(2585)
Help would be appreciated. Thanks
As you will see in the documentation for the onCreate method, the first parameter of the handler function is a UserRecord which does not have a data property.
So the first error you get is normal.
In your case, if you want, for example, to get the user's photoURL, you should do event.photoURL (Since event is of type UserRecord). Similarly, you will do event.uid to get the user's uid.
For the second error, you may have a look at https://stackoverflow.com/a/43122423/3371862 or How to resolve 'Build:'Promise' only refers to a type, but is being used as a value here.'

Getting auto-generated (via trigger) field from an insert in sequelize

I have a base controller for generic insert/update operations across the whole API, using only a table dictionary so we can use the same function to insert data into many tables.
The problem is there is a table that uses a correlative number generated via trigger, and when sequelize returns the inserted value, it includes the new ID but the correlative field returns empty, and I need it to show it on the interface.
I've thought of just querying the new field again to the API, or querying it on the same save function again when it includes these certain tables names, but is there a way to tell sequelize to "wait" for this new generated value and then return the data alright? Just like getting the new ID
Or maybe this needs to be fixed on the database? I don't have much experience in that field, but we are using MySQL if that helps.
function Init(models, dictionary) {
this.post = (req, res, next) => {
const { obj } = req.body;
const model = models[dictionary[obj._type]];
//Just stripping fields starting with "_"
const objClear = {};
for (const attr in obj) {
if (attr.charAt(0) !== '_') {
objClear[attr] = obj[attr];
}
}
//Saving
model.create(objClear).then(
(objSaved) => {
const data = {
obj: objSaved.get({ plain: true }),
action: 'inserted',
};
//I guess I could query the new row here again
res.json(data);
},
).catch(next);
};
}
module.exports = {
Init,
};
The response looks like:
{"obj":{"TOTAL":"0","ID":14,...,"TRANSACTION_NO":""},"action":"inserted"}
Where TRANSACTION_NO is the field generated with a trigger.
AFAIK, you have to query the new row unless you use Postgres (in which case you might try the Model.create option called "options.returning")
Two quick tests that did NOT solve the problem:
an afterCreate hook - the model still shows fields created by a trigger as null.
a model having a default value from a DB function - the model shows the function call,
not the result of the function (which does make it to the DB field).
Hope someone else has a solution!

Private Network : web3.eth.getAccounts() always send empty array

I am running a private Ethereum network. I do use https://aws.amazon.com/blockchain/templates/
The entire setup has been done. Things look setup properly on AWS. Now, I am trying to create the account and retrieve all those accounts. For that, I am using methods as below.
Web3Service.js
var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider(process.env.NETWORK_URL));
exports.getAccounts = function () {
return web3.eth.getAccounts();
};
exports.createAccount = function () {
return web3.eth.accounts.create();
};
app.js
var newAccount = await web3Service.createAccount();
console.log('newAccount ', newAccount);
var accounts = await web3Service.getAccounts();
console.log('accounts ', accounts);
I am not facing any errors at all. But in the response of the web3Service.getAccounts(); it's always empty [] array.
I have verified the Etherium setup. All nodes working perfectly.
You can find the entire codebase here : blockchain-node Sample entire codebase
web3.eth.accounts.create will provide you with the Ethereum address and the private key. In order to make new accounts available to a node, you have to store the new account information in the node's keystore.
When you call create, you will get an object like this (from the docs):
web3.eth.accounts.create();
> {
address: "0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01",
privateKey: "0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709",
signTransaction: function(tx){...},
sign: function(data){...},
encrypt: function(password){...}
}
Use the encrypt function to generate the encrypted keystore. This is what needs to be stored with the node in order to be retrievable through web3.eth.getAccounts. The location is going to vary depending on node client, OS, and if you override the keystore location when starting the node (for example, the default Geth location on Linux is ~/.ethereum/keystore).
After struggling found the solution :
Web3Service.js
/**
*
* Accounts Functions
*/
exports.createAccount = function () {
/* *
* Create Account Local Machine Only.
* It will not return in web3.eth.getAccounts(); call
*/
return web3.eth.accounts.create();
};
exports.createPersonalAccount = function (password) {
/* *
* Create Account in Node.
* web3.eth.getAccounts();
*/
return web3.eth.personal.newAccount(password);
};
app.js
var personalAccount = await web3Service.createPersonalAccount('123456789');
console.log('personalAccount ', personalAccount);
var accounts = await web3Service.getAccounts();
console.log('accounts ', accounts);
Updated source : Working Source Code
Thier is no explicitly do anything with keystore.
Start your Geth using this --rpcapi db,eth,net,web3,personal flag. It is necessary. Otherwise, you will face the error.

Finding out how many status objects are in a store

I have a store called CreativeStore and inside one of the fields is Status. The data is sent as JSON. I created a variable that is getting the Creative store. How would I find out what the status is and how many statuses their are.
In my Creative Model I have a field
}, {
type: 'int',
name: 'Status'
}, {
In my View Controller I have a method that checks if the store I created for the Creative Model exists (It does) and I assign it to a var called test.
var test = this.getCreativeStore();
getCreativeStore: function () {
var creativeStore = this.getStore('creativeStore');
if (!creativeStore) {
this.logError('creativeStore is undefined');
}
return creativeStore;
}
How do I find out how many Statuses are in the variable test?
You can use collect:
Collects unique values for a particular dataIndex from this store.
For example:
test.collect('status').length;
var statusCount = 0;
test.each(function(record) {
// Your status value in myStatus
if(record.get('Status') === myStatus)
++statusCount;
});