How can I find available Twilio numbers based on the US state?
When we are in the Twilio console, there is a criteria where we can add a number and select "match to = first part of number", which I guess works with regex conditions / patterns.
I am aware we can extract the state prefixes and to use the prefix for the state which we want to search and use it as some pattern.
In addition, I need to check for the voice capabilities.
I am referring to this API: https://www.twilio.com/docs/phone-numbers/api but I have a hard tome to understand the proper fields that needs to be used. Also, I found many StackOverflow questons pointing to a links to Twilio doc, that are no longer valid.
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);
const statePrefix = '823';
const voiceCapabilty = true;
client.availablePhoneNumbers('US')
.then(/* do something */);
Related
I'm trying to retrieve a list of Slack reminders, which works fine using Slack API's reminders.list method. However, reminders that are set using SlackBot (i.e. by asking Slackbot to remind me of a message) return the respective permalink of that message as text:
{
"ok": true,
"reminders": [
{
"id": "Rm012C299C1E",
"creator": "UV09YANLX",
"text": "https:\/\/team.slack.com\/archives\/DUNB811AM\/p1583441290000300",
"user": "UV09YANLX",
"recurring": false,
"time": 1586789303,
"complete_ts": 0
},
Instead of showing the permalink, I'd naturally like to show the message I wanted to be reminded of. However, I couldn't find any hints in the Slack API docs on how to retrieve a message identified by a permalink. The link is presumably generated by chat.getPermalink, but there seems to be no obvious chat.getMessageByPermalink or so.
I tried to interpet the path elements as channel and timestamp, but the timestamp (transformed from the example above: 1583441290.000300) doesn't seem to really match. At least I don't end up with the message I expected to retrieve when passing this as latest to conversations.history and limiting to 1.
After fiddling a while longer, here's how I finally managed in JS:
async function downloadSlackMsgByPermalink(permalink) {
const pathElements = permalink.substring(8).split('/');
const channel = pathElements[2];
var url;
if (permalink.includes('thread_ts')) {
// Threaded message, use conversations.replies endpoint
var ts = pathElements[3].substring(0, pathElements[3].indexOf('?'));
ts = ts.substring(0, ts.length-6) + '.' + ts.substring(ts.length-6);
var latest = pathElements[3].substring(pathElements[3].indexOf('thread_ts=')+10);
if (latest.indexOf('&') != -1) latest = latest.substring(0, latest.indexOf('&'));
url = `https://slack.com/api/conversations.replies?token=${encodeURIComponent(slackAccessToken)}&channel=${channel}&ts=${ts}&latest=${latest}&inclusive=true&limit=1`;
} else {
// Non-threaded message, use conversations.history endpoint
var latest = pathElements[3].substring(1);
if (latest.indexOf('?') != -1) latest = latest.substring(0, latest.indexOf('?'));
latest = latest.substring(0, latest.length-6) + '.' + latest.substring(latest.length-6);
url = `https://slack.com/api/conversations.history?token=${encodeURIComponent(slackAccessToken)}&channel=${channel}&latest=${latest}&inclusive=true&limit=1`;
}
const response = await fetch(url);
const result = await response.json();
if (result.ok === true) {
return result.messages[0];
}
}
It's not been tested to the latest extend, but first results look alright:
The trick with the conversations.history endpoint was to include the inclusive=true parameter
Messages might be threaded - the separate endpoint conversations.replies is required to fetch those
As the Slack API docs state: ts and thread_ts look like timestamps, but they aren't. Using them a bit like timestamps (i.e. cutting off some characters at the back and inserting a dot) seems to work, gladly, however.
Naturally, the slackAccessToken variable needs to be set beforehand
I'm aware the way to extract & transform the URL components in the code above might not the most elegant solution, but it proves the concept :-)
I see that Dialogflow has fulfiment and webhook installations to allow for further dynamic and logistic control over the bot responses. I'm trying to peg a database on top of the webhook, but the channel I'm using is Twilio Text Messaging, and I'm having a little trouble with connecting the two. When I do activate fulfillment, the twilio bot does not read it. Any way to solve this?
I already created a few webhooks using Flask, and integrated it through fulfillment briefly using ngrok, but the bot is responding via the text responses I set for it. Its for google assistance, and facebook messenger, but not with the Twilio integration.
I also tried using inlineJS to see if that held any difference to specifically define Twilio as the messaging outlet to use, however it did not peak success.
const functions = require('firebase-functions');
const {dialogflow} = require('actions-on-google');
const GOODLOCATION = 'location.good'
const NEARLOCATION = 'location.near'
const CHEAPLOCATION = 'location.cheap'
const WELCOME_INTENT = 'Default Welcome Intent'
const FALLBACK_INTENT = 'Default Fallback Intent'
const CRAVINGCULTUREINTENT = 'CravingCulture'
const CRAVINGITEM = 'CravingItem'
const app = dialogflow()
/*Supported Platforms*/
const PLATFORMS = {
UNSPECIFIED: 'PLATFORM_UNSPECIFIED',
FACEBOOK: 'FACEBOOK',
SLACK: 'SLACK',
TELEGRAM: 'TELEGRAM',
KIK: 'KIK',
SKYPE: 'SKYPE',
LINE: 'LINE',
VIBER: 'VIBER',
ACTIONS_ON_GOOGLE: 'ACTIONS_ON_GOOGLE',
TWILIO: 'TWILIO'
};
// Platforms that support Rich messaging
const SUPPORTED_RICH_MESSAGE_PLATFORMS = [
PLATFORMS.FACEBOOK,
PLATFORMS.SLACK,
PLATFORMS.TELEGRAM,
PLATFORMS.KIK,
PLATFORMS.SKYPE,
PLATFORMS.LINE,
PLATFORMS.VIBER,
PLATFORMS.ACTIONS_ON_GOOGLE,
PLATFROM.TWILIO
];
app.intent(WELCOME_INTENT, (conv)=> {
if(agent.requestSource === agent.TWILIO){
conv.ask('This is working, Congratulations!')
}
else{
conv.ask("Could not be served")
}
});
app.intent(FALLBACK_INTENT, (conv)=> {
conv.ask("I am unaware of that phrase, could you repeat that?")
});
exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app)
I want the output to be any thing that the user insert through the twilio that this bot will respond accordingly to what is passed in.
A little late, perhaps - hopefully this issue isn't still blocking/plaguing you.
I'm thinking you were intending:
if(agent.requestSource === PLATFORMS.TWILIO){
not:
if(agent.requestSource === agent.TWILIO){
However, also the value of agent.requestSource is actually lowercase "twilio".
I am working on a program where I will text a message to my Twilio number and have it send the message out to a group of people. I want the numbers to read from either a SQL database (so that people can sign up on a website via PHP) or through a Google Sheets spreadsheet. I really don't know where to start and was wondering if I could get some input from the pros.
Thank you!
Anthony
Twilio developer evangelist here.
If what you're looking for is using Google Spreadsheets, we actually have a pretty comprehensive tutorial on how to use Google Spreadsheets with PHP here.
But the gist is the following:
Enable your spreadsheet for programmatic access
Start reading the data from it and loop through your records.
Looping through your records can be as easy as this:
// Get our spreadsheet
$spreadsheet = (new Google\Spreadsheet\SpreadsheetService)
->getSpreadsheetFeed()
->getByTitle('Phone Numbers');
// Get the first worksheet (tab)
$worksheets = $spreadsheet->getWorksheetFeed()->getEntries();
$worksheet = $worksheets[0];
$listFeed = $worksheet->getListFeed();
/** #var ListEntry */
foreach ($listFeed->getEntries() as $entry) {
$phone = $entry->getValues();
}
On the loop above, you could also use the Twilio REST api to start sending SMS messages with Twilio as follows:
$sms = $client->account->messages->create(
// the number we are sending to - Any phone number
$phone,
array(
// Step 6: Change the 'From' number below to be a valid Twilio number
// that you've purchased
'from' => "YOUR_NUMBER",
// the sms body
'body' => "Hey $name, Monkey Party at 6PM. Bring Bananas!"
)
);
So it's just a matter of using the two together. you can read more about sending messages with PHP here.
Hope this helps you out
Does Twilio support lookup request using a subAccountSID instead of the accountSID?
I want this in order to organize the invoices for my clients and don't have to rely on creating my own log for that.
Twilio developer evangelist here.
If you want to use the subaccount details, you just need the subaccount sid and auth token. Then you can setup the lookups client like this:
const string subAccountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
const string subAuthToken = "subaccount_auth_token";
var lookupsClient = new LookupsClient(subAccountSid, subAuthToken);
// Look up a phone number in E.164 format
var phoneNumber = lookupsClient.GetPhoneNumber("+15108675309", true);
How do I search for phone number by prefix using the API? The Twilio "Buy A Number" tool lets you search for begins with term, but I don't see a way to do it using the API.
You can do:
AvailablePhoneNumbers/US/Local?Contains=703%
But that still finds numbers with 703 anywhere, not just the prefix. Only way I can see to do this is using the * single number search, a la:
AvailablePhoneNumbers/US/Local?Contains=703*******
But then how do I make that generic to any country? Have a lookup table of phone number lengths for every country so I can add the appropriate number of *'s?
Twilio provides this information in their API docs (Find phone numbers by number pattern).
For example using PHP:
<?php
// Get the PHP helper library from twilio.com/docs/php/install
require_once('/path/to/twilio-php/Services/Twilio.php'); // Loads the library
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "ACde6f132a3c49700934481addd5ce1659";
$token = "{{ auth_token }}";
$client = new Services_Twilio($sid, $token);
$numbers = $client->account->available_phone_numbers->getList('US', 'Local', array(
"Contains" => "510555****"
));
foreach($numbers->available_phone_numbers as $number) {
echo $number->phone_number;
}