Nexmo - Select from number based on location of destination to number - twilio

In Twilio there's an concept of phone # pools. A txt message can be sent using this Pools Id value and Twilio will select the best FROM number to send with. I've looked around Nexmos API's and I don't see similar capabilities, is this possible?
The only other option I've found is something call applications but I can't send messages without manually selecting the from numbers instead of automating it via application Id, I assume that would be one of the 'use cases'
There's a document from Nexmo https://help.nexmo.com/hc/en-us/articles/217571017-What-is-a-Sender-ID- that has the following
Random Numeric - Nexmo will apply a random number to comply with local regulations (usually taken from a pool of numbers we have access to from the relevant destination market).
Problem is how do I configure Random Numeric? It doesn't really explain and I might have missed those docs. Any suggestion help.

Random numeric is not something you set, is something the Nexmo API does in order to ensure delivery in certain parts of the world, in order to conform with local regulations.
There is no Pools concept in Nexmo at the moment, so if you want the same functionality you'd have to build it in your code. Rent a bunch of Nexmo phone numbers, and then apply a random algorithm of choice in your code before sending each message to select your phone number. Something like:
let myNexmoNumbers = [447481234567, 447481234568, 447481234569]
nexmo.message.sendSms(myNexmoNumbers[Math.floor(Math.random() * myNexmoNumbers.length)], TO_NUMBER, TEXT_MESAGE, (err, responseData) => {
if (err) {
console.log(err);
} else {
if(responseData.messages[0]['status'] === "0") {
console.log("Message sent successfully.");
} else {
console.log(`Message failed with error: ${responseData.messages[0]['error-text']}`);
}
}
})

Related

Twilio/Spoke: Does messaging service automatically share load between numbers in the service?

The Spoke app calls my Twilio Messaging Service with these parameters:
const messageParams = Object.assign(
{
to: message.contact_number,
body: message.text,
statusCallback: process.env.TWILIO_STATUS_CALLBACK_URL
},
userNumber ? { from: userNumber } : {},
messagingServiceSid ? { messagingServiceSid } : {},
twilioValidityPeriod ? { validityPeriod: twilioValidityPeriod } : {},
parseMessageText(message)
);
There is no indication as to which number in the Messaging Service to use. The Messaging Service has two numbers added to it. I tried a sample run and it sent all 6 messages to the first number added to the Messaging Service. Will it ever use the second? How can I change the policy about which number to use, apart from area code matching?
Disable sticky sender.
The Sticky Sender feature ensures the same From phone number is selected every time your application sends a message to a particular end-user. This allows your application to consistently send messages to your user from a single, recognizable phone number.

Twilio REST API V2 - How to get unread message count for a user?

I have found many links regarding unread message count but most of them are pointing at older release code.
From Current REST API v2, found this code.
.twilioClient
.chat
.services((process.env.TWILIO_CHAT_SERVICE_SID || config.TWILIO_CHAT_SERVICE_SID))
.users(req.params.userSID)
.userChannels
.list({}, (error, result) => {
for (var item in result) {
let count = item.unread_messages_count == null ? 0 : item.unread_messages_count;
totalUnreadMessages += count;
}
But the code shows unread_messages_count as null always and I searched about **consumption horizon ** from here.
https://www.twilio.com/docs/chat/consumption-horizon
But dont know how to set consumption horizon or someother thing to make this work through API.
Twilio developer evangelist here.
As the documentation says:
Note: Chat does not automatically set the Consumption Horizon. If you do not explicitly set this within your application, no Consumption Horizon will exist for a User within the Channel. Without a Consumption Horizon, your user's Consumption Horizon (read status) will not synchronize correctly across clients. If a user does not have a Consumption Horizon set on a channel, getting unconsumed messages will always return 0. If a member of a Channel has no consumption status, their last consumed index and timestamp will be null or 0 depending on the platform.
So, in order for there to be a consumption horizon, you need to set it via the SDK. In JavaScript, that looks a bit like:
activeChannel.updateLastConsumedMessageIndex(someMessageIndex)
.then(function () {
// consumption horizon updated
});
where activeChannel is a channel object that your user has joined and someMessageIndex is the index of the message that your user last read.
The consumption horizon for the channel must be set via the SDK for it to show in the REST API.

How to access data field in Dialogflow?

As the Dialogflow documentations states, the data field represents
Additional data required for performing the action on the client side.
The data is sent to the client in the original form and is not
processed by Dialogflow.
How should one access it in the iOS framework?
request?.setMappedCompletionBlockSuccess({ (request, response) in
...
}
I couldn't find it in the response object and can't find any documentation for iOS.
Thanks.
Your question is a bit vague (can you edit and narrow it down?), but i think you got it the other way round, what that snippet of documentation that you pasted means is that you are supposed to send that payload to DialogFlow and it will forward it to a connected Client (e.g Messenger, Slack etc) un-touched. It simply means that DialogFlow assumes that you know what you are doing.
Here is a sample Fulfilment response to DialogFlow in JS
module.exports.sendGenericMessageWithText = function(message) {
return {
data: {
facebook: [
{
text: message
]
}
}
}

Sending different body via Amazon SES Api

I am using Amazon-SES api for sending email to clients. It's very successfull but i have to send different body for each client. When i start to send mails about 200.000 clients, how the code below look like ? Is it loop 200.000 times or can i prepare an object and send one time (like n:n system, now it's 1:n).
var clientList=new List<String>(); //200.000 mail adress
foreach(var to in clientList)
{
SendEmailRequest email = new SendEmailRequest();
email.Message = new Message();
email.Message.Body = new Body();
email.Message.Body.Html = new Content(bodyhtml);
email.Message.Subject = new Content(subject);
email.WithDestination(new Destination() { ToAddresses = new List<String>() { to } })
.WithSource("mysite#mysite.com")
.WithReturnPath("mysite#mysite.com");
SendEmailResponse resp = client.SendEmail(email); //that's 1:n
}
SendEmailResponse resp = client.SendEmail(emailList); //that's n:n but it's a wrong usage
How can i send n:n algorithm in Amazon SES ?
Application is Asp.net MVC 3. So can i use Asynchronous Controller ? Is it good idea ?
Assuming you have production access for Amazon SES already (see What should I do after I'm finished testing and evaluating Amazon SES?) and a sufficiently increased Sending Quota to send 200.000 mails/day in the first place (see How Amazon SES Sets Sending Limits), the respective limits are documented for the SendEmail action:
The total size of the message cannot exceed 10 MB.
Amazon SES has a limit on the total number of recipients per message:
The combined number of To:, CC: and BCC: email addresses cannot exceed
50. If you need to send an email message to a larger audience, you can divide your recipient list into groups of 50 or fewer, and then call
Amazon SES repeatedly to send the message to each group. [emphasis mine]
Please note: It is strictly recommended to use Bcc: only for this kind of mass mailing operation, else your users will see their mail addresses exposed to each other and I can guarantee they won't be amused at all!
So you could prepare mails with 50 Bcc: recipients at a time, dropping the outbound mail amount for your use case to about 4.000, which is a considerable improvement already. However, please note a respective AWS Team response to Increase sending limit, and question on FAQ:
if you're sending to multiple ISPs [...], I would recommend
sending to one address at a time since certain ISPs are sensitive
about multiple addresses on the BCC: line in large quantities. [emphasis mine]
Whether or not this warning applies depends on your use case as usual (e.g. you might be able to shard the mails by ISP etc.).
Doing it asynchronously is fine and likely useful, but you need to ensure to stay within your Maximum Send Rate (mails/second) limit as well. These limits are visible in the SES tab of the AWS Management Console, but available via the API as well of course (see Monitoring Your Sending Limits for details).

Communicating between (chat) server and client

just to clarify certain questions.
Let's say I'm making a chat application. Most of the online tutorials are basic server-client programs that send the chat message directly as strings.
So what if there is someone that came online, or offline. How would the client notify the server of such changes? What I came up with is to use flags {online}User, {offline}user, {privatechat}blabla.
What if someone knew how your code and that would allow them to sabotage by keep sending {online}blabla.
This would work, but has some flaws that I could think of as well. What would be the correct or better way to do this?
Can someone point me in the right direction? Thanks.
Or another example, in games. To tell the unit to move right, does it send a string back to the server {unit}{move right}? Something along those lines.
I kinda got the logic on how to make the chat server. If I just prefix a "{chat}" to the textbox. As long as I read this command "{chat}" I'll just ignore whichever commands which comes along.
How about in an RTS (not that I'm gonna make one, just curious), you mean there's literally 50 over strings telling how units move, attack, take damage, actions etc? Will all these commands be done on one thread? or multi-threaded?
Well you have to implement session-handling and send sessionToken with your order to move a unit in game. So server will be able to check whether pointed user have rights to order the pointed unit etc. Same things with chats.
In my chat, every client sends some PING message to server every two minutes. So if 5 minutes passed and no PING is received, server counts the user as [offline].
If you are afraid of cheating users who reverse engineer your client and can make serious troubles to the system with cheats, you have to do two things:
make server to check if given
user order is valid
implement bot-detection. check if
user makes some actions with some
constant time interval or if user
uses some limited amount of words in
chat etc.
I hope this post at least gives you some point.
The example of server logic is following:
[WebMethod]
string LoginUser(string login, string pwd)
{
if( dal.IsCorrectUser(login,pwd) )
{
string token = dal.MakeSession(login);
return string;
}
return "-1";
}
[WebMethod]
bool UserOrder(string token, string order)
{
if( !dal.SessionExist(token) )
{
return false;
}
int userId = dal.GetUserBySession(token);
if(! dal.ValidOrderForUser(userId,order) )
{
dal.RegisterWrongOrder(userid,order); // For cheaters-detecting purposes
return false;
}
return dal.ExecuteUserOrder(userId, order);
}
In fact you can send string or any serializable objects as an user-order.
[Serializable]
struct UserOrder
{
int unitId;
int Order;
}
All samples are for c#. Just to demonstrate logic.

Resources