create channel with flex api from twilio serverless function - function

I am trying t ocreate a chat channel through nodejs twilio flex api, I can create it from other server or node project, but if I deploy it in twilio's serverless function it causes error ,seems it doesn't recognize flex api.
It gives error can not read property create of undefined.
Does twilio function has not included flex api yet?
code is as below:
const twilio = require('twilio')(context.ACCOUNT_SID, context.AUTH_TOKEN);
threadID=from
fromName=from
fromAddress=from
const channelArgs = {
flexFlowSid: 'FO.....',
identity: from,
chatUniqueName: from,
chatUserFriendlyName: from,
chatFriendlyName: from,
target: from,
preEngagementData: JSON.stringify({
threadID,
fromName,
fromAddress,
subject
})
};
twilio.flexApi.channel.create(channelArgs).then(channel => {
console.log('got chat channel', channel.sid);

Verify the Twilio Helper Library in use by your Twilio Functions environment is up to date.
You can find the most up to date Twilio Node Helper Library for twilio is below.
twilio-node changelog

Related

blockchain tutorial Error: The send transactions "from" field must be defined

I am following a blockchain tutorial from dappuniversity.
When I create the task in the line
await App.todoList.createTask(content)
from line
https://github.com/dappuniversity/eth-todo-list/blob/e3ed9a2cefb581c09730250c56c9d30a19cc63c8/src/app.js#L115
I get the following error :
Uncaught (in promise) Error: The send transactions "from" field must be defined!
at Method.inputTransactionFormatter (truffle-contract.js:50747)
at truffle-contract.js:51228
at Array.map (<anonymous>)
at Method.formatInput (truffle-contract.js:51226)
at Method.toPayload (truffle-contract.js:51261)
at Eth.send [as sendTransaction] (truffle-contract.js:51551)
Do I need to define a 'from' field somewhere?
With the latest dependencies, none of the above answers were working for me.
I had to edit the loadAccount method:
loadAccount: async () => {
// Set the current blockchain account
const accounts = await web3.eth.getAccounts();
App.account = accounts[0];
},
then pass the App's account to the createTask method: await App.todoList.createTask(content, { from: App.account })
I was running into issues with the above answer which appears due to recent Metamask updates and that moving from web3.currentProvider to window.ethereum
I was able to make this work using
await App.todoList.createTask(content, {from: App.account})
I am using the latest truffle/contract. I needed to specify the from account in my createTask method like the following:
await App.todoList.createTask(content, { from: web3.eth.defaultAccount})
This worked.
Same happened to me on Remix while interacting with the contract deployed on Rinkeby. I chose injected web3 for the environment, But account field was empty.
It happended because I rejected the connection to metamask first and then did not get any other request to connect with metamask. So I refreshed remix, locked and unlocked metamask. It sent request to connect to metamask

Trigger a cloud build pipeline using Cloud Function

I'm trying to create a cloud function listening to cloudbuilds topic and making an API call to trigger the build. I think I'm missing something in my index.js file (I'm new to Node.js). Can you provide a sample example of a Cloud Function making an API call to the Cloud Build API?
Here is my function:
const request = require('request')
const accessToken = '$(gcloud config config-helper --format='value(credential.access_token)')';
request({
url: 'https://cloudbuild.googleapis.com/v1/projects/[PROJECT_ID]/builds',
auth: {
'bearer': accessToken
},
method: 'POST',
json: {"steps": [{"name":"gcr.io/cloud-builders/gsutil", "args": ['cp','gs://adolfo-test-cloudbuilds/cloudbuild.yaml', 'gs://adolfo-test_cloudbuild/cloudbuild.yaml']}]},
},
module.exports.build = (err, res) => {
console.log(res.body);
});
I was executing the command gcloud config config-helper --format='value(credential.access_token)', copying the token, and putting it as a value to the variable accessToken. But this didn't work for me.
Here is the error: { error: { code: 403, message: 'The caller does not have permission', status: 'PERMISSION_DENIED' } }
I had the same exact problem and I have solved it by writing a small package, you can use it or read the source code.
https://github.com/MatteoGioioso/google-cloud-build-trigger
With this package you can run a pre-configured trigger from cloud build.
You can also extend to call other cloud build API endpoints.
As my understanding cloud build API requires either OAuth2 or a service account. Make sure you gave the right permission to cloud build in the gcp console under IAM. After that you should be able to download the service-account.json file.

Obtain an id token in the Gmail add-on for a backend service authentication

The background
I'm using the Google Apps Script to create a Gmail Add-on.
Via this plugin, I would like to connect to my backend server (a non-Google service) using a REST service request. The request has to be authorised. When authorised, I could then make requests to that server to receive data associated with that user in the database. I'm already using Google sign-in in my webapp to sign in to the backend service - at the front end, I receive the id_token inside of the GoogleUser object in the authorisation response.
The problem
I need this id_token to log in to my backend service when connecting to it via the Gmail plugin. However, I couldn't find a way how to access the token.
The research
I would assume the token must be available through the API in the Apps Script.
In the webapp, I receive the id_token using the Google Auth API like this:
Promise.resolve(this.auth2.signIn())
.then((googleUser) => {
let user_token = googleUser.getAuthResponse().id_token; // this is the id_token I need in the Gmail plugin, too
// send the id_token to the backend service
...
};
In the Google Apps Script API I could only find the OAuth token:
ScriptApp.getOAuthToken();
I assumed the token could also be stored in the session. The Google Apps Script API contains the Session class and that itself contains the getActiveUser method, which returns the User object. The User object, however, only contains the user's email address, no id token (or anything else for that matter):
Session.getActiveUser().getEmail();
The question(s)
Is there a way to obtain the id token?
Am I choosing the right approach to logging in to the backend server using the data of the signed-in user in the Gmail?
Method 1: use getIdentityToken()
Gets an OpenID Connect identity token for the effective user:
var idToken = ScriptApp.getIdentityToken();
var body = idToken.split('.')[1];
var decoded = Utilities.newBlob(Utilities.base64Decode(body)).getDataAsString();
var payload = JSON.parse(decoded);
var profileId = payload.sub;
Logger.log('Profile ID: ' + profileId);
Method 2: use Firebase and getOAuthToken()
Steps to get Google ID Token from Apps Script's OAuth token:
Enable Identity Toolkit API for your Apps Script project.
Add new Firebase project to your existing Google Cloud Platform project at https://console.firebase.google.com/
Create Firebase app for platform: Web.
You will get your config data: var firebaseConfig = {apiKey: YOUR_KEY, ...}.
Enable Google sign-in method for your Firebase project at https://console.firebase.google.com/project/PROJECT_ID/authentication/providers.
Use Apps Script function to get ID Token for current user:
function getGoogleIDToken()
{
// get your configuration from Firebase web app's settings
var firebaseConfig = {
apiKey: "***",
authDomain: "*.firebaseapp.com",
databaseURL: "https://*.firebaseio.com",
projectId: "***",
storageBucket: "***.appspot.com",
messagingSenderId: "*****",
appId: "***:web:***"
};
var res = UrlFetchApp.fetch('https://identitytoolkit.googleapis.com/v1/accounts:signInWithIdp?key='+firebaseConfig.apiKey, {
method: 'POST',
payload: JSON.stringify({
requestUri: 'https://'+firebaseConfig.authDomain,
postBody: 'access_token='+ScriptApp.getOAuthToken()+'&providerId=google.com',
returnSecureToken: true,
returnIdpCredential: true
}),
contentType: 'application/json',
muteHttpExceptions: true
});
var responseData = JSON.parse(res);
idToken = responseData.idToken;
Logger.log('Google ID Token: ');
Logger.log(idToken);
return idToken;
}
Kudos to Riƫl Notermans
You should enable oAuth scopes,
https://developers.google.com/apps-script/concepts/scopes

Does sending mail via nodemailer in firebase cloud functions require billing account?

I had deployed a firebase cloud function to send a welcome mail when a user signs in for the first time.
In the firebase console, in firebase cloud function log messages, I saw this error message when the function was invoked.
Error Message:
Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions
Is it not possible to send emails for free using firebase cloud functions? if it is possible, please explain the procedure. (Possiblly with a sample code)
Edit 1:
1. I am currently using nodemailer for sending mail.
2. I am using Gmail as the mail service.
Does sending mail via nodemailer in firebase cloud functions require billing account?
NO, You DO NOT need a billing account to send email via nodmailer using cloud functions.
I was getting the billing error as yours in my cloud function. And I have done 2 simple steps and it's gone.
1. In your gmail account setting, enable Less secure app access to ON
2. Also go to this link and click continue https://accounts.google.com/DisplayUnlockCaptcha .
After doing the above 2 steps, the billing error is gone, and email is sending successfully from the cloud function.
And here is my nodejs code for your refernce:
const functions = require('firebase-functions');
const nodemailer = require('nodemailer');
const mailTransport = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'xyzz#gmail.com',
pass: '123'
},
});
exports.sendMail = functions.https.onRequest(async (req, res) => {
const mailOptions = {
from: '"Test." <noreply#firebase.com>',
to: 'xyz#gmail.com'
};
// Building Email message.
mailOptions.subject = 'Thanks and Welcome!'
mailOptions.text = 'Thanks you for subscribing to our newsletter. You will receive our next weekly newsletter.'
try {
await mailTransport.sendMail(mailOptions);
console.log('subscription confirmation email sent to');
return res.send('Sended');
} catch (error) {
console.error('There was an error while sending the email:', error);
return res.send(error.toString());
}
});
You can test locally before you deploy it
firebase serve --only functions
you will get a link http://localhost:5000/project-name/us-central1/sendMail; paste it in the browser and the cloud function will run. If any errors it will show up in the browser and console/powershell

#feathersjs/socketio-client connection timeout. Why?

I maked follow:
feathers g app # with socket and rest
feathers g service # todos & NeDB
npm start
and simple client for this. I copy code from documentation
https://docs.feathersjs.com/api/client/socketio.
const feathers = require('#feathersjs/feathers');
const socketio = require('#feathersjs/socketio-client');
const io = require('socket.io-client');
const socket = io('http://localhost:3030');
const app = feathers();
app.configure(socketio(socket));
app.service('todos')
.on('created', message => console.log('New message created', message));
app.service('todos').find().then(r => {
console.log(r)
}).catch(e => console.log('error',e))
app.service('todos').create({
title: 'A message from a REST client'
});
this client code get me timeout errors for find() and create() methods
But if I make POST request by CURL, I have onCreated message in console
Why I got errors on create() and find() calls?
UPDATE:
I maked git repo for easy reproduce this problem
https://github.com/tolyanor/feathersjs-error
UPDATE2:
I change autogenerated file src/app.js like in feathers example chat application https://github.com/feathersjs/feathers-chat/blob/master/src/app.js
Now I CAN call service method create on client, but CAN NOT receive onCreated message. So, this code
app.service('/todos')
.on('created', message => console.log('New todos created', message));
never calling
You are using a Feathers v3 client with a Feathers v2 server. Old clients will be backwards compatible with new servers but not the other way around. Follow the migration guide to upgrade your server or generate a new application using #feathersjs/cli (feathers --version on the command line should show v3.5.0 or later).