twilio-labs / function-templates Goto Github PK
View Code? Open in Web Editor NEWTwilio Function templates for different Voice, SMS, Video, Chat, Sync, etc use cases
License: MIT License
Twilio Function templates for different Voice, SMS, Video, Chat, Sync, etc use cases
License: MIT License
If we are going to allow twilio-run
to create new templates within the same namespace unless function/asset names overlap, we should make it harder for function names to overlap.
The video, chat and sync token templates all have functions/token.js
.
We should rename them to video-token.js
, chat-token.js
and sync-token.js
.
We should have docs that show how to copy paste the templates into the console UI
Migrate the Simulring Twimlet to an equivalent Twilio Function Template.
Dial up to 10 non-empty forwarding numbers in parallel, connecting the first one that picks up.
(the Twimlet generator only accepts up to 5 numbers but the limitation is not enforced by the Twimlet itself and <Dial>
supports up to 10 numbers.)
with:
<Number>
's url
configured to play a message to the recipient using the undocumented Whisper Twimlet with the optional Message
parameterTimeout
seconds, or 20 seconds by defaultDial
flag set to true
FailUrl
parameterPlay a message to the recipient, requesting to press a digit to accept the call.
If a key has been pressed by the recipient, bridge the call.
(that's the idea at least, but in practice, the call is bridged whether a digit has been pressed or not)
WHEN the forwarded call ends (Dial
flag is set to true
)
IF the status of the call DialStatus
is answered
or DialCallStatus
is completed
OR the fallback URL FailUrl
is empty
THEN hang up
ELSE redirect to the fallback URL FailUrl
.
To make it more contributor and user friendly we should create at least a prettier setup that is automatically run.
Migrate the Forward Twimlet to an equivalent Twilio Function Template.
WHEN a phone call is incoming
IF the incoming phone number phone
is found in a white list of up to five allowed numbers AllowedCallers
OR the white list is empty
THEN forward the call to the outgoing phone number PhoneNumber
with:
CallerId
if provided,Timeout
seconds, or 20 seconds by default,Dial
flag set to true
FailUrl
set to the provided FailUrl
value, if any, or an empty stringWHEN the forwarded call ends (Dial
flag is set to true
)
IF the status of the call DialStatus
is answered
or DialCallStatus
is completed
OR the fallback URL FailUrl
is empty
THEN hang up
ELSE redirect to the fallback URL FailUrl
.
Migrate the Find Me Twimlet to an equivalent Twilio Function Template.
WHEN a phone call is incoming
IF the list of forwarding phone numbers PhoneNumbers
, limited to a maximum of 10 non-empty phone numbers, contains at least one non-empty phone number
THEN pop the next non-empty phone number from the list and forward the call to that number with:
<Number>
's url
configured to request the recipient to accept the call explicitly by pressing a key, using the undocumented Whisper Twimlet with:
Message
HumanCheck
flag set to 1
Timeout
seconds, or 60 seconds by defaultDial
flag set to true
FailUrl
, Timeout
and Message
PhoneNumbers
ELSE (no more forwarding number are available)
redirect to the FailUrl
, if any, or hang up
Play a message to the recipient, requesting to press a digit to accept the call.
If a key has been pressed by the recipient, bridge the call.
(that's the idea at least, but in practice, the call is bridged whether a digit has been pressed or not)
WHEN a forwarded call ends (Dial
flag is set to true
)
IF the status of the call DialStatus
is answered
or DialCallStatus
is completed
THEN hang up
ELSE go back to stage 1 and try the next forwarding number, if any.
Theevent.Sid
property in the /save-sms
function is invalid. It should be changed to event.SmsSid
.
warning @twilio-labs/plugin-serverless > twilio-run > ngrok > [email protected]: request-promise-native has been deprecated because it extends the now deprecated request package, see request/request#3142
warning @twilio-labs/plugin-serverless > twilio-run > ngrok > [email protected]: request has been deprecated, see request/request#3142
warning @twilio-labs/plugin-serverless > twilio-run > ngrok > request > [email protected]: this library is no longer supported
error [email protected]: The engine "node" is incompatible with this module. Expected version ">=10.17.0". Got "10.16.0"
error Found incompatible module.
I'm having some problems getting the start-verify.js to work using the functions API. First the code has event.to. Changing it to event.To get's me farther but then I get this every time. (I replaced the SID with a dummy in this example).
ERROR { success: false, error: { message: 'The requested resource /Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXX/Verifications was not found', moreInfo: 'https://www.twilio.com/docs/errors/20404' }
The verify services works outside of functions. Any idea what it can't find the service?
The underlying platform updates inline with the Node release schedule for Node 10 currently.
Is it enough to just set the .nvmrc
file to 10
?
I was following the main README instructions nvm use
however I think that might be outdated, because when I run twilio serverless:start
in the https://github.com/twilio-labs/function-templates/tree/master/verify example I get:
WARNING Different Node.js Version Found
Following the guide here, https://www.twilio.com/docs/voice/sip/quickstart#initialize-your-environment, when trying to initialise the environment - password is not being accepted. Based on the logs seen from console there is a 403 Not authorized error.
Checked the environment parameter the password is configured as "default". This problem is the same for my other colleague as well.
requestBody: {
values: [[event.SmsSid, event.From, event.Body, event.To, event.DateSent, event.DateCreated]],
},
which one is correct : event.DateSent or event.DateCreated
Migrate the Simple Message Twimlet to an equivalent Twilio Function Template.
Play each message from the list of messages, Message
, in turn:
Message
, if it starts with http
Message
using an English voiceWhile the Simple Message Twimlet generator only allows to provide up to five messages, this limit is not enforced in the code.
I ran the Twilio video chat on my iPhone.
The (severless) video chat is derived from https://www.twilio.com/code-exchange/basic-video-chat
a) From my laptop, I can see the video picture from the iPhone.
b) From my iPhone, I can see the video picture from my laptop.
Here is the iPhone "problem"..... From my iPhone, I CANNOT see the video picture of myself at my iPhone It looks black. (Self View does not work)
However, from my laptop, I am able to see the video picture of myself at my laptop. (This Self View works)
Here is the URL for the video chat
https://video1-5706-ed4jfp.twil.io/conference.html
Do you think you can try it from your laptop talking to your iPhone? See if it works or does not work on your iPhone.
I am NOT using Github. I can copy my serverless code in Twilio and email the copy of the code to you.
There are no errors when I deploy the video chat app from Twilio. I am using Nodejs v16 in Twilio.
Thanks for all your help,
Timothy Quek
Looks like the explanation got cut off:
Meaning once it's deployed it will not be
// Install the C# / .NET helper library from twilio.com/docs/csharp/install
using System;
using Twilio;
using Twilio.Rest.Verify.V2;
class Program
{
static void Main(string[] args)
{
// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");
TwilioClient.Init(accountSid, authToken);
var service = ServiceResource.Create(friendlyName: "My First Verify Service");
Console.WriteLine(service.Sid);
}
}
Reported in Slack.
If you download the SIP quickstart (twilio serverless:init acme --template="sip-quickstart"
) and set the DEFAULT_SIP_USER_PASSWORD
to something that does not pass the validation for SIP credentials (minimum of 12 characters, contain at least 1 digit, and have mixed case) then the registration fails with a 403 error.
Initial suggestion is that the .env
file describes the password requirements.
A 403 error isn't particularly useful for users here, so I would suggest we also ensure that the error message when using an incorrect password is more user friendly and directs them to fill in a suitable password.
@craigsdennis what do you think?
Migrate the Call Me Twimlet to an equivalent Twilio Function Template.
WHEN a phone call is incoming
forward the call to the forwarding number PhoneNumber
with:
<Number>
's url
configured to play a message to the recipient using the undocumented Whisper Twimlet with the optional Message
parameterTimeout
seconds, or 20 seconds by defaultDial
flag set to true
FailUrl
parameterPlay a message to the recipient, requesting to press a digit to accept the call.
If a key has been pressed by the recipient, bridge the call.
(that's the idea at least, but in practice, the call is bridged whether a digit has been pressed or not)
WHEN the forwarded call ends (Dial
flag is set to true
)
IF the status of the call DialStatus
is answered
or DialCallStatus
is completed
OR the fallback URL FailUrl
is empty
THEN hang up
ELSE redirect to the fallback URL FailUrl
.
Still new to all this, so forgive my ignorance please.
I copied /forward-message-sendgrid.protected.js into a new Twilio function and changed the configurations to forward to my cell. When I try to test it out, my phone does ring (yay) but then it reads "an application error has occurred" and I can't speak to anyone...
Here's the error:
Msg | "An attempt to retrieve content from https://webhooks.twilio.com/v1/Accounts/AC1565008ccbd4bde9aa65d66245faf38a/Flows/?Dial=true returned the HTTP status code 404" |
---|---|
sourceComponent | "12000" |
ErrorCode | "11200" |
httpResponse | "404" |
url | "https://webhooks.twilio.com/v1/Accounts/AC1565008ccbd4bde9aa65d66245faf38a/Flows/?Dial=true" |
LogLevel | "ERROR" |
Any idea what I'm doing wrong here?
Hey everyone,
I am facing an issue with the video sample while validating the passcode. I just got the code without any changes.
On local, it runs fine (node 12.22.4 that is the same version live).
When I deploy, I get an error while typing the correct passcode.
I logged the variables, and they are the same.
Any ideas of what I can debug on this case?
Thanks!
Migrate the undocumented Whisper Twimlet to an equivalent Twilio Function Template.
Gather a single digit, requested:
Message
, if it starts with http
Message
, if any, using an English voicePress any key to accept.
IF the HumanCheck
flag is set
AND no digit has been entered
(gather times out after waiting for 5 seconds more after the end of the message)
THEN hang up
WHEN a digit has been entered (Digits
parameter is set and non-empty)
THEN accept the call (return an empty document)
The link in the template for "license" in
I acknowledge that all my contributions will be made under the project's license.
points to https://github.com/twilio-labs/function-templates/LICENSE - which is a 404. Should probably be https://github.com/twilio-labs/function-templates/blob/main/LICENSE
example: #157
For the sms-notifications
template, we have a UI where customers can enter multiple phone numbers to send SMS to. However, it requires you to hit Return after entering a phone number in order to "confirm" it before sending out the SMS. This is described in the helper text but people tend to miss it.
function-templates/sms-notifications/assets/index.html
Lines 62 to 69 in f49b46d
We should either add a more descriptive button next to the phone number input that says "add", "confirm number as recipient" or something similar or add to the JavaScript to check if there is a valid phone number in the recipient form that hasn't been confirmed when an SMS is attempted to be send.
Migrate the Hold Music Twimlet to an equivalent Twilio Function Template.
IF no S3 Bucket, Bucket
, has been provided
OR it was an empty string
THEN say in an English voice An S 3 bucket is required.
ELSE continue to step 2
Use cURL to fetch the contents of the S3 bucket at the URL:
http://
Bucket
,.s3.amazonaws.com
IF the download fails
THEN say in an English voice Failed to fetch the hold music.
ELSE continue to step 3
Parse the S3 Bucket as XML
FOR EACH child <Contents>
element found in the root XML element
IF the text in <Key>
element is a URL ending with .mp3
or .wav
or .ul
THEN add the URL to the list of songs to play
IF the list of songs to play is empty
THEN say in an English voice Failed to fetch the hold music.
ELSE continue to step 4
Shuffle the list of songs to play.
FOR EACH song to play
http://
Bucket
,.s3.amazonaws.com/
Message
, has been providedMessage
, if it starts with http
Message
using an English voiceWHEN the end of the playlist is reached
redirect the flow to go back to step 1
I'm trying to get the Funlet Simulring working. I'm getting an error at the "split" function (full error copied below).
I've copied in the code, added two numbers to line 37:
phoneNumbers: [+1xxx,+1xxx],
I also have to environmental variables set:
TWILIO_VOICE_WEBHOOK_URL=/funlet-simulring and:
FUNLET_SIMULRING_PHONE_NUMBERS=+1xxx,+1xxx
I've tried editing line 145 since "FUNLET_FINDME_PHONE_NUMBERS" seems to me to not be defined anywhere. But if I define it my just hard coding in my forwarding numbers, I can get the function to play, but it doesn't forward anywhere.
Any help y'all can offer is appreciated! I'm at a total loss.
Error: {"message":"Cannot read property 'split' of undefined","name":"TypeError","stack":"TypeError: Cannot read property 'split' of undefined\n at getPhoneNumbers (/var/task/handlers/ZNxxx.js:145:37)\n at Object.exports.handler (/var/task/handlers/ZNxxx.js:387:29)\n at Object.exports.handler (/var/task/node_modules/runtime-handler/index.js:339:10)\n at Runtime.exports.handler (/var/task/runtime-handler.js:17:17)\n at Runtime.handleOnceNonStreaming (/var/runtime/Runtime.js:74:25)"}
It would be nice to have an example template that shows how an MMS powered ticketing could work.
Hi ${name}! Thanks for registering for the happy hour event. Here's your ticket!
via Twilio Messaging (SMS with mediaUrl
property)index.html
, main.js
and styles.css
in an assets/
directory for the event websiteissue-ticket.js
in functions/
to send out the MMSgenerate-qr-code.js
as functions/
that receives data in a request parameter to generate a QR code and return it as an image data. (to be used mediaUrl
prop of the MMS)The README formats of the various templates started diverging. I would like to propose that we standardize the format. I think @robinske's verify
template has a good structure to act as a starter. It's short and explains both customization as well as usage/how to get started. https://github.com/twilio-labs/function-templates/tree/master/verify
This will also allow us to better integrate the README in the future in other tools.
For any additional info we could have docs/
folders with additional markdown files.
@philnash what do you think?
Migrate the Simple Menu Twimlet to an equivalent Twilio Function Template.
Gather 1 or more digits based on the number of entries in the menu
(1 digit for 1-9 entries, 2 digits for 10-99 entries, ...)
requested:
Message
, if it starts with http
Message
using an English voiceIF no digit was pressed
THEN go back to stage 1
WHEN one or several digits have been pressed (Digits
parameter is set)
IF the number in Digits
corresponds to the key of one of the Options
array
THEN redirect to the URL found in the value of the corresponding entry of Options
ELSE (no matching entry is found)
say in an English voice: I'm sorry, that wasn't a valid option.
and go back to stage 1
I would like to contribute to this Repo by adding a template that sends Serverless Emails using SendGrid
I think we should invest in some automation that keeps the dependencies safe.
Right now we can use Dependabot to keep top level dependencies up-to-date but not the nested ones for the templates themselves. My suggestion is the following:
devDependency
for the root package.json
Dependabot
it will automatically be mergedpackage.json
and update all the nested package.json
accordinglypush
to master that will run the script from (3) and commit any needed changesPossible concerns/issues:
package-lock.json
updates? Should we be concerned or only rely on semver. Most of those are nested deps anyways meaning we don't have control over themWe should either fix this action or remove it.
Also we should update the .owners
file to remove jmulcahey-twilio
.
Hello,
I am trying to use the "verify" template in order to add phone validation in my application. Unfortunately, I cannot find the css elements and the code behind them in the project.
For example, if I want to use the <div class="form-group phone-input">
in order to add the animated flag for each country in that list, where can I find the code behind this css?
Thank you in advance
The default .env file has WORK_WEEK* twice, not WORK_HOUR_* for the second configurations.
https://github.com/twilio-labs/function-templates/blob/master/voicemail/.env
As mentioned in #18 we should be improving the test harness. I think we should be leveraging parts of the twilio-run
tool for this since it is already putting effort in simulating the Twilio Runtime and therefore provides the right globals etc.
That way we only need to maintain one implementation to stay in sync with the actual Runtime.
We need lots more of these!
If a MMS is sent without any text content, the forward-message-sendgrid
will result in a 500 error. At a minimum, it should not error out. Ideally, the attached media would be included as attachments.
Hello!
I'm trying to use the simulring funlet by pasting the js code into twilio Functions and changing the parameters in the script. I then link the phone number to this function directly when it receives an incoming call.
I'm able to ring more than one phone but whenever that call is answered, I get an error message letting me know that I should check the debugging console for more info.
When I check the debugging console, the error message reads as follows:
An attempt to retrieve content from https://wisteria-wolverine-2937.twil.io/?Dial=true returned the HTTP status code 404
I've been racking my brain around this issue for the past few days and am almost certain that I'm missing something critical. Please let me know what you think!
Best,
Erin
Hello, I built the verify sample app using the twilio cli and noticed that the scaffolded app isn't working. I get the following error message; SyntaxError: Unexpected token o in JSON at position 1
.
The check-verify-endpoint is expected to return a JSON but it returns an object, so return response.json()
fails. See
function-templates/verify/assets/index.html
Line 172 in 20781ed
I believe this could be fixed like so:
fetch('./start-verify', {
method: 'POST',
body: data
})
.then((response) => {
const content = $('.result-message')
content.empty()
return response
})
.then((response) => {
if (response.ok) {
$('#form-error').empty()
$('.modal').modal('show')
console.log('Successfully sent token.')
} else {
showVerificationStartError(
`${response.statusText} <a href="${response.statusText}">[more info]</a>`
)
}
})
.catch((err) => {
console.log(err)
showVerificationStartError('Error starting verification.')
})
Same error happens with the check-verify
endpoint here:
function-templates/verify/assets/index.html
Line 204 in 20781ed
This could be fixed like so:
fetch('./check-verify', {
method: 'POST',
body: data
})
.then((response) => {
debugger
if (response.ok) {
showVerificationStatus('success', 'Verification success')
$('#verification_code').val('')
} else {
showVerificationStatus('danger', 'Verification failed')
$('#verification_code').val('')
}
})
.catch((err) => {
console.log(err)
showVerificationStatus('danger', 'Something went wrong!')
$('#verification_code').val('')
})
Cheers
This comand
twilio serverless:init example --template=video && cd example
ends with
✔ Creating project directory
✔ Creating project directories and files
✖ The template "video" doesn't exist
Migrate the Voicemail Twimlet to an equivalent Twilio Function Template.
Play the voicemail message, either:
Message
, if it starts with http
Message
, if any, using an English voicePlease leave a message after the beep.
Record the voicemail and optionally, request its English transcription if Transcribe
parameter is set to true
, by setting:
transcribe
parameter to true
transcribeCallback
to the script URL with the required parameter Email
, to trigger stage 3 at the end of the transcription (otherwise, the transcription is stored without notification)WHEN a recording has completed ( RecordingUrl
is set)
Say Thanks. Good bye.
in English, then hang up.
IF no transcription has been requested (Transcribe
is not set to true
)
THEN send an email in English to the email address Email
, including:
RecordingUrl
, with the extension .mp3
addedA request to the
RecordingUrl
will return a recording in binary WAV audio format by default. To request the recording in MP3 format, append ".mp3" to theRecordingUrl
.
— https://www.twilio.com/docs/voice/twiml/record#attributes-action-parameters
WHEN an optional transcription has completed (TranscriptionStatus
is set)
send an email in English to the email address Email
, including:
TranscriptionText
, if TranscriptionStatus
is completed
RecordingUrl
, with the extension .mp3
addedThis script will soon break, as Twilio announced "Sale Notify. On October 24, 2022 we made the decision to end of sale Notify. No new customers may onboard to this product. The Notify API will sunset in 2023"
A link takes you to their notification that they ending the life of this service.
Concern because I was planning to use this script, as it's part of the Code Exchange, but now my hands are tied and I don't have a quick off-the-shelf solution.
Migrate the Conference Twimlet to an equivalent Twilio Function Template.
WHEN a phone call is incoming
IF a password, Password
, has been set for the conference
AND no digits, Digits
, have been entered or the digits entered do not match the password
THEN gather a number of digits, computed as the maximum of 3 and the length of the expected password, requested by saying in an English voice Please enter your conference pass code
, then redirect the flow back to stage 1
ELSE continue to stage 2
WHEN a phone call is incoming
AND the correct password has been provided or no password has been set
IF a list of moderators, Moderators
, has been provided
AND the flag EnableSmsNotifications
has been set
AND the calling number is not in the list of moderators (and neither is the recipient's number!)
THEN invite each moderator to the conference by sending an SMS with a text in English including the phone number of the caller.
Welcome the caller to the conference:
Message
, if it starts with http
Message
using an English voiceYou are now entering the conference line.
Join the conference room with the given name, Name
, or a generated name created from an MD5 hash of the welcome message Message
, if any, and the list of moderator phone numbers, if any, configuring:
waitUrl
, to the URL provided in Music
, if it starts with http
, or the URL of the Twimlet Hold Music with the Bucket
parameter set to com.twilio.music.
followed with the genre in Music
parameter, if the genre is one of classical
, ambient
, electronica
, guitars
, rock
or soft-rock
, with the method waitMethod
set to GET
in both casesstartConferenceOnEnter
to true
if the caller (or the recipient!) is a moderator and 'false' otherwiseIssue:
The latest 'got' release (v12.6.0) is currently a native ES module and no longer provides a CommonJS export. Currently, the "forward-message-sendgrid" has the older 'got' release (v6.7.1) in its dependencies. While most users tend to upgrade the library in the dependencies to the latest version, they will face the following error.
Error [ERR_REQUIRE_ESM]: require() of ES Module /var/task/node_modules/got/dist/source/index.js from /var/task/handlers/ZNXXXXXXXXXXXXXXXXXXXXXXXXXXX.js not supported. Instead change the require of index.js in /var/task/handlers/ZNXXXXXXXXXXXXXXXXXXXXXXXXXXX.js to a dynamic import() which is available in all CommonJS modules
However, due to Twilio Functions currently does not support ES modules, using the dynamic import() will produce an error too.
Solution:
It is advisable to migrate this example to sendgrid-nodejs (@sendgrid/mail) as it is officially maintained by the Sendgrid team.
PR:
Migrate the Echo Twimlet to an equivalent Twilio Function Template.
Respond with the contents of the Twiml
parameter.
Especially for new folks adding tests for these Functions can be confusing. We should document some basic best practices and resources that people can use to learn how to write the tests for the Functions they are adding. Especially if they involve network requests.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.