Twilio how to manage local phone numbers through api - twilio

I am trying to move my account off of using local numbers and onto toll free numbers.
I would like to get a list of all my local numbers. The incoming_phone_numbers api does not seem to return the Type attribute which tells me local vs toll free.
I believe I need to use the Active Number api, which is in preview, to get that info https://www.twilio.com/docs/phone-numbers/global-catalog/api/active-numbers
I am receiving a 404 response when I use the below script.
I've found post of people talking about this api, but all the comments were about the issue I am having with no resolution https://stackoverflow.com/a/63297180/3599659
from twilio.rest import Client
import keyring
import requests
from requests.auth import HTTPBasicAuth
account_sid = keyring.get_password("twilio", "account_sid")
auth_token = keyring.get_password("twilio", "auth_token")
client = Client(account_sid, auth_token)
numbers = client.incoming_phone_numbers.list(limit=1)
print(f"getting info for {numbers[0].sid}")
response = requests.get(f"https://preview.twilio.com/Numbers/ActiveNumbers/{numbers[0].sid}", auth=HTTPBasicAuth(account_sid, auth_token))
if not response:
print(f"Request for active numbers failed. status code:{response.status_code}. {response.content}")
quit()
print(response.content)

This API is in Private Developer Preview. I am not sure if it still open to accepting new customers. I am looking to discover this.

It does cost $0.005 per call but if you only have US numbers you can make a call to the lookups api requesting carrier information for the number.
response = requests.get(f"https://lookups.twilio.com/v1/PhoneNumbers/{numbers[0].phoneNumber}?Type=carrier", auth=HTTPBasicAuth(account_sid, auth_token))
This should list the carrier name as either Twilio - SMS/MMS-SVR or Twilio - Toll-Free - SMS-Sybase365/MMS-SVR so you can identify the toll free numbers that way. This is assuming the numbers were issued by twilio and haven't been ported in etc.

Related

Retrieving Message Service Name from Twilio's Phone Numbers API

I'm using the IncomingPhoneNumber resource (https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) to retrieve infomration about my phone numbers in Twilio.
Both .ReadAsync and .FetchAsync return numbers that I've bought via the Twilio console, and some of those numbers are in a Sender Pool for messaging services.
However, the payload returned by either of those two methods does not contain whether or not a phone number is in a message service pool.
On the console, you can see if a phone number belongs to a message service.
Is it possible, using the IncomingPhoneNumber Resource REST API to find out if a phone number is part of a messaging service?
No, the IncomingPhoneNumber resource won't be able to tell you that. But the PhoneNumber Resource of the Messaging Service API will be able to tell you (or help modify the assignments).
// Download the helper library from https://www.twilio.com/docs/node/install
// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);
client.messaging.v1.services('MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.phoneNumbers
.list({limit: 20})
.then(phoneNumbers => phoneNumbers.forEach(p => console.log(p.sid)));

Tweepy bot to tweet DMs

I would like to make a bot on twitter to use with my friends, it would be like a spotted. The bot would need to tweet the messages they send on his dm. On the internet I found this function, but I don't know if it's right, nor how to close this puzzle, can someone help me?
api.list_direct_messages()
You can get the DM messages with
auth = tweepy.OAuthHandler('api_key', 'api_secret')
auth.set_access_token('access_token', 'token_secret')
api = tweepy.API(auth)
messages = get_api().list_direct_messages(count=5)
The code above would rin in a thread to fetch the messages every x minutes.
Once you have the messages you can process the list, send the tweet and delete the DMs (to avoid processing it again).
for message in messages:
text = message.message_create["message_data"]["text"]
api.update_status(f'Tweet DM content: {text}'
# remove DM
api.destroy_direct_message(message.id)

Twilio: Get parameters from outbound calls from recordings

I have a TwiMl like this in a Bin:
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Say voice="alice">Hello {{Name}}. You have ticket number {{TicketNum}} so please solve it.</Say>
</Response>
Then I use hmac authentication and launch the script to make the call using the following TWIML Bin url with query strings attached:
twiml_link="https://handler.twilio.com/twiml/EHxxxxxxxxxxx?Name=Bob&TicketNum=45"
I get the call with Bob and Ticket 45. After that I need to alert our incident tracking system that Bob has acknowledge the ticket 45 and is "on it." I can't because of architecture send something back to my system. I need to go out and query twilio again.
So I wrote this python snippet to hit the Twilio API to find all completed calls. :
from twilio.rest import Client
import sys, os
# Your Account Sid and Auth Token from twilio.com/console
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)
calls = client.calls.list(status=completed)
for call in calls:
print(call.sid)
print(call.to)
print(call.status)
print(call.start_time)
print(call.duration)
print(call.annotation)
print(call.uri)
None of these commands can print Bob or the ticket number or the Twiml Bin URL or the query strings I used. Any tips? Thanks in Advance!
That approach isn't a reliable way to determine if the intended party answered the phone and acknowledge the message without "Human Detection". You can find more details here.
Alternative to AMD - "Human Detection"
https://support.twilio.com/hc/en-us/articles/223132567-Can-Twilio-tell-whether-a-call-was-answered-by-a-human-or-machine-#alternatives-to-amd
The dialed party could be a voicemail system, so querying the REST API to see if the call status was completed will provide misleading results if your goal is to determine the person acknowledged the ticket.
You could use a Twilio Function, https://support.twilio.com/hc/en-us/articles/115007737928-Building-apps-with-Twilio-Functions, to collect the result of the
Alan

Twilio lookup test numbers

There are test numbers to which you can send SMS using my test credentials. They fake sending beautifully. But, attempting to use the lookup API also provided by Twilio, even if the intention is to retrieve information about the test number, will fail:
>>> from django.conf import settings
>>> from twilio.rest.lookups import TwilioLookupsClient
>>> account_sid = settings.TWILIO_ACCOUNT_SID
>>> auth_token = settings.TWILIO_AUTH_TOKEN
>>> client = TwilioLookupsClient(account_sid, auth_token)
>>> lookup_client.phone_numbers.get('+15005555009', include_carrier_info=True)
---------------------------------------------------------------------------
TwilioRestException Traceback (most recent call last)
<ipython-input-9-03718f1c0615> in <module>()
----> 1 client.phone_numbers.get('+15005555009', include_carrier_info=True)
...
TwilioRestException:
HTTP Error Your request was:
GET https://lookups.twilio.com/v1/PhoneNumbers/+15005555009?Type=carrier
Twilio returned the following information:
Resource not accessible with Test Account Credentials
More information may be available here:
https://www.twilio.com/docs/errors/20008
+15005555009 is the only phone number listed to emulate a landline, that is incapable of returning an SMS. I am expecting the API to return 'landline' for the carrier type for such a number. That link in the error message brings me to a page with no working test credentials.
How can I test the lookup API with the test credentials given?
I don't think you can use the lookup API with test credentials.
From https://www.twilio.com/docs/api/rest/test-credentials ...
"Supported Resources
Your test credentials can currently be used to interact with the following three resources:
Buying phone numbers: POST
/2010-04-01/Accounts/{TestAccountSid}/IncomingPhoneNumbers
Sending SMS messages: POST
/2010-04-01/Accounts/{TestAccountSid}/SMS/Messages
Making calls: POST /2010-04-01/Accounts/{TestAccountSid}/Calls
Requests to any other resource with test credentials will receive a 403 Forbidden response. In the future, we may enable these resources for testing as well."

Twilio IP Messaging - get the last message index on REST API

Using the twilio-ruby package to connect to the REST API for Twilio's IP Messaging service and attempting to compute an unread message count.
The REST API is paginating the messages so that something like
channel.messages.list.last.index
Will return 49 once there are more than 50 messages in the channel.
Is there a way to get just the last message on the channel (as seems to be possible in the android/ios SDK) to avoid paginating through all message history?
In regards to computing an unread message count, take a look at the Message Consumption Horizon and subtract the lastConsumedMessageIndex from the total number of messages in the list - 1.
For the messages list (in Python):
https://www.twilio.com/docs/api/ip-messaging/rest/messages#list-all-messages
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest.ip_messaging import TwilioIpMessagingClient
# Your Account Sid and Auth Token from twilio.com/user/account
account = "ACCOUNT_SID"
token = "AUTH_TOKEN"
client = TwilioIpMessagingClient(account, token)
service = client.services.get(sid="SERVICE_SID")
channel = service.channels.get(sid="CHANNEL_ID")
messages = channel.messages.list()
See also, Sending a Consumption Report (the example in JavaScript):
//determine the newest message index
var newestMessageIndex = activeChannel.messages.length ?
activeChannel.messages[activeChannel.messages.length-1].index : 0;
//check if we we need to set the consumption horizon
if (activeChannel.lastConsumedMessageIndex !== newestMessageIndex) {
activeChannel.updateLastConsumedMessageIndex(newestMessageIndex);
}

Resources