Using the Twilio API, how can I check if a number is in use by a service? - node.js

I am trying to create a new messaging service using the Node.js twilio sdk. To do so, I have devised the following workflow.
I've created a new service like so.
client.messaging.v1.services.create({
friendlyName: 'test service,
inboundRequestUrl: 'https://someUrl.com',
inboundMethod: 'POST',
usecase: 'discussion'
})
I list all the numbers I own like so:
client.incomingPhoneNumbers.list()
I assign a number to my service like so (where the serviceSid is the sid of the service created in step 1 and the phoneNumberSid is the sid of one of phone numbers returned in step 2):
client.messaging.v1.services(<serviceSid>)
.phoneNumbers
.create({ phoneNumberSid: <phoneNumberSid> })
I am happy with this workflow, with the exception of one problem. You cannot assign the same number to two different messaging services, so I need to make sure the phone number whose sid I pass into step 3, doesn't already have a service. The problem is that the response I get back from step 2 doesn't tell me whether the numbers are used by another service.
All of this to say, can anyone suggest some way to modify this workflow to be more robust? Ideally, is there some way I can tell from step 2 whether or not a number is already being used by a service, so I know not to pass it in to step 3?
Thanks

Yes, there is a way to do this. To be honest, it's not very nice, but you can iterate over all messages services and test if your phone number (SID) belongs to a mapping of one of the services and then remove this mapping. Once removed, you can assign the phone number to any other messaging service.
async function unbindPhoneFromMessagingServices(phoneNumberSid) {
const allServices = await client.messaging.v1.services.list();
await Promise.all(
allServices.map(async (service) => {
const mapping = client.messaging.v1
.services(service.sid)
.phoneNumbers(phoneNumberSid);
try {
await mapping.fetch();
} catch (e) {
const RESOURCE_NOT_FOUND = e.code === 20404;
if (RESOURCE_NOT_FOUND) {
return;
}
throw e;
}
await mapping.remove();
console.log(
`The phone number was decoupled from messaging service ${service.sid}.`
);
})
);
}
PS: This snippet is taken from one of my repositories. Feel free to check out the complete code on GitHub.

Related

XERO-NODE SDK => How to choose a specific email template

I am using the Xero-node SDK to automatically create client invoices which works well.
At the end of the process, I would like to automatically email the client the invoice.
In the documentation it has the following example:
const xeroTenantId = 'YOUR_XERO_TENANT_ID';
const invoiceID = '00000000-0000-0000-0000-000000000000';
const requestEmpty: RequestEmpty = { };
try {
const response = await xero.accountingApi.emailInvoice(xeroTenantId, invoiceID, requestEmpty);
console.log(response.body || response.response.statusCode)
} catch (err) {
const error = JSON.stringify(err.response.body, null, 2)
console.log(`Status Code: ${err.response.statusCode} => ${error}`);
}
I have 2 questions:
The requestEmpty method does not work in javascript. Does anyone know the correct structure of requestEmpty?
I have used requestEmpty = { } but this throws an error => even though the system does actually send an email (probably a bug)
AND....
Is there a way for me to specify the email template that I would like the invoice to use (if I have specific templates setup in the web version)? Currently it seems to use the default Xero email template.
If you don't get an answer to your first query here, please can you raise it on the SDK page in Github and the Xero SDK team will look into this for you.
With regards to point 2, it is not possible to choose the email template when sending through the API, a basic template is used.

How change friendly name notify twilio sms

I am having some problems, I want to change the name of the sender. I mean, it is possible to assign an Alphanumeric Sender ID, I reviewed the documentation and followed the guidelines, in the response of the twilio api the name goes but when in the messages I receive it sends them to the same number. I know that it is not something due to the regulations of the country because according to the twilio documentation, it is possible. (https://support.twilio.com/hc/en-us/articles/223133767-International-support-for-Alphanumeric-Sender-ID) What is happening? How can I fix? Do I have to do any configuration?
How I want the sender ID to be seen
As I receive the sender ID
UPDATING QUESTION
Ok, the way I have structured the code is as follows:
I am working on a nodejs project, I need to send a message to multiple phone numbers so in order to do it I used the SMS notification service offered by Twilio, this is the method that was created:
async sendSMSAsNotify(req: Request, res: Response) {
try {
console.log("req.body:", req.body);
let messageBody = req.body.body;
console.log(messageBody);
let numberList = req.body.toBinding;
let extractBody = messageBody.replace(/<[^>]+>/g, '');
console.log(extractBody);
var decodedStripedHtml = he.decode(extractBody);
//console.log(decodedStripedHtml);
//console.log(`Body: ${messageBody}`);
var numbers = [];
for (let i = 0; i < numberList.length; i++) {
numbers.push(
JSON.stringify({
binding_type: "sms",
address: numberList[i],
})
);
}
const notificationOpts = {
toBinding: numbers,
body: decodedStripedHtml,
title: 'MyCompany'
};
// console.log("numbers:", notificationOpts.toBinding);
// console.log("body", notificationOpts.body);
const response = await this.client.notify
.services(process.env.SERVICE_SID_NTF)
.notifications.create(notificationOpts);
console.log('response', response);
res.json({
msg: `Message sent successfully! ${response}`,
});
} catch (e) {
throw new HttpException(HttpErrors.NOT_FOUND_ERROR, HttpStatus.NOT_FOUND);
}
}
The sendSMSAsNotify() method works great, I can send the same SMS to multiple numbers. But now what I want to achieve is that every message I send shows the sender id. I didn't find how to do it in the documentation of the SMS notification service, so I tried to change it and use a very simple method to send SMS via twilio to a single number just for testing.
async sendSMS(sms: SMSDto) {
try {
return await this.client.messages.create({
body: sms.message,
from: 'MyCompany',
to: sms.number,
});
} catch (e) {
return e
}
}
But in neither of the two methods in which I tried to change the sender identification it did not allow me and that is what brings me here, I really need help, it is a requirement that I need to fulfill and I cannot find a way to help me.
First up, while the list of countries that support alphanumeric sender IDs does contain Honduras there are further guidelines for SMS in Honduras that say:
Dynamic Alphanumeric Sender IDs are not fully supported for Honduras mobile operators. Sender IDs may be overwritten with a local long code or short code outside the Twilio platform.
So, even if you set everything up as I am about to explain, it is still possible that your sender ID may be overwritten with a local long code or short code and that Twilio is unable to do anything about that.
That being said, here's how to set up for alphanumeric sender IDs.
Since you are using Notify to send the messages, you will have set up a Messaging Service to use with Notify.
The Messaging Service controls how the SMS messages are sent out from Notify, from a pool of numbers. That pool can also contain your alphanumeric sender ID
So, to send from an alphanumeric sender ID you need to go to your Sender Pool within your Messaging Service and add an alpha sender.
Once you have the alpha sender set in your Messaging Service's pool, it will be used to send your messages out. You can even remove any long code numbers you have in the pool, if you do not plan to use them, though they are useful to fallback to if you do send to a country that doesn't support alphanumeric sender IDs.
Is it possible that you are in a country that does not support alphanumeric sender IDs and that Twilio falls back on a short code then?
PS: It would be helpful if you could add a code snippet, that shows the code you run, to your question.

issue with creating role and channel automatically from private message with bot

Not sure how the create channel and create role isn't working inside the following code, towards the bottom. (EDIT: Nothing is sent to the console and nothing happens regardng the code. It is like it is entirely ignored.) This is a snippet from code that User A challenges User B. User B is messaged, alerting them that a challenge has been issued to them via a Private Message. If the challenge is accepted, I want the bot to 1)Make a role specifically for User A and User B named "User A vs User B" 2) take User A and User B and put them both into that new role and 3) Make a battlefield named "User A vs User B" inside a specific category inside the server the bot is on.
I am unsure if the problem lies in how the bot is trying to make the role and channel in a sever while the bot is talking to the user in a private message instead of on the server. I thought putting the "server" variable as the server ID would help but it doesn't seem to do anything after the accept message.
// Awaits reply from user
if (message.channel.id === '541736552582086656') return target.send("Do you accept the challenge? Please reply with 'accept' or 'deny'.")
.then((newmsg) => {
newmsg.channel.awaitMessages(response => response.content, {
max: 1,
time: 150000,
errors: ['time'],
}).then((collected) => {
// Grabs the first (and only) message from the collection.
const reply = collected.first();
if (reply.content === 'accept'){
reply.channel.send(`You have ***accepted *** the challenge from ${challenger}. Please wait while your battlefield is made...`);
message.author.send(`${target} has accepted your challenge! Please wait while the channel is made for your brawl...`)
/// Problems start here
function createChannel(message){
var server = "SERVER ID";
var name = `${target} vs ${challenger}`;
message.guild.createRole({
role: {
name: `${target} vs ${challenger}`,
color: "#00fffa",
permissions: [] }
}).then(role => {
target.addRole(role, name)
challenger.addRole(role, name)
.catch(error => client.catch(error))
}).catch(error => client.catch(error))
server.createChannel(Name, name).then(
(channel) => {
channel.setParent("CATEGORY ID")
})
} // problems end here
} else if (reply.content === 'deny') {
reply.channel.send("You have ***denied *** the challenge.")
} else {
reply.channel.send("Your response wasn't valid.");
}
})
})
}
I have been wondering if I need to go about making the channel and role in a different way since it is trying to be made from a private message and not inside the server..
Thanks for any and all help! I also apologize if I'm using stack overflow too much for problems like this... You guys are great at helping me see different ways to do things and what I'm doing wrong, so I am learning, but I don't want to feel like I'm abusing it too much.
I think the problem is the fact that you create a function called createChannel with the code to create a rol and channel, but you never call said function.
You can either call the function after you've declared it or (which is in my opinion better) you can remove the following lines
function createChannel(message){
} // problems end here

Twilio Functions - SMS masking

Hello I am quite new to Twilio, but I have tried to look up how to answer this question. I would like to use Twilio Functions to solve my problem. I was wondering if it is possible for two people to send SMS messages to each other without revealing either of their numbers.
I was hoping to do this with only one new number per pair.
I imagined it would be through a conditional statement, where person X sends a message to the twilio number and person Y receives it, and vice versa. I assume this cannot be done with the twiML bins because of this conditional statement.
Thanks for your attention.
Twilio developer evangelist here.
You could absolutely do this with Twilio Functions. Here's a simple example of using a number to mask SMS messages between two callers.
class NumberMapping {
constructor() {
this.mapping = {};
}
addMaskedPair(numberA, numberB, twilioNumber) {
if (!this.mapping[twilioNumber]) {
this.mapping[twilioNumber] = {};
}
this.mapping[twilioNumber][numberA] = numberB;
this.mapping[twilioNumber][numberB] = numberA;
}
findNumber(from, to) {
const numberPairs = this.mapping[to];
if (!numberPairs) { return undefined; }
return numberPairs[from];
}
}
const numberMapping = new NumberMapping();
numberMapping.addMaskedPair('+1234567890', '+1098765432', '+1203948576');
exports.handler = function(context, event, callback) {
const to = numberMapping.findNumber(event.From, event.To);
if (typeof to !== 'undefined') {
const response = new Twilio.twiml.MessagingResponse();
response.message({ from: event.To, to: to }, event.Body);
callback(null, response);
} else {
callback(new Error(`Number mapping couldn't be found for sender ${event.From} and Twilio number ${event.To}.`));
}
};
The idea is that you create a NumberMapping object that maps between the two external numbers and your Twilio number. You add your mappings using:
numberMapping.addMaskedPair(firstNumber, secondNumber, twilioNumber);
and then when you need to retrieve the other number in a pair you can call
numberMapping.findNumber(number, twilioNumber);
The rest is just the function to return TwiML.
Note, you will only need as many Twilio numbers as there are relationships of the number that has the maximum set of relationships.
Let me know if that helps at all.
You need to purchase a number from twilio, then use node JS code to send and receive sms with it. You can also send voice messages too. The thing with twilio is that when you receive messages, twilio saves it to its website so you have to go to website and check it explicitly with your account.
You can create account and receive messages with this link
Here is some tutorial on how to send messages, you have to choose node.JS option.

Windows Azure node.js Push notification for Windows store 8.1 - How to use 'createRawTemplateRegistration' template?

Please explain with one example as I am getting Error: 400 - The specified resource description is invalid.
Basically, I want to update badge value. But there is no template for badge registration in WnsService API document (http://azure.github.io/azure-sdk-for-node/azure-sb/latest/WnsService.html). So, I am trying with "createRawTemplateRegistration" template to update the badge value.
Please help me on this.
You can directly use the function sendBadge() to push badge value to client devices.
Please try the following code:
var azure = require('azure');
var notificationHubService = azure.createNotificationHubService('<hubname>', '<connectionstring>');
notificationHubService.wns.sendBadge(null,99,function(error,response){
if(error) console.log(error);
console.log(response);
})
Any further concern, please feel free to let me know.
update
Do you mean that you want only one template and to handle all the types of notifications including Raw, Toast, Badge? If so, I think the answer is negative. According the description http://azure.github.io/azure-sdk-for-node/azure-sb/latest/WnsService.html#createRawTemplateRegistration:
Remember that you have to specify the X-WNS-Type header
So the header option is required. And according the REST API which is invoked via this api in nodejs is Create Registration, and we can find the description:
The BodyTemplate element is mandatory, as is the X-WNS-Type header.
So we should specify the notification type for the template.
update1
This code sample works fine on my side:
var channel = '<devicetoken>';
var templateMessage = { text1: '$(message)' };
notificationHubService.wns.createRawTemplateRegistration(channel,'tag',JSON.stringify(templateMessage), {headers: { 'X-WNS-Type': 'wns/raw' }},
function (e, r) {
if (e) {
console.log(e);
} else {
console.log({
id: r.RegistrationId,
deviceToken: r.DeviceToken,
expires: r.ExpirationTime
});
}
}
)

Resources