Is it possible to send a single message to multiple numbers at a time using Twilio? - api

I'm developing an app that allows users to add people, info, and Name/phone, or select multiple numbers from their iPhone contact list to send SMS messages to the selected numbers. the problem is Twillio API needs to be call every time per number. Is their any way to call the API once for multiple numbers?
Is it possible to send message to multiple number at a time?
Is it possible to send multiple messages?
Thanks in advance

It's not possible, you need to iterate through the list and make one request per message (which is probably better than batching it and dealing with the potential of multiple errors / resends).

Each new SMS message from Twilio must be sent with a separate REST API request. To initiate messages to a list of recipients, you must make a request for each number to which you would like to send a message. The best way to do this is to build an array of the recipients and iterate through each phone number.
const numbersToMessage = ["+15558675310", "+14158141829", "+15017122661"]
numbersToMessage.forEach(async number => {
const message = await client.messages.create({
body: 'message body',
from: '+16468635472',
to: number
});
console.log(message.status)
});

Yes this is possible. Infact i'm trying to do the same thing at the moment(which is why i'm here) and Twilio has some advanced stuff that lets us achieve this.
Assuming you have a twilio ssid, twilio auth token and a twilio phone number, the next thing you have to do is create a "Twilio Messaging Service" from the dashboard. You can use the ssid of the created messaging service and use or if you want to send a message to like 10k numbers in one go, you create a "Twilio Notify Service" from the dashboard which takes the previously created messaging service as part of its configuration. Once this is done you can call the twilio.notifications.create() and pass bindings({ binding_type: 'sms', address: number }) for each phone number to it.
Complete explanation found in this twilio blog right here with perfectly working code.
https://www.twilio.com/blog/2017/12/send-bulk-sms-twilio-node-js.html

Yes it is possible to send message to multiple user's from your Twilio Number.
You can try this for your node.js file:
var arr = ["+1xxxxxxxxxx","+1xxxxxxxxx"];
arr.forEach(function(value){console.log(value);
client.messages.create({
to:value,
from: "+19253504188",
body: msg,
}, function(err,message){
console.log(err);
});
});

Yes it is possible. You have to provide the numbers as a list and iterate API call.
For example send a message to two numbers.
numbers = ['+1234562525','+1552645232']
for number in numbers:
proxy_client = TwilioHttpClient()
proxy_client.session.proxies = {'https': os.environ['https_proxy']}
client = Client(account_sid, auth_token, http_client=proxy_client)
message = client.messages \
.create(
body="Your message",
from_='Your Twilio number',
to=number
)

Related

How to receive encrypted payment token data of Google Pay

I'm trying to use Google Pay on my website. Once I confirm the payment Google returns this data structure:
But I need something like this:
{
"signature":"MEYCIQDTe92wpG6OUgxJ/8Qnr36XzSgjGGCM7R3LwxjgwPYMTAIhAJDrjHG9wEm1BxVM6MMMB+jGTGpi3VScEMVbHIUsObFi",
"protocolVersion":"ECv2",
"signedMessage":"{\"encryptedMessage\":\"FY8w/U3IbdsZQovX8ufNGFDOePgc/genRiMjHyvuIBqLY4a6uPz7wI0ra31K6YbFJlAnCjFhTwSvDxAYXw6hlmI8sESO5eM1eZlzfP3+NoKV80OXKvOM/xI/qOQEqpEQEVXx6Bw2EpMMFW8yBaA8XPUNee3EJlUk+/f8lRdRcNmI65QKPLAzUnySo75HzBkSc5It/8/oXdYwR93/K6HRKGZuD+bIaxy3SUvC9ehQqhBoP+A34yQX1knfJ1qjBMhhVVcPZHi+Bg6LXA4ms/lfDdim6D1Epr6XQhc2h4RZ/dT+6Enn81s/8ym+jMMs8kqsW9ib8vkdTARv9AbUu7zeGPrKTCAxwc1n6joRR72dSnNCI9j9sxd9tkuC9wuRyDmjbWT+hRZgLc1v/xzzNImo3NxdKdaPzKBE3t9XQZY5fp3lZELaoXAuxAZYtZ7bX64Mz9c28wD8EM+krvfbmGMiBjIt8EfeH48/SjeaUKfDu+yQnjPJAKbDZPhKJ1jqlY/ChP0Om7spQacT86QUVK/DwfzukwvwwRJkWydNEac5fgfS2T6ToZ+PW4VHbxkDnY/h+B0uwdlNQIL2a3Ar5Q\\u003d\\u003d\",\"ephemeralPublicKey\":\"BGkK4bSvob+e7ZgaNV/4vSJYYa10OJzd3aUk9yPEP6iNBRcfHiD/NTvhKjN4P24l0tEzH3L8TrySl6AczPJpCkw\\u003d\",\"tag\":\"xGEhEfJESIyBSfq2fExWiZxNWelnm3m4i8P7cgsarqg\\u003d\"}"
}
Could you please advice me what should I do to get the second data structure. Thank you!
The response that you are after is found under paymentMethodData.tokenizationData.token. However, the contents of this field are determined by the request parameters that you pass to loadPaymentData. Are you able to include the request that was used to generate the above response?
FYI, the following JSFiddle will produce a result similar to what you are after:
const tokenizationSpecification = {
  type: 'DIRECT',
  parameters: {
    'protocolVersion': 'ECv2',
'publicKey': 'BMzk6xvwPgU8vjB...7KRu4tuRmhm6nv8=',
  }
};
/*
{
"signature":"MEUCI...TougPg",
"protocolVersion":"ECv2",
"signedMessage": "{\"encryptedMessage\":\"VhQuaN...5o0Ny6Y\\u003d\"}"
}
*/
I achieved this by using a DIRECT tokenization specification which is discouraged:
Key Point: The Direct integration allows merchants to decrypt the Google Pay response on their servers. To qualify, you must be Payments Card Industry (PCI) Data Security Standard (DSS) Level 1 compliant. Your servers also need to have the required infrastructure to securely handle users' payment credentials.
Third parties that supply gateway or processing services on behalf of actual merchants aren't eligible to use the Direct integration. For questions about your integration as a payment service provider, contact us.
If you don't meet the necessary prerequisites, we recommend that you use a supported gateway to receive a payment token.
Not sure if this is still an open issue. But here are my 2 cents and might be the answer to your solution.
Please note: This is an answer if you are using WorldPay/Vantiv only.
From your first response above with the token, I believe you are using gateway as "vantiv"
"gateway": "vantiv"
"vantiv:merchantPayPageId": "YOUR_PAY_PAGE_ID"
"vantiv:merchantOrderId": "YOUR_ORDER_ID"
"vantiv:merchantTransactionId": "YOUR_TRANSACTION_ID"
"vantiv:merchantReportGroup": "*web"
If you want to get the second response with signature and signedMessage then all you have to do is change the gateway to "worldpay" and you should get the same response:
"gateway": "worldpay"
"gatewayMerchantId": "YOUR_WORLDPAY_MERCHANT_ID"
You can find the request here

How to create "Round Robin Call Forwarding Function" in Twilio Stack

I have researched high and low through multiple websites and have not found a single fully documented solution for round-robin call forwarding with-in the Twilio stack; let alone within Twilio Studio. The last time this question was asked in detail was in 2013 so your help is greatly appreciated. I am looking to find a solution to the following to educate myself and others:
[Round Robin Scenario]
Mentioned by Phil Krnjeu on Aug 1 '13 at 23:04, "I'm trying to create a website that has a phone number on it (say, a phone number for a school). When you call that number, it has different secretary offices (A,B,C, D). I want to create something where the main number is called, and then it goes and calls phone number A the first time, the second time someone calls the main number, number B is called, C, then D. Once D is called (which would be the 4th call), the 5th call goes back to A."
The response to the above question was to use an IVR Screening & Recording application which requires the caller to pick an agent which is not a true Round Robin solution. The solution I am looking for and many others require the system to know which agent is in a group and which agent is next to receive a call.
[Key Features Needed]
Ability to add forwarding numbers as identified above A, B, C, D as a group or IVR extensions such as 1 = Management, 2 = Sales and etc...
Set a subsequent calling rule that notates in a DB of some sort. Caller A through D, for example, equals 1 unsuccessful. When caller A has been forwarded a call it now equals 0 successful then the script stops and allows the call to be answered by the user or its voicemail. Then the next call comes in and is forwarded to user B and assigned a 0 successful value, then the script stops.
After the caller finishes the call or finishes leaving a voicemail the script needs to end the call.
[Final Destination]
The round-robin should finalize its call with the forwarded phone numbers voicemail.
[Known Issues]
Forwarding a call to multiple numbers not stopping when someone answers
[Options]
Once this question is posted I am sure someone will ask in the near future what if I wanted the call to be forwarded to a Twilio voicemail instead of using the forwarded phone number's voicemail which could be let's say a cell phone. I do not necessarily need this feature, however, making an additional comment would be very helpful to the community. Thank you for your time.
I have limited knowledge of programming besides having the ability to review articles posted by other users. One article I researched in detail that did not work for me was, "IVR: Screening & Recording with PHP and Laravel."
The solution I am looking for first would be to make this code through the new Twilio Studio interface if that is not possible then any other solution would be helpful to all.
Sam here from the Twilio Support Team. You can build what you've described using Twilio's Runtime suite, Studio, and Functions.
I wrote a blog post with detailed instructions and screenshots here, and I've included a summarized version below as well.
CREATE YOUR VARIABLE
First, you need to create a serverless Variable which will be used as the round robin counter. The variable must be inside an Environment, which is inside a Service. This is the only part of the application where you will need your own laptop. You can see how to create these with any of the SDKs or using curl in the docs.
Create a Service
Create an Environment
Create a Variable
Be sure to copy the SIDs of your Service, Environment, and Variable since you will need that for your function.
For convenience, this is how you create the Variable in NodeJS.
const accountSid = 'your_account_sid';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);
client.serverless.services('ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.environments('ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.variables
.create({key: 'key', value: 'value'})
.then(variable => console.log(variable.sid));
CREATE YOUR FUNCTION
Create the following Environment Variables here in the console and save set them equal to their respective SID that you saved earlier.
RR_SERVICE_SID
RR_ENV_SID
RR_VAR_SID_CTR
Next, make sure you check the Enable ACCOUNT_SID and AUTH_TOKEN checkbox above the Environment Variables section under Credentials.
Be sure your Twilio Client version in the Dependencies section is set to the latest, so we can be sure it includes the Serverless resources. At the time of writing (March 2020), the default Client version does not include them, so we upgraded to 3.41.1, which was the latest.
Go here in the console and create a blank Function.
Copy and paste the following code and replace the numbers with the ones you would like to include in your Round Robin (make sure the environment variables you just created match what's in the code).
exports.handler = function(context, event, callback) {
// Number List
let numbers = [
"+18652142345", //Sam
"+18651092837", //Tina
"+19193271892", //Matt
// Copy and paste line above to add another number.
];
// Initialize Twilio Client
let client = context.getTwilioClient();
// Fetch Round Robin Ctr
client.serverless.services(context.RR_SERVICE_SID)
.environments(context.RR_ENV_SID)
.variables(context.RR_VAR_SID_CTR)
.fetch()
.then(variable => {
// Use counter value to determine number to call
let number = numbers[variable.value];
// Create var with new ctr value
let ctr = variable.value;
// Check if current counter value is less than RR length (i.e. the number of numbers in round robin)
// If so, increment
if(ctr == numbers.length-1) {
ctr = 0;
}
// Otherwise reset ctr
else ctr++;
// Update counter value
client.serverless.services(context.RR_SERVICE_SID)
.environments(context.RR_ENV_SID)
.variables(context.RR_VAR_SID_CTR)
.update({value: ctr})
.then(resp => {
// Return number to call
let response = {number};
// Return our counter value and a null error value
callback(null, response);
});
});
};
CREATE YOUR STUDIO FLOW
Click the red plus sign to create a new Flow here.
Give the Flow a name and click Next.
Scroll to the bottom of the templates and click 'Import from JSON' and click Next.
Paste the Flow JSON shown here and click Next.
Click the RoundRobin function widget and select the Function you just created under the Default service.
Click the FunctionError widget, click MESSAGING & CHAT CONFIG, and change the SEND MESSAGE TO number to a number that you would like to notify by text in the event of a Function failure.
Click the DefaultNumber widget and change the default number that will be forwarded to in the event of a Function failure.
Click the Publish button at the top of your Flow.
CONFIGURE YOUR TWILIO NUMBER
Go here in the console.
Click the Twilio number you would like to configure.
Scroll down to the A CALL COMES IN dropdown in the Voice section and select Studio Flow.
Select your new Flow in the Select a Flow dropdown to the right.
Click Save at the bottom.
And that's it. You're now all set to test!

How to obtain Telegram chat_id for a specific user?

How to obtain user chat_id in Telegram bot API?
The documentation says:
Integer | Unique identifier for the message recipient — User or GroupChat id
The message updates you receive via getUpdates or your webhook will contain the chat ID for the specific message. It will be contained under the message.chat.id key.
This seems like the only way you are able to retrieve the chat ID. So if you want to write something where the bot initiates the conversation you will probably have to store the chat ID in relation to the user in some sort of key->value store like MemCache or Redis.
I believe their documentation suggests something similar here, https://core.telegram.org/bots#deep-linking-example. You can use deep-linking to initiate a conversation without requiring the user to type a message first.
I created a bot to get User or GroupChat id,
just send the /my_id to telegram bot #get_id_bot.
It does not only work for user chat ID, but also for group chat ID.
To get group chat ID, first you have to add the bot to the group,
then send /my_id in the group.
Here's the link to the bot.
There is a bot that echoes your chat id upon starting a conversation.
Just search for #chatid_echo_bot and tap /start. It will echo your chat id.
Another option is #getidsbot which gives you much more information. This bot also gives information about a forwarded message (from user, to user, chad ids, etc) if you forward the message to the bot.
First, post a message in a chat where your bot is included (channel, group mentioning the bot, or one-to-one chat). Then, just run:
curl https://api.telegram.org/bot<TOKEN>/getUpdates | jq
Feel free to remove the | jq part if your dont have jq installed, it's only useful for pretty printing. You should get something like this:
You can see the chat ID in the returned json object, together with the chat name and associated message.
You can just share the contact with your bot and, via /getUpdates, you get the "contact" object
Using the Perl API you can get it this way: first you send a message to the bot from Telegram, then issue a getUpdates and the chat id must be there:
#!/usr/bin/perl
use Data::Dumper;
use WWW::Telegram::BotAPI;
my $TOKEN = 'blablabla';
my $api = WWW::Telegram::BotAPI->new (
token => $TOKEN
) or die "I can't connect";
my $out = $api->api_request ('getUpdates');
warn Dumper($out);
my $chat_id = $out->{result}->[0]->{message}->{chat}->{id};
print "chat_id=$chat_id\n";
The id should be in chat_id but it may depend of the result, so I also added a dump of the whole result.
You can install the Perl API from https://github.com/Robertof/perl-www-telegram-botapi. It depends on your system but I installed easily running this on my Linux server:
$ sudo cpan WWW::Telegram::BotAPI
Hope this helps
chat_id is nothing but id of user (telegram user account id). You can start a chat with #get_my_chat_id_bot. It will send you back the chat_id (your user_id).
There are following commonly used ids: channel id, group id, bot id, chat id(user id).
Straight out from the documentation:
Suppose the website example.com would like to send notifications to its users via a Telegram bot. Here's what they could do to enable notifications for a user with the ID 123.
Create a bot with a suitable username, e.g. #ExampleComBot
Set up a webhook for incoming messages
Generate a random string of a sufficient length, e.g. $memcache_key = "vCH1vGWJxfSeofSAs0K5PA"
Put the value 123 with the key $memcache_key into Memcache for 3600 seconds (one hour)
Show our user the button https://telegram.me/ExampleComBot?start=vCH1vGWJxfSeofSAs0K5PA
Configure the webhook processor to query Memcached with the parameter that is passed in incoming messages beginning with /start. If the key exists, record the chat_id passed to the webhook as telegram_chat_id for the user 123. Remove the key from Memcache.
Now when we want to send a notification to the user 123, check if they have the field telegram_chat_id. If yes, use the sendMessage method in the Bot API to send them a message in Telegram.
Whenever user communicate with bot it send information like below:
$response = {
"update_id":640046715,
"message":{
"message_id":1665,
"from":{"id":108177xxxx,"is_bot":false,"first_name":"Suresh","last_name":"Kamrushi","language_code":"en"},
"chat":{"id":108xxxxxx,"first_name":"Suresh","last_name":"Kamrushi","type":"private"},
"date":1604381276,
"text":"1"
}
}
So you can access chat it like:
$update["message"]["chat"]["id"]
Assuming you are using PHP.
Extending #Roberto Santalla answer and if you prefer to use Telegram API together with javascript and axios library then you might want the following:
const method = 'get'
const headers: any = {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
timestamp: +new Date(),
}
const options = { headers: { ...headers } }
const urlTelegramBase =
'https://api.telegram.org/bot123456:ABCDEF'
const urlGetUpdates = `${urlTelegramBase}/getUpdates`
const username = 'user_name'
const {
data: { result: messages },
} = await axios[method](urlGetUpdates, options)
const chat_id = messages.find(
messageBlock => messageBlock.message.chat.username === username
).message.chat.id
console.info('chat_id': chat_id)

Interfax developer account configuration for multiple recipients

I want to configure an interfax account for sending and receiving faxes.
Can anyone tell me how to send/receive a test fax?
I know about the .sendFax() and .GetList() methods, but how do I send fax to myself (in test account)?
I followed the article,
Receive incoming faxes via callback to a web application
it works fine. But it only gives you intimation that you have received fax.
Edit:
You can set feedback url and use the parameter which they asked. When interfax will receive fax for you, it will send it to your feedback url and it will go directly to your database (If you set this in page load event).
You can use following code
MessageItem[] faxList = null;
Inbound inbound = new Inbound();
ListType messageListType = ListType.NewMessages;
int interFaxResult = inbound.GetList(AppConfig.InterfaxUsername, AppConfig.InterfaxPassword, messageListType, AppConfig.InterfaxMaxitems, ref faxList);
if (interFaxResult == 0)
{
// Save faxes in DB
}

Send an email via MailChimp

I think problem is around $api->listSubscribers()
include('../libs/mailchimp/MCAPI.class.php');
$options = array('list_id' => '$list_id', 'subject' => 'Prova', 'from_name' => 'name', 'from_email' => 'info#example.com');
$content = array('html' => '<p>Testo di prova</p>');
$api = new MCAPI($apikey);
$campaignId = $api->campaignCreate('trans', $options, $content);
$api->listSubscribe($options['list_id']);
$api->campaignSendNow($campaignId);
if ($api->errorCode){
echo "Unable to Create New Campaign!";
echo "\n\tCode=".$api->errorCode;
echo "\n\tMsg=".$api->errorMessage."\n";
} else {
echo "New Campaign ID:".$campaignId ."\n";
}
Why does'nt it send an email?
You have a several issues here:
The first one is that you are not doing error checking after each API call. If you take the error checking code from the bottom and stick it after the listSubscribe() call, you'll immediately get an error because you aren't passing any sort of subscriber data (at the very least you need the email address). The docs for listSubscribe are here
Once you do that - unless you've thoroughly read and considered the options in the listSubscribe docs - your second issue is going to be that you are running listSubscribe with the double_optin parameter set to true (the default), which means they won't be subscribed until clicking a link in the confirmation email.
Next, that code is just going to get you in trouble, and probably quickly. If you are going to use psuedo-transcational campaigns it is imperrative that you only create ONE psuedo-trans campaign per type of email and then send that campaign over and over. That's how they are intended to work. Not doing that is going to cause you to fill up your account with a whole bunch of trash campaigns at which point there's no point in using a psuedo-trans campaign since that's the same as creating/sending a regular campaign to a single user over and over.
Do you get any errors?
It seems you are not including the api key, it should look like:
$api = new MCAPI($apikey);
Instead of:
$api = new MCAPI('apikey');
You get the API Key from your api dashboard: http://admin.mailchimp.com/account/api