使用Twilio功能转发SMS消息时获取Twilio电话号码友好名称

当我将SMS消息转发到另一个电话号码时,我想传递Twilio电话号码的友好名称。 (“友好名称”是购买时分配给Twilio号码的属性。)

这与herehere中所述的“使用Twilio字母数字的发件人ID发送品牌的SMS消息”相同。

我在不支持上述条件的美国运营,并且可以在转发的邮件正文(或电子邮件的主题行)中包含“友好名称”。另外,“友好名称”与上述示例中的消息的原始发件人不相关,而是与我的Twilio号相关联。希望一切都清楚。

我正在使用以下示例代码:

Forwarding SMS messages to another phone number – Twilio Support

三个参数传递给函数:

exports.handler = function(context,event,callback) {

context包括我配置的环境变量。 callback与这个问题无关。对于event参数,我们具有以下属性:

accountSid
ApiVersion
Body
From
FromCity
FromCountry
FromState
FromZip
MessageSid
NumMedia
NumSegments
SmsMessageSid
SmsSid
SmsStatus
To
ToCity
ToCountry
ToState
ToZip

我想使用Twilio Functions获取友好名称,它不是event的属性。是否可以通过其他属性之一获得友好名称?如果可以,怎么办?

更新:从this Twilio doc起,我发现有一条线索可以从accountSid获得友好名称。某事 .outgoing_caller_id.friendlyName

我不太了解如何在Twilio函数中执行此操作。我尝试使用:

context.getTwilioClient();

文档说:“将返回一个初始化的REST客户端,您可以使用该客户端来调用Twilio REST API。”但是,它返回一个空的httpClient对象以及用户名,密码和accountSID的字符串。我期待有一个填充的对象,可以从中获取电话号码的友好名称。

顺便说一句,我想问一下哪些对象被传递到event参数中。在什么情况下event参数包含的属性与我上面列出的属性不同?

c2125102 回答:使用Twilio功能转发SMS消息时获取Twilio电话号码友好名称

您正走在正确的道路上!优秀的研究。实际上,context.getTwilioClient()是其中的一部分。初始化Twilio REST API客户端后,就可以使用另一个Twilio API来确定event.To中的FriendlyName。我在这里找到Filter IncomingPhoneNumbers with exact match

下面是一种方法,当然可能还有其他方法。

const got = require('got');

// async function to deal with async REST API call

exports.handler = async function(context,event,callback) {

  const client = context.getTwilioClient();

  // await an async response
  await client.incomingPhoneNumbers
    .list({phoneNumber: event.To,limit: 1})
    .then(incomingPhoneNumbers => event.friendlyName = incomingPhoneNumbers[0].friendlyName)
    .catch(err => console.log(err));

  const requestBody = {
    personalizations: [{ to: [{ email: context.TO_EMAIL_ADDRESS }] }],from: { email: context.FROM_EMAIL_ADDRESS },subject: `New SMS message from: ${event.From}`,content: [
      {
        type: 'text/plain',value: `${event.Body} - ${event.friendlyName}`
      }
    ]
  };

  got
    .post('https://api.sendgrid.com/v3/mail/send',{
      headers: {
        Authorization: `Bearer ${context.SENDGRID_API_KEY}`,"Content-Type": 'application/json'
      },body: JSON.stringify(requestBody)
    })
    .then(response => {
      console.log(response);
      let twiml = new Twilio.twiml.MessagingResponse();
      twiml.message({to: '+1555xxxxxxx'},`You Message: ${event.Body} - ${event.friendlyName}`);
      callback(null,twiml);
    })
    .catch(err => {
      console.log(err);
      callback(err);
    });
};

特定于与事件对象关联的键,这是一个方便使用的键。

Object.keys(event).forEach( thisKey => console.log(`${thisKey}: ${event[thisKey]}`));
本文链接:https://www.f2er.com/3127699.html

大家都在问