How to get location (lat & long) sent by user from Facebook messenger bot through Dialog Flow? - facebook-messenger

I'm creating a emergency chatbot in dialogflow that can get the location of the user.
So what I'm trying to achieve is to get the Latitude and Longitude from that location like how and store it in variable like this
var lat = latitude
var long = longitude

you can get information from webhook event in payload.coordinates property
reference : https://developers.facebook.com/docs/messenger-platform/send-messages/quick-replies

Create a custom follw-up intent with event input called FACEBOOK_LOCATION, then the lat and lng is set in context facebook_location, you can print this in a dialwoflow response with "lat: #facebook_location.lat, long: #facebook_location.long"
Image example:

Related

Sending emails to multiple users using flows(Salesforce)

I need to send an email notification to the record owner and manager once the opportunity is closed-won.
adding only owner email works fine
adding only manager email works fine
But if I add both together with coma, {!$Record.Owner.Email},{!$Record.Engagement_Manager__r.Email} I'm getting error.
what is the correct way to add it?
You can try creating a Formula Resource in your flow like this but, in your case, using $Record.Owner.Email and $Record.Engagement_Manager__r.Email:
Then, you can use this Resource in your Email Action:
Try the below code and let me know if it works.
global class SendPurchaseOrderEmail {
WebService static void sendEmail(String poId) {
List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
String theTemplate = [SELECT Id FROM EmailTemplate WHERE DeveloperName = 'Purchase_Order_With_Items'].Id;
User theUser = [SELECT Id FROM User WHERE Name = 'user name goes here'];
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setSaveAsActivity(false);
mail.setTemplateId(theTemplate);
mail.setWhatId(poId);
mail.setTargetObjectId(theUser.Id);
mail.setToAddresses(new String[] { 'TestUser#salesforce.com' ,'abc#test.com'}); //add other emails here.
emails.add(mail);
Messaging.sendEmail(emails);
}
}
Please refer below link for more details.
https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_sendemail.htm
This is because you have to pass a direct email address there.
Instead of that, you can create a collection variable, store the emails into it, then pass that variable to email addresses (collection) field.
Note: you can only store upto 5 emails into that colllection variable at a time.
Hi For that you can simply add collection Variable.
For that variable assign multiple values to it. So that you can send email to both record owner as well as manager.
From New Resource Select the Variable and click Allow Multiple Values and Data-type as text.
Then by using Assignment. Add the following email Address to it Please refer the below image.
I hope you have got the solution
Thanks

Accessing link in email message using gmail api & Cypress

hope u all safe ,
i am doing e2e automated test by Cypress , and i have problem to access link in the received email (Gmail account)from a specific email address. So far using GMAIL api I am able to get the email id using Cy.task
testCase 1. : visit signup page and fill information .// Passed
testCase 2 : ensure that email has received by using gmail-tester library // Passed
testCase 3: the problem is here ===>> click on CTA confirm ur email address and it should direct me to confirmation page Or extract href then cy.visit(href)
**href**="http://post.spmailtechnol.com/f/a/mD0QS83FHCNqxzGZpDJgfg~~/AALxrAA~/RgRgYvyvP0T3aHR0cHM6Ly9uZXh0LWRldi50YWphd2FsLmNvbS9lbi91c2VyL3ZlcmlmeT90b2tlbj00ZjM5Y2I0ZC0yZjU2LTQxYmItOWFlNC0yMDFjN2Y3ZTAyM2UmcmVxdWVzdElkPWM2ZGNiOTEwLThkZWQtNDFhYy05ODQ0LWJjMTdlZWFmOTEyNyZ1dG1fc291cmNlPXRyYW5zYWN0aW9uYWwmdXRtX21lZGl1bT1lbWFpbCZ1dG1fY2FtcGFpZ249MjAyMDAzMzBfRU5fQ09NX1JFR0lTVFJBVElPTiZ1dG1fY29udGVudD1Cb2R5JnV0bV90ZXJtPUNUQVcDc3BjQgoAAC_JgV6KRz5mUh9lbHNoYWlraHRlc3RlbWFpbHMrMjBAZ21haWwuY29tWAQAAAAB" style="font-size:14px;color:#ffffff;text-decoration:none;border-radius:2px;padding:12px 0 12px 0;display:inline-block;border-top:1px solid #499df3;border:none;font-weight:bold;min-width:190px;text-align:center;background:#1dac08"
↵ target="_blank">Confirm email</a>
thanks in advance for ur reply & help , Thank you
if you need to click on href try this
cy.get('[href*="post.spmailtechnol.com"]').click()
or
cy.get('[target="_blank"]').click()
If you are getting a raw body response (a string) you cannot use the cypress method unless you convert this strings into a DOM object so you have to get the link in this way if you have an email body as string:
const links = body.split("href=http://my.url.com");
var activation_link = links[0].match(/\bhttp?:\/\/\S+/);
activation_link= activation_link[0].replace('"','')
cy.visit(activation_link)

Fetching data really fast from Google cloud firestore

I am making a flutter application and I’m using cloud firestore as my online database. One of the features in my app is looking for nearby users and showing their profile to the current user in a custom widget on screen. The way I do it is I get current user’s location (either live location or the address saved in database) and then go through every single user in my database collection for users. I get the address of the user from the stored data, calculate the distance using Distance Matrix API and then if distance is less than a specific number (e.g 10000 meter) I create the profile widget for the user to show it on screen.
There are 2 problems:
1- if my number of users grows (for example a million users), By going through every user detail and calculating the distance, It can take a really long time to get the results on the screen . Right now, I only have 20 users for testing purposes and when I search for nearby users, it can take 30 seconds for the results to show up on the screen.
2- With a slow internet connection, the waiting time can be much much more and it can use lots of user’s data for this simple task.
How can I improve this feature and make it faster?
(The current idea that I have is dividing user’s in different documents with respect to their location and then going through only one of the documents by using current user’s location. The problem is that how to divide the addresses efficiently and find the best addresses to look for.)
Below is the code where I find nearby users and add them to a list which I pass to my custom widget class.
final List<UserBoxDesign> listOfBoxes = [];
final FirebaseUser currentUser = await auth.currentUser();
final String currentUserId = currentUser.uid;
if (_userLocationSwitchValue == false) { //use default address of the user
currentUserAddress = await _databaseManagement.getUserCollectionValues(
currentUserId, "address");
} else {
//currentUserAddress = //to do, get device location here.
}
if (_searchValue == SearchValues.Users) {
final List<String> userIds = await _databaseManagement.getUserIds();
for (String id in userIds) {
final String otherUserLocations =
await _databaseManagement.getUserCollectionValues(id, "address");
final String distanceMeters = await _findDistanceGoogleMaps(
currentUserAddress, otherUserLocations);
if (distanceMeters == "Address can't be calculated" ||
distanceMeters == "Distance is more than required by user") {
//if it's not possible to calculate the address then just don't do anything with that.
} else {
final double distanceValueInKilometers = (double.parse(
distanceMeters) /
1000)
.roundToDouble();
final String userProfileImageUrl =
await _databaseManagement.getUserCollectionValues(id, "image");
final String username =
await _databaseManagement.getUserCollectionValues(id, "username");
listOfBoxes.add(
UserBoxDesign( //it creates a custom widget for user if user is nearby
userImageUrl: userProfileImageUrl,
distanceFromUser: distanceValueInKilometers,
userId: id,
username: username,
),
); //here we store the latest values inside the reserved data so when we create the page again, the value will be the reservedData value which is not empty anymore
}
print(listOfBoxes);
}
listOfBoxes.sort((itemA,itemB)=>itemA.distanceFromUser.compareTo(itemB.distanceFromUser)); //SORTs the items from closer to more far from user (we can reverse it to far comes first and close goes last)
setState(() {
_isSearchingForUser = false;
});
return listOfBoxes;
Here is the code where I calculate the distance between origin address and destination address.
Future<String> _findDistanceGoogleMaps(
String originAddress, String destinationAddress) async {
final String url =
"https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=$originAddress&destinations=$destinationAddress&key=$GoogleMapsAPIKey";
try {
final response = await http.get(url);
final responseDecoded = json.decode(response.body);
final distanceInMeters = double.parse(responseDecoded["rows"][0]
["elements"][0]["distance"]["value"]
.toString()); //this is the value in meters always so for km , divide by 1000.
if (distanceInMeters < 100000) {
return distanceInMeters.toString();
} else {
return "Distance is more than required by user";
}
} catch (e) {
return "Address can't be calculated";
}
}
this is how my screen looks when I find nearby users.
if you give code example it will be easy to answer.
I can suggest (we had similar task) to use coordinates longitude and latitude and make requests in your range.
So you don't need Distance Matrix API (I think it will be expensive) and your queries will be fast and cheap.
I googled and found out answer here
How to run a geo "nearby" query with firestore?
==after updated question==
You try to use all the logic inside screen and do it synchronously. Because of that you have such a long rendering time.
You calculate everything on user device and pass to a widget return listOfBoxes;
Instead you can try to use Streambuilder, example is here How to efficiently access a firestore reference field's data in flutter?
Organise data in your database in a such way, that you can make request for your purposes: "Find all users within X range sorted by distance AND ...".
In this case Firebase will do it very quickly and pass data to your Streambuilder asynchronously.
I guess that you can keep longitude, latitude and work with them instead of addresses.
Sorry, I cant rewrite your code, not enough info. Just look example by link, there is a good example.
==update 2==
The package https://pub.dev/packages/geoflutterfire
allow to store geo data to Firestore and how to make requests
// Create a geoFirePoint
GeoFirePoint center = geo.point(latitude: 12.960632, longitude: 77.641603);
// get the collection reference or query
var collectionReference = _firestore.collection('locations');
double radius = 50;
String field = 'position';
Stream<List<DocumentSnapshot>> stream = geo.collection(collectionRef: collectionReference)
.within(center: center, radius: radius, field: field);

Gmail API Watch not filtering by Label

I am using Gmail Push Notifications with Google PubSub and have a custom label that I want to monitor for any changes. I use the following code to register a watch for the label (Id of the label is Label_1)
WatchRequest wr = new WatchRequest();
wr.TopicName = "projects/" + primaryLink.ggProjectId + "/topics/iLink" + segmentId;
if (labels != null && labels.Count > 0)
{
wr.LabelIds = new List<string>();
wr.LabelIds.Add("Label_1");
wr.LabelFilterAction = "include";
}
WatchResponse wrr = gs.Users.Watch(wr, emailAccount).Execute();
return "HistoryId " + wrr.HistoryId.ToString();
}
The watch registers OK. The issue is that I get push notifications for any Gmail change not just those under the label.
Are custom labels supported?
I noticed the same issue but later on found out that its because of the way API works. You can filter the emails via LabelIds but you will receive notifications only if emails are directly being filtered to selected custom label. I guess its design rather than a flaw in the API.
To test this, create a custom filter in Gmail which would directly apply your custom label to a set of emails and you should be receiving notifications for those emails.
Edited (June 11, 2015):
Push notification send you HistoryID and user's mailbox name. In response your endpoint should call userhistory.list() with HistoryID and LabelId you want to monitor for changes.
$opt_param = array();
$opt_param['startHistoryId'] = $historyID;
$opt_param['labelId'] = $labelID;
$opt_param['fields'] = 'nextPageToken,historyId,history/messagesAdded';
$service->users_history->listUsersHistory($userID, $opt_param);
Above is a PHP code snippet to filter the history list with historyID and labelID.

Get user cover picture by Id

I'm working on a web application which is mostly based of Facebook
Graph API. I hold some user's data - actually , the possible
public data available - such as profile picture, name and id. I
wondered how I'll be able to get a direct link to a user cover picture
of a user only by using his id? and I already got the User ID.
This is the code that I used to get the profile picture & it worked-
<img src="https://graph.facebook.com/{{user.id}}/picture?type=large" style="float:left;"/>
Now I want to get cover picture.
Thanks in advance.
To get the cover picture of a user, make this call-
\GET http://graph.facebook.com/{user-id}?fields=cover
You'll get the image url in source key of the JSON response:
{
cover: {
id: "111222333",
offset_y: 55,
source: "https://scontent-a.xx.fbcdn.net/.....jpg" // that's the cover photo url
},
id: "111222"
}

Resources