Controlling events of a Twilio call - java

In the next sample code, Twilio puts in conversation OPERATOR_PHONE_NUMBER to CLIENT_PHONE_NUMBER, and records the call.
But I don't know what should be the code to control some things, one or both of the phones...:
does not exist.
exists but communicates.
exists, does not communicate but does not pick up.
exists, does not communicate, picks up and the conversation takes place.
import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Call;
import com.twilio.rest.api.v2010.account.CallCreator;
import com.twilio.type.PhoneNumber;
import com.twilio.type.Twiml;
public class SimpleCallWithRecording2 {
private static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
private static final String AUTH_TOKEN = "9ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ";
private static final String ASSIGNED_PHONE_NUMBER = "+15999999999999";
//Must be verified numbers in trial account
private static final String OPERATOR_PHONE_NUMBER = "+34888888888";
private static final String CLIENT_PHONE_NUMBER = "+34777777777";
public static void main(String[] args) throws Exception {
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
PhoneNumber to = new PhoneNumber(OPERATOR_PHONE_NUMBER);
PhoneNumber from = new PhoneNumber(ASSIGNED_PHONE_NUMBER);
Twiml twiml = new Twiml(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?> " +
"<Response> " +
" <Say voice=\"woman\">This is said by a robotic woman</Say> " +
" <Dial> " +
" <Number> " + CLIENT_PHONE_NUMBER + "</Number> " +
" </Dial> " +
"</Response> " );
CallCreator callCreator = Call.creator(to, from, twiml);
callCreator.setRecord(true);
Call call = callCreator.create();
System.out.println(call);
}
}
In the doc I see something could be done with callCreator.setStatusCallback(URI.create("https://www.myapp.com/events")), and some clasification of events: "initiated", "ringing", "answered", "completed". BUT I havent find the code "on the other side", I mean in https://www.myapp.com/events extreme ¿?

You need to setup a that rest endpoint and set it as status callback url.
The url will recieve events from twilio.
Refer this
edit: if you also need events from the nested verb, define attribute 'action' to it.
ie
<Dial action="//callbackURL">
<Number> CLIENT_PHONE_NUMBER </Number>
</Dial>
that way you'll know your cases 1 ,2 ,3 ,4.
and to "control" the call, you just respond with the desired TwiML to the callback request. Hope this clarifies.
edit2: You need to do something like:
//handles callback url
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
{ //...
TwiMLResponse twiml = new TwiMLResponse();
String callSid = request.getParameter("CallSid");
//handle call specific data
switch(request.getParameter("CallStatus")){
case "no-answer": //construct twiML
case "ringing" ://...
}
//...
response.setContentType("application/xml");
response.getWriter().print(twiml.toXML());
}
See: IVR - Example

Related

How to assign roles with a Discord bot made in Java?

I'm trying to get my Meeseeks bot to assign and remove roles on discord for my personal server. I'm not all too familiar with the special methods and commands, and I've had no luck looking for it!
This is my code right now;
package discord.meeseeksBot;
import discord.meeseeksBot.Ref2;
import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.JDABuilder;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.MessageChannel;
import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
public class App extends ListenerAdapter
{
public static void main(String[] args) throws Exception
{
JDA jda = new
JDABuilder(AccountType.BOT).setToken(Ref2.token).buildBlocking();
jda.addEventListener(new App());
}
#Override
public void onMessageReceived(MessageReceivedEvent evt)
{
User objUser = evt.getAuthor();
MessageChannel objMsgCh = evt.getChannel();
Message objMsg = evt.getMessage();
//the prefix to which the bot responds to is "Mr.Meeseeks, "
if(objMsg.getContentRaw().equalsIgnoreCase(Ref2.prefix+"I need
help"))
{
objMsgCh.sendMessage("Hi, " + objUser.getAsMention() + ", " + "
I'm Mr.Meeseeks! Look at me! How can I help?").queue();
objMsgCh.sendMessage("You can tell me to **ADD** you to a role,
or **REMOVE** you from a role!").queue();
}
}
}
I'm working to get the bot to where he'll reply to "Mr.Meeseeks, I need help"
with a list of title roles (these roles serve no hierarchical purpose, nor do they appear separately from online members!) you can choose from, and apply to yourself. I'd also like him to be able to remove yourself from a role.
And example for what I had in mind was a role for gender pronouns, (i.e. "she/her" or "he/him") so that when a profile is clicked on in the server, you'd be able to see what they'd be called.
So you could say, "Mr.Meeseeks, add me to "she/her" pronouns!" and he'd do that for you, or "Mr.Meeseeks, remove me from "she/her" pronouns!".
I can't seem to figure it out for Java.
I am not too familiar with JDA, as Discord4J is better, but I can point you in the right direction.
You want to use regex to test for "Mr", "Meeseeks", "add", and "me" all in the same message. Then you can test for the gender pronouns:
#Override
public void onMessageReceived(MessageReceivedEvent evt) {
User objUser = evt.getAuthor();
MessageChannel objMsgCh = evt.getChannel();
Message objMsg = evt.getMessage();
String content = objMsg.getContentRaw();
Guild guild = evt.getGuild();
//the prefix to which the bot responds to is "Mr.Meeseeks, "
if (objMsg.getContentRaw().equalsIgnoreCase(Ref2.prefix + "I need help")) {
objMsgCh.sendMessage("Hi, " + objUser.getAsMention() + ", " + " I'm Mr.Meeseeks! Look at me! How can I help?").queue();
objMsgCh.sendMessage("You can tell me to **ADD** you to a role, or **REMOVE** you from a role!").queue();
// Test for "Mr", "Meeseeks", "add", and "me".
} else if (content.matches("^(?=.*\\badd\\b)(?=.*\\bme\\b)(?=.*\\bto\\b)(?=.*\\bMr\\b)(?=.*\\bMeeseeks\\b).+")) {
// Test for pronouns (Assuming your roles names are "he/him" and "she/her")
Role group = content.matches("((she)|(her))") ? guild.getRolesByName("she/her", true).get(0) :
content.matches("((he)|(him))") ? guild.getRolesByName("he/him", true).get(0) : null;
if (group == null) {
// Let the user know if they used an invalid pronoun.
objMsgCh.sendMessage("Sorry " + objUser.getAsMention() + ", I can't find that role!").queue();
} else {
// Assign the role.
guild.getController().addRolesToMember​(guild.getMember(objUser), group);
objMsgCh.sendMessage("Added " + objUser.getAsMention() + " to " + group.getName() + "!").queue();
}
}
}

NullPointerException in Gdx.net.sendHttpRequest

I have tried to write a little code using libGDX to work with network. Here's a code:
public class Test {
public static void main(String[] args) {
String accessToken = "********"; //a set of symbols, not important because it is specific of request target
String userID = "*********"; //also not important
String message = "Hello World";
String uri = "method/wall.post?owner_id=" + userID + "&message=" + message + "&access_token=" + accessToken;
HttpRequestBuilder requestBuilder = new HttpRequestBuilder();
HttpRequest httpRequest = requestBuilder.newRequest().method(HttpMethods.GET).url("https://api.vk.com/").content(uri).build();
Gdx.net.sendHttpRequest(httpRequest, //Here Eclipse shows NullPointerException
null); //But not here
}
If I write this URL in browser, it works right. It means, that the problem on my side. How to fix it?
Summary of values of the object which causes NullPointerException:
You are writing this code in the static main entry point of your program. Your Gdx is not yet loaded,so Gdx is still null at this point.
Create a none static class and put your code in it's constructor and initialize that class within this static entry point.
public class WebTest()
{
public WebTest()
{
String accessToken = "********"; //a set of symbols, not important because it is specific of request target
String userID = "*********"; //also not important
String message = "Hello World";
String uri = "method/wall.post?owner_id=" + userID + "&message=" + message + "&access_token=" + accessToken;
HttpRequestBuilder requestBuilder = new HttpRequestBuilder();
HttpRequest httpRequest = requestBuilder.newRequest().method(HttpMethods.GET).url("https://api.vk.com/").content(uri).build();
Gdx.net.sendHttpRequest(httpRequest, //Here Eclipse shows NullPointerException
null); //But not here
}
}
public class Test {
public static void main(String[] args) {
new WebTest();
}
}

Authorize.net Java example

I am looking to develop simple Java program which will be sending a request and get response from "Authorize.net" say for Authorization, Capture, Void, Refund Transactions etc. I have created my test account in authorized.net - https://sandbox.authorize.net/. I did goggled lots of week and didn't find any sample example for reference.
I am using AIM for my development, let's say I've code for AuthTransaction
GenericValue cc = (GenericValue) params.get("creditCard");
String currency = (String) params.get("currency");
String amount = ((BigDecimal)params.get("processAmount")).toString();
String number = UtilFormatOut.checkNull(cc.getString("cardNumber"));
String expDate = UtilFormatOut.checkNull(cc.getString("expireDate"));
String cardSecurityCode = (String) params.get("cardSecurityCode");
AIMRequest.put("x_Amount", amount);
AIMRequest.put("x_Currency_Code", currency);
AIMRequest.put("x_Method", props.getProperty("method"));
AIMRequest.put("x_Type", props.getProperty("transType"));
AIMRequest.put("x_Card_Num", number);
AIMRequest.put("x_Exp_Date", expDate);
if (UtilValidate.isNotEmpty(cardSecurityCode)) {
AIMRequest.put("x_card_code", cardSecurityCode);
}
if (AIMRequest.get("x_market_type") != null) {
AIMRequest.put("x_card_type", getCardType(UtilFormatOut.checkNull(cc.getString("cardType"))));
}
But I don't know how to make a request call and get a response back. Any one please guide me / provide me sample code ?
Yes, Authorize.net does provide Java SDK and maven dependency from http://mvnrepository.com/artifact/net.authorize/anet-java-sdk.
Authorize.Net SDK includes standard payments, recurring billing, and customer profiles.
I've perform the simple AuthCapture Transaction through following Java code
package com.auth.net;
import java.math.BigDecimal;
import net.authorize.Environment;
import net.authorize.Merchant;
import net.authorize.TransactionType;
import net.authorize.aim.Result;
import net.authorize.aim.Transaction;
import net.authorize.data.creditcard.CreditCard;
public class AIMauthCaptureTransactionDemo {
public static final String apiLoginID= "Your Sandbox API Login ID";
public static final String transactionKey= "Your Sandbox API Transaction Key";
public static void main(String[] args) {
Merchant merchant = Merchant.createMerchant(Environment.SANDBOX, apiLoginID, transactionKey);
// create credit card
CreditCard creditCard = CreditCard.createCreditCard();
creditCard.setCreditCardNumber("4111 1111 1111 1111");
creditCard.setExpirationMonth("12");
creditCard.setExpirationYear("2018");
// create transaction
Transaction authCaptureTransaction = merchant.createAIMTransaction
(TransactionType.AUTH_CAPTURE, new BigDecimal("5.00"));
authCaptureTransaction.setCreditCard(creditCard);
#SuppressWarnings("unchecked")
Result<Transaction> result = (Result<Transaction>)merchant.postTransaction(authCaptureTransaction);
if(result.isApproved()) {
System.out.println("Response Code : "+ result.getReasonResponseCode());
System.out.println("Response Text : " + result.getResponseText());
System.out.println("Transaction Id: " + result.getTarget().getTransactionId());
System.out.println("AuthorizationCode : "+result.getTarget().getAuthorizationCode());
}
else if (result.isDeclined()) {
System.out.println(result.getReasonResponseCode() + " : " + result.getResponseText());
}
else {
System.out.println(result.getReasonResponseCode() + " : " + result.getResponseText());
}
}
}
Here, Please refer first transaction which I performed some time before in below screen shot

Chat bot using google app engine is not replying

heres the code
it basically takes a message and echos it back.
the problem is it is not replying at all :(
in google app engine, my applications page, i get error-"The requested URL /guestbook was not found on this server."
package guestbook;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.http.*;
import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;
#SuppressWarnings("serial")
public class GuestbookServlet extends HttpServlet {
private static final Logger LOG =
Logger.getLogger(GuestbookServlet.class.getName());
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
// Parse incoming message
XMPPService xmpp = XMPPServiceFactory.getXMPPService();
Message msg = xmpp.parseMessage(req);
JID jid = msg.getFromJid();
String body = msg.getBody();
LOG.info(jid.getId() + " --> JEliza: " + body);
// Get a response from Eliza
String response = "echo: " + body;
LOG.info(jid.getId() + " <-- JEliza: " + response);
// Send out response
msg = new MessageBuilder()
.withRecipientJids(jid)
.withBody(response)
.build();
xmpp.sendMessage(msg);
/*Message message = xmpp.parseMessage(req);
JID fromJid = message.getFromJid();
String body = message.getBody();
String respMsg = null;
if (body.equals("/list")) {
respMsg = "Hi";
} else if (body.equals("/help")) {
respMsg = "Welcome to the Guestbook Chatbot!\nThe following commands are supported: \n /list \n /help";
} else {
respMsg = "Command '" + body + "' not supported! \nEnter '/help' for list of commands.";
}
JID tojid = new JID(fromJid.getId());
Message msg = new MessageBuilder().withRecipientJids(tojid).withBody(respMsg).build();
boolean messageSent = false;
xmpp = XMPPServiceFactory.getXMPPService();
if (xmpp.getPresence(tojid).isAvailable()) {
SendResponse status = xmpp.sendMessage(msg);
messageSent = (status.getStatusMap().get(tojid) == SendResponse.Status.SUCCESS);
}*/
}
}
As per the details you have given i think the problem should be with the web.xml file
<servlet><servlet-name>GuestbookServlet</servlet-name><servlet-class>your.package.structure.GuestbookServlet</servlet-class></servlet><servlet-mapping><servlet-name>GuestbookServlet</servlet-name><url-pattern>/_ah/xmpp/message/chat/</url-pattern></servlet-mapping>
try adding this into the web.xml change your.package.structure.GuestbookServlet accordingly for example mine would be com.appengine.capp
JDK settings had to be changed from 1.7 to 1.6.
under window-> preferences -> java -> compiler

Timeout trying to lock table; why is this occurring and how do I fix it?

I've been using JPA in the Play Framework for some time now, and everything was going fine - however, I have now come up against an error which I'm not seeing any obvious solutions to. Just for some context, what I am trying to create is a basic social network.
I have a Post class:
public class Post extends Model {
private String owner;
private long timestamp;
#ElementCollection
private List<String> viewers;
private String content;
public Post(String owner, List<String> viewers, String content) {
this.timestamp = System.currentTimeMillis();
this.owner = owner;
this.viewers = viewers;
this.content = content;
System.out.println("Saving post by " + owner + " with timestamp:" + this.timestamp);
}
(Getters and setters ignored here)
}
I have a User class which adds posts:
public long addPost(String viewers, String content) {
LinkedList<String> viewersList = new LinkedList(Arrays.asList(viewers.split(",")));
Post newPost = new Post(this.name, viewersList, content);
newPost.save();
return newPost.getTimestamp();
}
And I have a StreamManager handling notification of posts and retrieval of posts.
public static void executePost(String content, String viewers) {
System.out.println("Post content: " + content);
String user = session.get("username");
User u = User.connect(user);
if (u == null) {
System.out.println("User is null");
}
/* Add post to local record of posts */
long timestamp = u.addPost(viewers, content);
/* Send notification of post to server */
}
I'm running my application with a thread pool of 3 threads, which means that there is some amount of concurrency in the system. While the system is waiting for a response from the server after notification (end of executePost), another thread is trying to access the newly created Post using this code:
public static void retrievePost(String owner, String timestamp) {
byte[] postAndKey = new byte[1024];
byte[] post = null;
byte[] encryptedKey = null;
User u = User.connect(owner);
Post.findAll();
//List<Post> posts = (Post.find("byOwner", owner).fetch());
System.out.println("Looking for post by " + owner + " at timestamp: " + timestamp);
//System.out.println("Looking through: " + posts.size() + " posts");
At Post.findAll() the framework throws a nasty error, telling me that there is a Timeout trying to lock table "POST". I suspect that this is because one thread is still in executePost() while another is trying to access the post in retrievePost(). Considering that the Post has been 'saved', however, shouldn't the lock have been released? Is this really the reason, and is there any way around the error?
Thanks.
Just for reference, if anyone else is having a similar issue: I fixed it by explicitly sleeping the calling thread using await(), which meant that it gave up all its locks, allowing the thread in retrievePost() acess to the table.

Categories