Twilio TaskRouter Worker Conference - java

I have a Twilio phone number which I am using for softphone and that phone I have configured for TaskRouter. So whenever Somebody call to twilio number that call route to available Worker, this is working fine but my question is how Worker can call other non twilio number in live call.
I am reading a docs on https://www.twilio.com/docs/api/taskrouter/handling-assignment-callbacks#redirecting-call where it mentions that
1. Dial the worker in a Conference name by the ReservationSid. This can be done on assignment call back.
2. Utilize Redirect Assignment Instruction to transfer the customer from a Queue to a Conference named by the ReservationSid.
So how can I dial a Worker in conference and how customer redirect to that conference so Agent can dial a non twilio number in live call and redirect that call in conference
means it is like three way communication,
Customer-->Twilio Number--->Worker--->Non Twilio number??

in PHP I have manage like this
first set one URL assignment in taskrouter
HERE : TaskRouter->Settings->Event Callbacks
like www.site.com/test/event_status_callback.php
You can use twilio conferece task router :-
https://www.twilio.com/docs/api/taskrouter/reservations
Conference Instruction like this
// Get the PHP helper library from twilio.com/docs/php/install
require_once '/path/to/vendor/autoload.php'; // Loads the library
use Twilio\Rest\Client;
// Your Account Sid and Auth Token from twilio.com/user/account
$accountSid = "AC1afdf65d5c4e434dc58792456bda940f";
$authToken = "your_auth_token";
$workspaceSid = "WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$taskSid = "WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$reservationSid = "WRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$client = new Client($accountSid, $authToken);
// Update a Reservation with a Conference instruction
$reservation = $client->taskrouter
->workspaces($workspaceSid)
->tasks($taskSid)
->reservations($reservationSid)
->fetch();
$reservation->update(
array(
'instruction' => 'conference',
'dequeueFrom' => '+18001231234'
)
);
1) call come on twilio number and goes to taskrouter
<Response>
<Enqueue workflowSid="WWXXXXXXXXXXXXXXXXXXXXXXXX">
<Task>{"selected_language": "<?= $language ?>"}</Task>
</Enqueue>
</Response>
2)now call goes to perticuler language wise and dail to avelable workers and here you can redirect your call to other Non Twilio number get call sid
also you can Use Db for manage worker side and call sid
In this event_status_callback.php page you get call_sid
$call = $client
->calls($call_sidss)
->update(
array(
"url" => $url . "test/callredirectonsupport.php",
"method" => "POST"
)
);
echo $call->to;
3) callredirectonsupport.php
now you call redirect to callredirectonsupport.php
here you can write youe dial code

Related

Cloning PaymentMethods from the Platform to Connected Accounts

I'm using Stripe with Standard accounts.
I'm saving Customers and PaymentMethods on the Platform, so, in client side the customer choose a Payment Method and it is sent to the server. So, in the server side I clone the PaymentMethod to the Connected Account that will receive the payment. My server side code looks like this
RequestOptions requestOptions = RequestOptions.builder()
.setStripeAccount("{{CONNECTED_STRIPE_ACCOUNT_ID}}")
.build();
PaymentMethodCreateParams paramsClone = PaymentMethodCreateParams.builder()
.setCustomer("cus_1")//Id of the customer in the platform
.setPaymentMethod("payment_method_id")//One of the payment methods of the cus_1
.build();
PaymentMethod newPaymentMethod = PaymentMethod.create(paramsClone, requestOptions);
At this point I assume that this new newPaymentMethod is in the connected account, right?
Well, then I create a PaymentIntent
PaymentIntentCreateParams params = PaymentIntentCreateParams.builder()
.setAmount(100)
.setPaymentMethod(newPaymentMethod.getId())
.setCurrency("usd")
.setApplicationFeeAmount(10)
.build();
PaymentIntent paymentIntent = PaymentIntent.create(params, requestOptions);
Everything seems good at this point. The Payment Intent is returning the stripe client secret like 'pi_1Ipfl3Bf0KWukpZWQdbAzoz1_secret_RAKsPMLpyhkDJ7q8N1VvSmaoR' and the status is 'requires_confirmation'. So, when I try to confirm in the client side it throws an error saying: No such payment_intent: 'pi_1Ipfl3Bf0KWukpZWQdbAzoz1'.
I think that it is something related to switching things between my platform and the connected account, but I can not figure out what is the exact problem. I'm following this https://stripe.com/docs/connect/cloning-customers-across-accounts and this https://stripe.com/docs/payments/payment-methods/connect#cloning-payment-methods but still I can not figure out how to get it work.
Can someone explain this? Regards!
Your server-side steps are correct, you are creating a PaymentIntent on the Connect account.
What you are missing client-side is, since the PaymentIntent lives on the Connect account, your Stripe.js/mobile SDK also needs to be authenticated as the Connect account.
You basically need to specify this on your client-side:
var stripe = Stripe('{{PLATFORM_PUBLISHABLE_KEY}}', {
stripeAccount: '{{CONNECTED_STRIPE_ACCOUNT_ID}}',
});
https://stripe.com/docs/connect/authentication#adding-the-connected-account-id-to-a-client-side-application
Since I presume you already have Stripe.js authenticated as your Platform publishable key (in order to create the first PaymentMethod on the Platform, to clone), you would have to create a second instance of Stripe.js on your client, one authenticated as the Connect account.
Well, at the end I solved it in the client side. I just had to tell stripe to confirm on behalf of the Connected Account. Using tipsi-stripe in react native is something like this:
stripe.setStripeAccount('acct_XYZ');//Set the connected account
stripe.confirmPaymentIntent({ clientSecret: stripeClientSecret })
.then((cofirmResponse) => {
stripe.setStripeAccount(null);//Reset the connected account
...
}).catch((e) => {
stripe.setStripeAccount(null);//Reset the connected account
...
});

Online Multipler Games in Java

In Java, is there a way to make a client/server system for a game without having to enter ips (like in Minecraft).
But instead, have it automatically connect the user to a game when he requests to join one (like in Fortnite, or surviv.io).
The only method I current know for client/server is having to give each user a server ip to connect to (like in Minecraft), so I was wondering if I could do it this way.
Thanks in advance.
IMHO, I think in all ".io" games, they are only hiding the registration processing. In my case, the previous game I made had a feature calls "Quick Play".
When a player uses that playing method and first time joins the game, I get his device's ID (for example in Android) then use it as a unique ID for that player in-game (I'm not sure about iOS but you can get that unique value in Android).
You can see the example below:
_on(TEvent.CONNECTION_SUCCESS, args -> {
var connection = Connection.convert(args[0]);
var message = TObject.convert(args[1]);
info("CONNECTION", connection.getAddress());
// Allow the connection login into server (become a player)
String username = message.getString("u");
// Should confirm that credentials by data from database or other services, here
// is only for testing
_playerApi.login(new PlayerLogin(username), connection);
return null;
});
Now when a new user login, he will send his device's ID and I can treat him a new player and make that ID as his name (or making a randomized name for him)
You can see more detail in the link below:
Login Example

Twilio call a user, play audio and receive callback

I need some help in achieving functionality using twilio API.
I want to call user and play some pre-recorded audio file and receive callback status/event.
Here is what I have achieved.
Twilio.init(TWILIO_SID, TWILIO_AUTH_TOKEN);
Call call = Call.creator(new PhoneNumber(callDetailModel.getToNumber()),
new PhoneNumber(FROM_TWILIO_NUMBER),
new URI(API_URL + "/call/twilio/voice/demo-voice")).create();
Now in "/call/twilio/voice/demo-voice" I am generating TwiML.
Play play = new Play.Builder(
"demo-play.wav")
.loop(1).build();
Number number = new Number.Builder(request.getParameter("Caller"))
.statusCallback(API_URL + "/call/twilio/events-demo")
.statusCallbackMethod(Method.POST).statusCallbackEvents(Arrays
.asList(Event.INITIATED, Event.RINGING, Event.ANSWERED, Event.COMPLETED)).build();
Dial dial = new Dial.Builder()
.timeLimit(60)
.callerId(request.getParameter("Called"))
.record(Dial.Record.DO_NOT_RECORD)
.number(number).build();
VoiceResponse twiml = new VoiceResponse.Builder().dial(dial).play(play).build();
return (twiml.toXml());
And now in event callback we are checking if receiver has received call or not, is it completed or not etc.
Now, the problem is when user receive a call auto voice mail of Twilio is getting played and after that my demo-play.wav get played. We want to remove that twilio voice mail and want to play only demo-play.wav which we have passed through TwiML.
UPDATE:
The audio getting played is here.
https://vocaroo.com/i/s0KNEhHxUKX5
Also the twiml which is generated is something like this
<Response>
<Dial timeLimit="7200" callerId="+1xxxxx" record="record-from-answer-dual">
<Number statusCallbackEvent="initiated ringing answered completed" statusCallback="http://38c5cb01.ngrok.io/call/twilio/events-demo" statusCallbackMethod="POST">+1zzzzzzzz</Number>
</Dial>
<Play loop="1">https://aws.xxx.H1OAOec30bbc5-bc3a-4251-a27c-2e4e41b386061521208641292FOIZ1.wav</Play>
</Response>
Am I missing something? Do I need to pass the Play in Dial verb? If then how?

Sending notifications One to One (Firebase) [duplicate]

I am thinking about keeping all registration ids(push token) in DB and sending notifications to user from iPhone. I tried something like this but did not get any notification.
func sendPNMessage() {
FIRMessaging.messaging().sendMessage(
["body": "hey"],
to: TOKEN_ID,
withMessageID: "1",
timeToLive: 108)
}
What I am doing wrong or maybe it is impossible at all?
Currently it's not possible to send messages from the application itself.
You can send messages from the Firebase Web Console, or from a custom server using the server-side APIs.
What you might want to do is to contact a server (like via http call) and that server will send the message to the user.
This way ensure that the API-KEY of the server is protected.
PS: the sendMessage(..) api is called upstream feature, and can be used to send messages from your app to your server, if you server has an XMPP connection with the FCM server.
Yes you can send push notification through Firebase.Please make sure do NOT include the server-key into your client. There are ways "for not so great people" to find it and do stuff... The Proper way to achieve that is for your client to instruct your app-server to send the notification.
You have to send a HTTP-Post to the Google-API-Endpoint.
You need the following headers:
Content-Type: application/json
Authorization: key={your_server_key}
You can obtain your server key within in the Firebase-Project.
HTTP-Post-Content: Sample
{
"notification": {
"title": "Notification Title",
"text": "The Text of the notification."
},
"project_id": "<your firebase-project-id",
"to":"the specific client-device-id"
}
Google Cloud Functions make it now possible send push notifications from device-to-device without an app server.
From the Google Cloud Functions documentation:
Developers can use Cloud Functions to keep users engaged and up to
date with relevant information about an app. Consider, for example, an
app that allows users to follow one another's activities in the app.
In such an app, a function triggered by Realtime Database writes to
store new followers could create Firebase Cloud Messaging (FCM)
notifications to let the appropriate users know that they have gained
new followers.
Example:
The function triggers on writes to the Realtime Database path where followers are stored.
The function composes a message to send via FCM.
FCM sends the notification message to the user's device.
Here is a demo project for sending device-to-device push notifications with Firebase and Google Cloud Functions.
Diego's answer is very accurate but there's also cloud functions from firebase it's very convenient to send notifications in every change in the db. For example let's say you're building chat application and sending notification in every new follower change.
This function sample is very good example.
For more information about cloud functions you can check official docs.
I have an app that has a "send feedback to developer" section. I also have a User collection in my firestore database. When a user logs into the app, I have that Users data update their FCM token with the following code in my SceneDelegate.swift:
import Firebase
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
authListener = Auth.auth().addStateDidChangeListener({ (auth, user) in
Auth.auth().removeStateDidChangeListener(self.authListener!)
if user != nil {
DispatchQueue.main.async {
let docRef = Firestore.firestore().collection("User").document((user?.email)!)
docRef.getDocument { (snapshot, error) in
guard let snapshot = snapshot else {return}
Messaging.messaging().token { token, error in
if let error = error {
print("Error fetching FCM registration token: \(error)")
} else if let token = token {
docRef.updateData(["FCMtoken":token])
print("FCM registration token: \(token)")
}
}
}
}
}
})
guard let _ = (scene as? UIWindowScene) else { return }
}
then in my feedback view controller i have this code to send my specific device (but you can look up/fetch which specific device you want in your database where the FCMtoken is stored where i have INSERT-DEVICE-TOKEN-HERE). The url to send to is "https://fcm.googleapis.com/fcm/send" and you can find YOUR-APP-FCM-KEY by going to your project settings in firebase, going to cloud messaging tab and its the server key.
func sendMePushNotification() {
let token = "INSERT-DEVICE-TOKEN-HERE"
if let url = URL(string: "https://fcm.googleapis.com/fcm/send") {
var request = URLRequest(url: url)
request.allHTTPHeaderFields = ["Content-Type":"application/json", "Authorization":"key=YOUR-APP-FCM-KEY"]
request.httpMethod = "POST"
request.httpBody = "{\"to\":\"\(token)\",\"notification\":{\"title\":\"Feedback Sent!\",\"body\":\"\(self.feedbackBox.text!)\",\"sound\":\"default\",\"badge\":\"1\"},\"data\": {\"customDataKey\": \"customDataValue\"}}".data(using: .utf8)
URLSession.shared.dataTask(with: request) { (data, urlresponse, error) in
if error != nil {
print("error")
} else {
print("Successfully sent!.....")
}
}.resume()
}
}
Use onesignal,you can send device to notifications or device to segments ,it can work with firebase in this way
Use onesignal functions to create a specific id,save it in a firebase database ,then when the id can be put in another function that is used to send a notification
Notes: 1-i am using it in my apps with firebase works perfectly
2-i can submit that code,just someone comments so i can find this answer

limit users in group chat of whatsapp by an android app

i m trying to developing an app where i want to monitor whatsapp group chat and limit users e.g max 5 users can join if 6th coming, ignore or remove most inactive and add new user to chat
i have no idea how can i do that ? it requires root acess or not?
is there any api available to do this ?
You can use Yowsup which is a Python library. You will need to setup a separate WhatsApp account that logs into the WhatsApp servers using this library. This account will need to be the "owner" of the groups and will need to manage adding and removing users from the chat. The code will also need to monitor the chat traffic to figure out who is talking. The code you develop does not need to run all the time.
You will need to register listeners for a number of WhatsApp events. Some of your init code will look like this:
class WhatsappClient:
def __init__(self):
atexit.register(self.exitfunction)
connectionManager = YowsupConnectionManager()
connectionManager.setAutoPong(True)
self.signalsInterface = connectionManager.getSignalsInterface()
self.methodsInterface = connectionManager.getMethodsInterface()
self.signalsInterface.registerListener("auth_success", self.onAuthSuccess)
self.signalsInterface.registerListener("auth_fail", self.onAuthFailed)
self.signalsInterface.registerListener("message_received", self.onMessageReceived)
self.signalsInterface.registerListener("receipt_messageSent", self.onMessageSent)
self.signalsInterface.registerListener("disconnected", self.onDisconnected)
self.signalsInterface.registerListener("group_messageReceived", self.onGroup_messageReceived)
self.signalsInterface.registerListener("notification_groupParticipantAdded", self.onNotification_groupParticipantAdded)
self.signalsInterface.registerListener("notification_groupParticipantRemoved", self.onNotification_groupParticipantRemoved)
self.signalsInterface.registerListener("group_gotInfo", self.onGroup_gotInfo)
self.signalsInterface.registerListener("group_gotParticipants", self.onGroup_gotParticipants)
self.signalsInterface.registerListener("group_subjectReceived", self.onGroup_subjectReceived)
self.signalsInterface.registerListener("notification_groupPictureUpdated", self.onNotification_groupPictureUpdated)
self.signalsInterface.registerListener("group_setSubjectSuccess", self.onGroup_setSubjectSuccess)
self.signalsInterface.registerListener("group_createSuccess", self.onGroup_createSuccess)
self.signalsInterface.registerListener("group_createFail", self.onGroup_createFail)
self.signalsInterface.registerListener("group_endSuccess", self.onGroup_endSuccess)
self.signalsInterface.registerListener("group_addParticipantsSuccess", self.onGroup_addParticipantsSuccess)
self.signalsInterface.registerListener("group_removeParticipantsSuccess", self.onGroup_removeParticipantsSuccess)
some examples of method implementations above:
def onGroup_messageReceived(self, messageId, gjid, author, content, timestamp, receiptRequested, pushName):
formattedDate = datetime.datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
log("Group message %s - %s (%s):%s"%(gjid, pushName, author, content))
if receiptRequested:
self.methodsInterface.call("message_ack", (gjid, messageId))
# do something with the message....
def onGroup_addParticipantsSuccess(self, gjid, jid):
log ("Participant added success g=%s j=%s " % (gjid, jid))
def onGroup_removeParticipantsSuccess(self, gjid, jid):
log ("Participant removed success g=%s j=%s " % (gjid, jid))

Categories

Resources