How to send bulk SMS messages with Twilio Java SDK? - java

I've found plenty of information on how to send bulk of sms messages with Js, Python, PHP SDKs but nothing on how to achieve this using Java?
Here is a code snippet demonstrating the implementation for Python.
from twilio.rest import Client
account = "AC98e9a2817c2e0b4d38b42d1445ef42d9"
token = "your_auth_token"
client = Client(account, token)
notification = client.notify.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")\
.notifications.create(
to_binding=[
"{\"binding_type\":\"sms\",\"address\":\"+15555555555\"}",
"{\"binding_type\":\"facebook-messenger\",\"address\":\"123456789123\"}"
],
body="Hello Bob")

Twilio developer evangelist here.
There is an example of sending bulk SMS messages with Java in the documentation for Twilio Notify.
Here is the example:
import java.util.Arrays;
import java.util.List;
import com.twilio.Twilio;
import com.twilio.rest.notify.v1.service.Notification;
public class Example {
// Find your Account Sid and Token at twilio.com/user/account
public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static final String AUTH_TOKEN = "your_auth_token";
public static final String SERVICE_SID = "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static void main(String[] args) {
// Initialize the client
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
List<String> toBindings = Arrays.asList(
"{\"binding_type\":\"sms\",\"address\":\"+15555555555\"}",
"{\"binding_type\":\"facebook-messenger\",\"address\":\"123456789123\"}");
Notification notification = Notification
.creator(SERVICE_SID)
.setBody("Hello Bob")
.setToBinding(toBindings)
.create();
System.out.println(notification.getSid());
}
}

Here is the official guide how to do that in java:
https://www.twilio.com/docs/libraries/java

Twilio developer evangelist here. You can get started with free credits here which should last you a month or two if you’re using it for personal use. https://www.twilio.com/try-twilio
More details on working with your trial account here: https://www.twilio.com/docs/usage/tutorials/how-to-use-your-free-trial-account

Related

Can somebody help me to get started with Google Dialogflow in spring boot

Searched a lot but there is no precise answer on how to get started with dialogflow in spring boot.
Aim: To detect intent from GDF knowledgebase and return back the response.
What I have done so far:
Tried executing this code https://github.com/googleapis/java-dialogflow/blob/HEAD/samples/snippets/src/main/java/com/example/dialogflow/DetectIntentTexts.java
by creating a main app.
App.java
package com.example.dialogflow;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class App {
public static void main(String[] args) {
DetectIntentTexts theDetectIntentTexts = new DetectIntentTexts();
String projectId = "abc";
String sessionId = "xyz";
String lang = "en";
List<String> myTexts = new ArrayList<>();
myTexts.add("hi");
String ans = null;
try {
ans = String.valueOf(theDetectIntentTexts.detectIntentTexts(projectId, myTexts, sessionId, lang));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Bot reply:" + ans);
}
}
But it fails to run.
I have my service account GCP set in local machine and export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your-project-credentials.json is set too
Any help would be appreciated.
Finally was able to solve it.
Steps:
First run
gcloud auth application-default revoke
This will remove user account & service account credentials.
Now login into gcloud using service account credentials.
gcloud auth activate-service-account --key-file=key.json
Wonder why we have to revoke user account credentials because keeping both the accounts and activating service account didn't work.
Now it works.

How to put Label in email using AWS SES?

I have used this code to send email using AWS SES:
package com.amazonaws.samples;
import java.io.IOException;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder;
import com.amazonaws.services.simpleemail.model.Body;
import com.amazonaws.services.simpleemail.model.Content;
import com.amazonaws.services.simpleemail.model.Destination;
import com.amazonaws.services.simpleemail.model.Message;
import com.amazonaws.services.simpleemail.model.SendEmailRequest;
public class AmazonSESSample {
static final String FROM = "sender#example.com";
static final String TO = "recipient#example.com";
static final String SUBJECT = "Amazon SES test (AWS SDK for Java)";
static final String HTMLBODY = "Amazon SES test (AWS SDK for Java)";
static final String TEXTBODY = "This email was sent through Amazon SES ";
public static void main(String[] args) throws IOException {
try {
AmazonSimpleEmailService client =
AmazonSimpleEmailServiceClientBuilder.standard().withRegion(Regions.US_EAST_1).build()
SendEmailRequest request = new SendEmailRequest()
.withDestination(
new Destination().withToAddresses(TO))
.withMessage(new Message()
.withBody(new Body()
.withHtml(new Content()
.withCharset("UTF-8").withData(HTMLBODY))
.withText(new Content()
.withCharset("UTF-8").withData(TEXTBODY)))
.withSubject(new Content()
.withCharset("UTF-8").withData(SUBJECT)))
.withSource(FROM)
client.sendEmail(request);
System.out.println("Email sent!");
} catch (Exception ex) {
System.out.println("The email was not sent. Error message: "
+ ex.getMessage());
}
}
}
Now, my problem is I have to add a label to this email such that receiver sees:
MyLabel < #example.com>
instead of what receiver is currently seeing:
sender#example.com
According to AWS SES's developer guide,
You can add labels to verified email addresses without performing
additional verification steps. To add a label to an email address, add
a plus sign (+) between the account name and the "at" sign (#),
followed by a text label. For example, if you already verified
sender#example.com, you can use sender+myLabel#example.com as the
"From" or "Return-Path" address for your emails. You can use this
feature to implement Variable Envelope Return Path (VERP). Then you
can use VERP to detect and remove undeliverable email addresses from
your mailing lists.
But, if I change FROM to "sender+MyLabel#example.com", email gets sent as:
sender+MyLabel#example.com
Eventhough, I have verified my FROM email address. Please help.
I added label to my email by replacing my FROM variable's value from "sender#example.com" to "myLabel< sender#example.com>"
static final String FROM = "myLabel< sender#example.com>";

Google Analytics Reports v4 API does not show graph in browser [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have started updating with Google Analytics Reports v4 API. I have no prior knowledge. I am trying to generate a simple graph.
I have used the given sample code given in google analytics document. But I am not getting the report at all, but a message
Received verification code. You may now close this window...
No idea why such message displaying. It looks like there is no data available. So far I have done the below things to run the project.
Create the project.
Crate the service.
Create the View with email address retrieved from service's JSON file.
Create client_secrets.json and add it to my src\ folder.
Get the view id and use it in my code.
I do not know which direction to go from here. There are many things to look after and the documentation is really healthy. This is difficult for a beginner like me to decide to choose the right parts.
Also, I have the below questions to know answer.
Is it possible to run it on local server such as Tomcat?
Is google analytics free? Can I use it using my gmail email address?
Is it important to have domain and hosting to get the report in browser?
Am I need to give valid return URL while setting the client settings?
Why am I need to give View ID? If it is to give manually then how do I generate the report dynamically?
Here is my environment and Java code. Please review and help me to find the solution.
I am looking forward to a smooth and clean guidelines.
Environment
Eclipse Java EE with Tomcat 9.0.30 server.
Java used as programming language.
Code
package com.garinst;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.api.services.analyticsreporting.v4.AnalyticsReportingScopes;
import com.google.api.services.analyticsreporting.v4.AnalyticsReporting;
import com.google.api.services.analyticsreporting.v4.model.ColumnHeader;
import com.google.api.services.analyticsreporting.v4.model.DateRange;
import com.google.api.services.analyticsreporting.v4.model.DateRangeValues;
import com.google.api.services.analyticsreporting.v4.model.GetReportsRequest;
import com.google.api.services.analyticsreporting.v4.model.GetReportsResponse;
import com.google.api.services.analyticsreporting.v4.model.Metric;
import com.google.api.services.analyticsreporting.v4.model.Dimension;
import com.google.api.services.analyticsreporting.v4.model.MetricHeaderEntry;
import com.google.api.services.analyticsreporting.v4.model.Report;
import com.google.api.services.analyticsreporting.v4.model.ReportRequest;
import com.google.api.services.analyticsreporting.v4.model.ReportRow;
/**
* A simple example of how to access the Google Analytics API.
*/
public class HelloAnalytics {
// Path to client_secrets.json file downloaded from the Developer's Console.
// The path is relative to HelloAnalytics.java.
private static final String CLIENT_SECRET_JSON_RESOURCE = "client_secrets.json";
// Replace with your view ID.
private static final String VIEW_ID = "96519128";
// The directory where the user's credentials will be stored.
/*
* private static final File DATA_STORE_DIR = new File(
* System.getProperty("user.home"), ".store/hello_analytics");
*/
private static final File DATA_STORE_DIR = new File("hello_analytics");
private static final String APPLICATION_NAME = "Hello Analytics Reporting";
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
private static NetHttpTransport httpTransport;
private static FileDataStoreFactory dataStoreFactory;
public static void main(String[] args) {
try {
AnalyticsReporting service = initializeAnalyticsReporting();
GetReportsResponse response = getReport(service);
printResponse(response);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Initializes an authorized Analytics Reporting service object.
*
* #return The analytics reporting service object.
* #throws IOException
* #throws GeneralSecurityException
*/
private static AnalyticsReporting initializeAnalyticsReporting() throws GeneralSecurityException, IOException {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
// Load client secrets.
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
new InputStreamReader(HelloAnalytics.class.getResourceAsStream(CLIENT_SECRET_JSON_RESOURCE)));
// Set up authorization code flow for all authorization scopes.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY,
clientSecrets, AnalyticsReportingScopes.all()).setDataStoreFactory(dataStoreFactory).build();
// Authorize.
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
// Construct the Analytics Reporting service object.
return new AnalyticsReporting.Builder(httpTransport, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME).build();
}
/**
* Query the Analytics Reporting API V4. Constructs a request for the sessions
* for the past seven days. Returns the API response.
*
* #param service
* #return GetReportResponse
* #throws IOException
*/
private static GetReportsResponse getReport(AnalyticsReporting service) throws IOException {
// Create the DateRange object.
DateRange dateRange = new DateRange();
dateRange.setStartDate("7DaysAgo");
dateRange.setEndDate("today");
// Create the Metrics object.
Metric sessions = new Metric().setExpression("ga:sessions").setAlias("sessions");
// Create the Dimensions object.
Dimension browser = new Dimension().setName("ga:browser");
// Create the ReportRequest object.
ReportRequest request = new ReportRequest().setViewId(VIEW_ID).setDateRanges(Arrays.asList(dateRange))
.setDimensions(Arrays.asList(browser)).setMetrics(Arrays.asList(sessions));
ArrayList<ReportRequest> requests = new ArrayList<ReportRequest>();
requests.add(request);
// Create the GetReportsRequest object.
GetReportsRequest getReport = new GetReportsRequest().setReportRequests(requests);
// Call the batchGet method.
GetReportsResponse response = service.reports().batchGet(getReport).execute();
// Return the response.
return response;
}
/**
* Parses and prints the Analytics Reporting API V4 response.
*
* #param response the Analytics Reporting API V4 response.
*/
private static void printResponse(GetReportsResponse response) {
for (Report report : response.getReports()) {
ColumnHeader header = report.getColumnHeader();
List<String> dimensionHeaders = header.getDimensions();
List<MetricHeaderEntry> metricHeaders = header.getMetricHeader().getMetricHeaderEntries();
List<ReportRow> rows = report.getData().getRows();
if (rows == null) {
System.out.println("No data found for " + VIEW_ID);
return;
}
for (ReportRow row : rows) {
List<String> dimensions = row.getDimensions();
List<DateRangeValues> metrics = row.getMetrics();
for (int i = 0; i < dimensionHeaders.size() && i < dimensions.size(); i++) {
System.out.println(dimensionHeaders.get(i) + ": " + dimensions.get(i));
}
for (int j = 0; j < metrics.size(); j++) {
System.out.print("Date Range (" + j + "): ");
DateRangeValues values = metrics.get(j);
for (int k = 0; k < values.getValues().size() && k < metricHeaders.size(); k++) {
System.out.println(metricHeaders.get(k).getName() + ": " + values.getValues().get(k));
}
}
}
}
}
}
Maven Dependencies
<dependencies>
<!-- https://mvnrepository.com/artifact/com.google.oauth-client/google-oauth-client-jetty -->
<dependency>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId>
<version>1.30.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.api-client/google-api-client-gson -->
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client-gson</artifactId>
<version>1.30.7</version>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-analyticsreporting</artifactId>
<version>v4-rev20190904-1.30.1</version>
</dependency>
</dependencies>
Received verification code. You may now close this window...
This is the first step in the Oauth2 flow once the user has autorized your access to their google analytics data this code is returned to your application which is then exchanged for an access token. You may want to look into Oauth2 or you could just do what it says and close the window.
Is google analytics free? Can I use it using my gmail email address?
Yes the Google analytics api is free to use. Users login to your application with the user they have set up in their google analytics account
Is it important to have domain and hosting to get the report in browser?
You will need to host your application some place that users can access it. Remember google analytics returns data as Json it will be up to you to build your reports and display it to your users.
Am I need to give valid return URL while setting the client settings?
You will need a valid redirect uri if you are going to host this on the web in order for the authorization process to complete.
Why am I need to give View ID? If it is to give manually then how do I generate the
report dynamically?
Users can have more then one google analytics account each account can have more then one web properly and each web property can have more then one view. Your users need to be able to decide which view they want to see data for.
Note
This system is for requesting data from google analytics the raw data it is returned as json. It is not returned as reports you will need to create your graphics yourself. Oauth2 login is for multi user system anyone can log in to your application its not going to just show your personal data.
comment question
Is there any possibility to get the dynamic result such as user will login and get his own data?
Thats how oauth2 works. The user logs in your application has access to their data
How is it possible to display the JSON data in graphical reports as available in google analytics?
You will either need to create a library for graphics or find one already created for you by a third party and plug in the data you get back from Google analytics. APIs just return json data they dont have any control over how you the developer display it.

Authy Authentication is throwing UnknownHostException

I'm trying to implement 2 phase authentication for my application using authy authentication.
While trying to verify the token generated in authy mobile app m getting UnknownHostException.
package tes.resource;
import com.authy.*;
import com.authy.api.*;
public class SampleAuthenticator {
AuthyApiClient client=null;
public void init(){
String apiKey = "API_KEY";
String apiUrl = "http://api.authy.com";
boolean debugMode = true;
client = new AuthyApiClient(apiKey, apiUrl, debugMode);
}
public void register(String userid,String phone){
Users user=client.getUsers();
user.createUser(userid,phone, "57");
}
public boolean verify(){
Tokens tokens = client.getTokens();
Token verification = tokens.verify(27319980, "7983610");
return verification.isOk();
}
public static void main(String[] args){
SampleAuthenticator objSampleAuthenticator=new SampleAuthenticator();
objSampleAuthenticator.init();
System.out.println(objSampleAuthenticator.verify());
}
}
I have created a application to test whether authy is verifying the user based on the random token generated in authy app.
Any help is appreciated.
Authy developer evangelist here.
First I would recommend you change your Authy API key, since you seem to have leaked it in this question.
Secondly, the Authy API URL requires HTTPS. My guess is that you need to change
String apiUrl = "http://api.authy.com";
to an HTTPS url:
String apiUrl = "https://api.authy.com";
Let me know if that helps.

Posting status message to facebook page

Im trying to post some status message on my facebook page, not my personal facebook profile account, but on page i created separately.
My current code looks like this:
import facebook4j.Facebook;
import facebook4j.FacebookException;
import facebook4j.FacebookFactory;
import facebook4j.Post;
import facebook4j.ResponseList;
import facebook4j.conf.Configuration;
import facebook4j.conf.ConfigurationBuilder;
public class FacebookImpl {
// from https://developers.facebook.com/apps/
static String appId = "11removed";
// from https://developers.facebook.com/apps/
static String appSecret = "c0removed";
// from https://developers.facebook.com/tools/accesstoken/
static String appToken = "11removed";
// my facebook page
static String myFaceBookPage = "niremoved";
public static void main(String[] args) throws FacebookException {
// Make the configuration builder
ConfigurationBuilder confBuilder = new ConfigurationBuilder();
confBuilder.setDebugEnabled(true);
// Set application id, secret key and access token
confBuilder.setOAuthAppId(appId);
confBuilder.setOAuthAppSecret(appSecret);
confBuilder.setOAuthAccessToken(appToken);
// Set permission
// https://developers.facebook.com/docs/facebook-login/permissions
confBuilder.setOAuthPermissions("manage_pages,publish_pages,publish_actions");
confBuilder.setUseSSL(true);
confBuilder.setJSONStoreEnabled(true);
// Create configuration object
Configuration configuration = confBuilder.build();
// Create FacebookFactory and Facebook instance
FacebookFactory ff = new FacebookFactory(configuration);
Facebook facebook = ff.getInstance();
// this one works fine
System.out.println(getFacebookPostes(facebook, myFaceBookPage));
// try to post status
// FacebookException{statusCode=403, errorType='OAuthException',
// errorMessage='(#200) The user hasn't authorized the application to perform this action', errorCode=200, errorSubcode=-1, version=2.4.5}
facebook.postStatusMessage(myFaceBookPage, "Test Facebook4J.");
}
public static String getFacebookPostes(Facebook facebook, String page) throws FacebookException {
ResponseList<Post> results = facebook.getPosts(page);
// as example just to see if i get any data
return results.get(0).getMessage();
}
}
Problem is that i cant post any message on page using this code: facebook.postStatusMessage(myFaceBookPage, "Test Facebook4J."); but i can get messages already posted (via facebook web interfaces) with method getFacebookPostes.
Can anyone help me with this one ? And please do not paste some random dev.Facebook link to look into API.
What i did:
- create app on https://developers.facebook.com/apps/ i have appid, appsecret
Thanks

Categories