Giter Club home page Giter Club logo

api-snippets's Introduction

Code snippets for the Twilio API documentation

Build Status

Guidelines

  1. Snippets should use environmental variables to store user account information instead of placeholders. For example (in NodeJS):

    accountSid = process.env.TWILIO_ACCOUNT_SID
    

    Instead of:

    accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    

    As the latter impose a high security risk for users who push their own credentials on public repositories.

  2. Critical user account information that should be stored on environmental variables is:

    • Account SID
    • Sub accounts SIDs
    • Authentication Token
    • API key SID
    • API key Secret

    Any other information such as Call SID, etc. can have placeholders on them:

    Call SID:    CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    

    In the case of phone numbers, the following should be used:

    Destination Phone Number: +15558675310
    From/Twilio Number: +15017122661
    
  3. Snippet file names are important. A snippet's file extension is the only way to mark them for a specific language. This is important because the language will be visible on the docs. Also, you must mark snippets with the twilio-client version that is used in that particular snippet.

    For example, a java snippet that uses twilio-java v7.x should be named as: snippet-example-1.7.x.java

    The same applies to the rest of languages and library versions, and this is the list of currently supported languages and versions:

    snippet-example-1.6.x.java
    snippet-example-1.7.x.java
    snippet-example-1.2.x.js
    snippet-example-1.5.x.js
    snippet-example-1.7.x.rb
    snippet-example-1.6.x.cs
    snippet-example-1.4.x.php
    snippet-example-1.8.x.php
    snippet-example-1.9.x.py
    

    And the full structure should look like this:

    rest/
    |-- resource-example/
        └── snippet-example-1/
            |-- output/
            |   └── snippet-example-1.json
            |-- snippet-example-1.7.x.java
            |-- snippet-example-1.<sdk-version>.x.<language>
            |-- snippet-example-1.json.curl
            |-- snippet-example-1.xml.curl
            └── meta.json
    

    Client version is important, as that is how the test harness knows which version of the client it should use for testing.

Continuous Integration

All snippets are run in a container-based environment for each language (see .travis.yml file), so the first check we do is for syntax error.

There're two kind of snippets we test:

  • API/REST snippets: For these cases we only check syntax error. But, these snippets also do a request to Twilio's endpoints, so we mock this behaviour using a fake API server.

    Note: The test doesn't check if the http request body is well formed to do what the intended snippet is supposed to do, e.g., if you have a snippet doing resource.update(propA=True), but the expected result is to update propB, the test may go green because there's no syntax error. That's because some attributes are optional to update, so the request body may or may not has the parameters needed to update the resource according to the expected result.

  • TwiML snippets: When running TwiML snippets, the snippets should print the xml result to the standard output, so we can capture that output and compare it with the expected xml sample. We read this /output/sample.xml file which is placed in the same folder of the snippet.

How to mark specific folders as testable

If you want a snippet folder to be tested, there are two ways to mark it as testable:

  1. Using a meta.json file: This file is required and must live in all snippet folders, inside you can enable its specific folder for testing, adding "testable": true like so:

    {
      "title": "Snippet title",
      "type": "server",
      "testable": true
    }
  2. Using a test.yml file: This file is optional and can live inside any folder, it's used to specify a deep recursive testing for all folders inside. So, if the marked directory contains several snippets, all of them will be marked as testable recursively. You just need to add testable: true to the file like so:

    testable: true

Notes:

  • For testing TwiML snippets the option available is:

    meta.json -> "test_output": true
    test.yml -> test_output: true
    

    This will compare the output of the snippet with the output/sample.xml file inside the same directory of the snippet.

  • You can mark a directory or a snippet to be not testable too.

    meta.json -> "testable": false
    test.yml -> testable: false
    

    This way, you can mark snippets or directories to be tested or not, by exception.

  • For a snippet to be testable, it has to contain the basic things a program in that language should have. For example in Java, the code snippet should have a public class and a main method in it.

  • Specific dependencies are supported for snippets. If a new dependency is introduced, the testing scripts should be modified to support it.

Local Snippet Testing

The next steps describe how to run the snippets test locally in a UNIX based operating system (examples will be provided for Debian based Linux distributions and OSX using Homebrew). This has not been tested in a Windows OS.

Setting Up the Environment

Make sure you have the following dependencies installed on your system.

  1. Install Node.js. The best option for this is to use nvm

    curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.2/install.sh | bash \
    export NVM_DIR="$HOME/.nvm" \
    [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" \
    nvm install --lts
    npm install
  2. Install Python and PIP.

    • On Linux:
    sudo apt-get install python-pip python2.7-dev build-essential \
    sudo pip install --upgrade pip
    • On OSX:
    brew install python

    Once you have python and pip ready, run the command below

    pip install -r requirements.txt
    
  3. Install JDK8 and Gradle. The best option for this is to use sdkman

    curl -s "https://get.sdkman.io" | bash \
    source "$HOME/.sdkman/bin/sdkman-init.sh" \
    sdk install java \
    sdk install gradle
  4. Install PHP 5 with CURL.

    • On Linux:
    sudo add-apt-repository ppa:ondrej/php -y
    sudo apt-get update
    sudo apt-get install -y --force-yes php5.6
    • On OSX:
    brew install php56

    Once you have php ready, please install Composer

    curl -sS https://getcomposer.org/installer | \
    sudo php -- --install-dir=/usr/local/bin --filename=composer
  5. Install Ruby and RubyGems.

    curl -sSL https://get.rvm.io | bash -s stable --ruby
  6. Install MonoDevelop.

    sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF \
    echo "deb http://download.mono-project.com/repo/debian wheezy main" | sudo tee /etc/apt/sources.list.d/mono-xamarin.list \
    sudo apt-get update \
    sudo apt-get install mono-complete -y
    • On OSX:
    brew install mono

Install Language Dependencies

The testing and installation scripts use ruby. Before installing language dependencies you need to install the following gems:

gem install json colorize nokogiri

You can use the following command to install language dependencies, which will download the latest version of the helper libraries for each language:

ruby tools/snippet-testing/model/dependency.rb

Note: That file specifies the latest version for every helper library for each language, but for java the files to specify the versions are located in: tools/snippet-testing/language_handler/file-templates/build.<version>.gradle where <version> should be 6 or 7.

Another option is to use the snippet_tester.rb file and pass the -i flag, this will try to install whatever dependency is needed before running the tests:

ruby tools/snippet-testing/snippet_tester.rb -i

Note: This will also install missing dependencies before running the tests. sudo will be used within the dependency installation script so you might need to enter your password. DO NOT run the whole script with sudo as it would install dependencies for the wrong user.

Run the Tests

  1. Clone and run the fake-api server in a different terminal session.

    git clone [email protected]:TwilioDevEd/twilio-api-faker.git \
    cd twilio-api-faker \
    sudo gradle run
  2. Make your system trust the fake server's self signed certificate.

    • On Linux:
    sudo apt-get install ca-certificates \
    sudo cp twilio-api-faker/keystore/twilio_fake.pem /usr/local/share/ca-certificates/twilio_fake.crt \
    sudo update-ca-certificates
    • On OSX: Use the system's keychain to trust the provided certificate in the keystore directory of the fake-api repo. Go here for more information.
  3. Change your hosts file.

    Edit your /etc/hosts file. Add the following entries:

    127.0.0.1 api.twilio.com
    127.0.0.1 chat.twilio.com
    127.0.0.1 fax.twilio.com
    127.0.0.1 ip-messaging.twilio.com
    127.0.0.1 lookups.twilio.com
    127.0.0.1 messaging.twilio.com
    127.0.0.1 monitor.twilio.com
    127.0.0.1 notifications.twilio.com
    127.0.0.1 notify.twilio.com
    127.0.0.1 pricing.twilio.com
    127.0.0.1 preview.twilio.com
    127.0.0.1 sync.twilio.com
    127.0.0.1 taskrouter.twilio.com
    127.0.0.1 video.twilio.com
    127.0.0.1 wireless.twilio.com
    
  4. Make a copy of the .env.example file.

    cp .env.example .env
  5. Set the necessary environment variables.

    Change environment variables in the .env file to match your configuration and then use the source command to export the variables.

    source .env
  6. Finally, run the tests.

    ruby tools/snippet-testing/snippet_tester.rb

    Note: Remember to mark the directories you want to be tested with a test.yaml file. For more information go here.

    You can also specify a directory to be tested (relative or absolute path). If a directory is specified, then the default testing behavior for that directory and everything it contains is true.

    ruby tools/snippet-testing/snippet_tester.rb -d rest/making-calls

api-snippets's People

Contributors

acamino avatar adrianapineda avatar alexdlaird avatar atbaker avatar benparj98 avatar bld010 avatar cskonopka avatar dprothero avatar eliux avatar hortega avatar jefflinwood avatar joliveros avatar juancarlospaco avatar ktoraskartwilio avatar kwhinnery avatar lwilio avatar mcelicalderon avatar mosampaio avatar pkamp3 avatar po5i avatar rbeiter avatar ronualdo avatar sarahcstringer avatar satchkat avatar smendes avatar stern-shawn avatar szolotarjov avatar viktormuller avatar vinwall avatar well1791 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

api-snippets's Issues

Proxy Example Wrong

Fix (#605) you applied to #604 doesn't actually right.
According to latest changes to the library (5.16.4):
https://github.com/twilio/twilio-hp/blob/master/Twilio/Rest/Proxy/V1/Service/Session/ParticipantList.php#L136
Your change should look more like:

$client = new Client($sid, $token);
$session = $client
    ->proxy
    ->services("KSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
    ->sessions("KCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
    ->participants->create("+15558675310",
        array(
            "friendlyName" => "Alice"
        )
    );

From bccff96e10e7760d31fba99f7659dea6b81dae3d Mon Sep 17 00:00:00 2001

From bccff96 Mon Sep 17 00:00:00 2001
From: webtechnicom [email protected]
Date: Thu, 19 Sep 2019 07:53:00 +0200
Subject: [PATCH] Update configure-service-instance-hooks.curl


.../configure-service-instance-hooks.curl | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/ip-messaging/webhook-settings/configure-service-instance-hooks/configure-service-instance-hooks.curl b/ip-messaging/webhook-settings/configure-service-instance-hooks/configure-service-instance-hooks.curl
index 0285a1280..483c87403 100644
--- a/ip-messaging/webhook-settings/configure-service-instance-hooks/configure-service-instance-hooks.curl
+++ b/ip-messaging/webhook-settings/configure-service-instance-hooks/configure-service-instance-hooks.curl
@@ -2,4 +2,8 @@ curl -X POST https://chat.twilio.com/v1/Services/{service sid}
-d 'PreWebhookUrl=https://hooks.yoursite.com/pre-webhooks'
-d 'PostWebhookUrl=https://hooks.yoursite.com/post-webhooks'
-d 'WebhookMethod=POST'
--u '{twilio account sid}:{twilio auth token}'
\ No newline at end of file
+-u '{twilio account sid}:{twilio auth token}'curl -X POST https://chat.twilio.com/v1/Services/{service sid}
+-d 'PreWebhookUrl=https://hooks.yoursite.com/pre-webhooks'
+-d 'PostWebhookUrl=https://hooks.yoursite.com/post-webhooks'
+-d 'WebhookMethod=POST'
+-u '{twilio account sid}:{twilio auth token}'

Originally posted by @webtechnicom in #804 (comment)

Example code for detect channel states is incorrect

The following example code should be onChannel*:

@Override
public void onMessageAdded(Message message) {
Log.d(TAG, "Message added: " + message.getMessageBody());
}
@Override
public void onMessageUpdated(Message message) {
Log.d(TAG, "Message changed: " + message.getMessageBody());
}
@Override
public void onMessageDeleted(Message message) {
Log.d(TAG, "Message deleted");
}

TypeError: source.on is not a function when creating video composition.

The following example doesn't work for me.
https://github.com/TwilioDevEd/api-snippets/blob/master/video/rest/compositions/compose-room/compose-room.3.x.js

Here is the error i receive:

(node:8308) UnhandledPromiseRejectionWarning: TypeError: source.on is not a function
    at Function.DelayedStream.create (...\node_modules\delayed-stream\lib\delayed_stream.js:33:10)
    at FormData.CombinedStream.append (...\node_modules\combined-stream\lib\combined_stream.js:44:37)
    at FormData.append (...\node_modules\form-data\lib\form_data.js:74:3)
    at appendFormValue (...\node_modules\twilio\node_modules\request\request.js:323:21)
    at Request.init (...\node_modules\twilio\node_modules\request\request.js:334:11)
    at new Request (...\node_modules\twilio\node_modules\request\request.js:128:8)
    at request (...\node_modules\twilio\node_modules\request\index.js:53:10)
    at RequestClient.request (...\node_modules\twilio\lib\base\RequestClient.js:73:3)
    at Twilio.request (...\node_modules\twilio\lib\rest\Twilio.js:216:26)
    at Video.Domain.request (...\node_modules\twilio\lib\base\Domain.js:34:22)

Any suggestions?

deleting time range recordings

I need to delete call recordings of time range using twilio node SDK 3.X here is the code I used:

client.recordings
   .each({
      dateCreatedBefore:  '2017-12-30',
      dateCreatedAfter: '2017-11-01',
  }, (recording)=>{
client.recordings(recording.sid).remove();
});

I need a way to know when all the recordings are deleted successfully or some failed .. how can I use Promise.all with client.recordings.each

Undefined parameters are used in `Conference Instruction` sample code

Sample code: https://github.com/TwilioDevEd/api-snippets/blob/master/rest/taskrouter/reservations/conference/example-1.5.x.php#L26
Document: https://www.twilio.com/docs/taskrouter/api/reservations#code-conference-instruction

dequeueFrom is not mentioned in the document, but it is used in the sample code above.
dequeueFrom is not part of the Conference Participants API.

Since we do not know the parameters for using Conference in TaskRouter,
If possible, I hope that you can modify the sample code including the Conference Participants API.

SIM800Twilio example not working ...

I've got a SIM800L powered up and working with a 3.3v Pro Mini.

I've written my own code to send the specific AT commands to the SIM800L, and it works perfectly ... I get the commands to Twilio and on to my application.

I wanted to use the SIM800Twilio library and example from here so that I'm not re-writing all of this functionality. I installed it and ran it. And it doesn't work. :-(

https://github.com/TwilioDevEd/api-snippets/tree/master/wireless/quickstart/m2m_commands_arduino_sim800

There is not much debug output, but it does initialize ... says that it is sending the SMS ... and then says it's waiting for incoming SMS. BUT ... nothing ever shows up at Twilio ... and so it isn't working.

Thoughts on recommended ways to debug this and get it working? Is this supported code going forward or should I locate and adapt an alternative library?

TypeError: tc.messagingClient.getSubscribedChannels is not a function

Hello Team,

I have created Twilio chat client.

tc.messagingClient = new Twilio.Chat.Client(token);

Now,I am accessing the getSubscribedChannels function.

tc
      .messagingClient
      .getSubscribedChannels()
      .then((paginator)=> {

        console.log(paginator);
        for (i = 0; i < paginator.items.length; i++) {
          var channel = paginator.items[i];
          console.log('Channel: ' + channel.friendlyName);
        }
      },(error)=>console.log(error));

But I am getting the error
TypeError: tc.messagingClient.getSubscribedChannels is not a function

I am using below js files related for Twilio.

script(src="//media.twiliocdn.com/sdk/js/common/releases/0.1.5/twilio-common.js")
script(src="//media.twiliocdn.com/sdk/js/chat/releases/0.11.1/twilio-chat.js")

I have checked the inherited function in Twilio chat client object,but the getSubscribedChannels function is not listed there event.
twilio

How to Generate a Programmable Video Access Token for Android app.?

private void retrieveAccessTokenfromServer() {
Ion.with(this)
// Make JSON request to server
.load("http://localhost:8080/token.php")
.asJsonObject()
.setCallback(new FutureCallback() {
@OverRide
// Handle response from server
public void onCompleted(Exception e, JsonObject result) {
if (e == null) {
// The identity can be used to receive calls
String identity = result.get("identity").getAsString();
VideoActivity.this.accessToken = result.get("token").getAsString();
Log.i(TAG, "Token found: " + accessToken);
} else {
Log.i(TAG, "error fetching token from server");
Toast.makeText(VideoActivity.this,
R.string.error_retrieving_access_token, Toast.LENGTH_SHORT)
.show();
}
}
});
}

Whats this Url "http://localhost:8080/token.php" ? . Should i get server and config it ?

`interpret_as` attribute incorrectly used in Ruby SSML example

require 'twilio-ruby'
response = Twilio::TwiML::VoiceResponse.new
response.say(voice: 'Polly.Joanna', message: 'Hi') do |say|
say.break(strength: 'x-weak', time: '100ms')
say.emphasis('Words to emphasize', level: 'moderate')
say.p('Words to speak')
say.add_text('aaaaaa')
say.phoneme('Words to speak', alphabet: 'x-sampa', ph: 'pɪˈkɑːn')
say.add_text('bbbbbbb')
say.prosody('Words to speak', pitch: '-10%', rate: '85%', volume: '-6dB')
say.s('Words to speak')
say.say_as('Words to speak', interpret_as: 'spell-out')
say.sub('Words to be substituted', alias: 'alias')
say.w('Words to speak')
end
puts response

As of twilio-ruby 5.22.0 The say_as method expects the interpret-as attribute to be passed in ruby as interpretAs and not interpret_as.

docs/fax/receive - snippet with res.body.MediaUrl should be req.body.MediaUrl

On https://www.twilio.com/docs/fax/receive, right hand side Node.js example contains this:

// Define a handler for when the fax is finished sending to us - if successful,
// We will have a URL to the contents of the fax at this point
app.post('/fax/received', (req, res) => {
  // log the URL of the PDF received in the fax
  console.log(res.body.MediaUrl);

  // Respond with empty 200/OK to Twilio
  res.status(200);
  res.send();
});

That matches up with line 29 in basic-receive.js.

Sending a fax to a number on our Twilio account (that has the webhook connected to a running Express server with this code) results in TypeError: Cannot read property 'MediaUrl' of undefined on that line. While req.body contains keys FaxSid, ApiVersion, MediaUrl, NumPages, FaxStatus, To, From, AccountSid, RemoteStationId

Suggestion: Show how to send to more than one recipient

The example: api-snippets/notifications/sms-quickstart/send-notification/send-notification.curl is useful. But it would be really helpful (if it is possible) to show how to send to more than one recipient.

Going from 1 to 2 is hard to figure. (Do I need curly braces around Identity to repeat it? Commas? Semicolons?)

"ToBinding" does not work as shown in the CURL example

I cannot get his example to work: notifications/sms-quickstart/send-notification-to-number/send-notification-to-number.curl

Here is what my call looks like:

 curl -X POST "https://notify.twilio.com/v1/Services/IS<My Private Value Here>/Notifications" --data-urlencode 'ToBinding={"binding_type":"sms", "address":"+18011234567"}' --data-urlencode 'Body=Test Message' -u 'AC1828d273602b76952c34368876b889a9:<My Token Here>'

When I run that, I get this response:

{  
   "code":20001,
   "message":"Can not convert incoming parameters to Notification object: Parameter 'ToBinding' is invalid",
   "more_info":"https://www.twilio.com/docs/errors/20001",
   "status":400
}

The key part there is "Parameter 'ToBinding' is invalid". But I have checked it letter by letter so many times. It is exactly like the example.

NOTE: I tried it first using "bindings" stored by Twilio. I seem to have no problems with that method. This command sends the text message just fine:

curl -X POST "https://notify.twilio.com/v1/Services/IS<My Private Value Here/Notifications" --data-urlencode 'Identity=00000001' --data-urlencode 'Body=Test Message' -u 'AC1828d273602b76952c34368876b889a9:<My Token Here>'

Note: I posted this on Stack Overflow and someone there suggested I ask the Twilio developers.

composer.json in root of project

Why is this located here? it would seem to be a concern of the test harness used to execute the snippets, and not something globally required for the project.

Problem With making outgoin call

i have the next code sometimes the call go fine, but a lot of times them got error code 13224 , and it is the same code, i do not change anything.

<?php
// Require the bundled autoload file - the path may need to change
// based on where you downloaded and unzipped the SDK
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require __DIR__ . '/twilio-php-master/Twilio/autoload.php';
use Twilio\Rest\Client; 
$account_sid = 'SID'; 
$auth_token = 'token 
$client = new Client($account_sid, $auth_token);
try { // Initiate a new outbound call
    $call = $client->account->calls->create(
        // Step 4: Change the 'To' number below to whatever number you'd like 
        // to call.
        "+526241258619",
        // Step 5: Change the 'From' number below to be a valid Twilio number 
        // that you've purchased or verified with Twilio.
        "+14152338694",
        // Step 6: Set the URL Twilio will request when the call is answered.
        array("url" => "http://demo.twilio.com/welcome/voice/")
    );
    echo "Started call: " . $call->sid;
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

PHP Webhook snippet produces wrong query string

The PHP snippet provided to verify the signature of an incoming webhook payload uses http_build_query to generate a query string, which ignores any null value in an array.
This returns a query string that is missing some keys that were provided in the payload, generating a wrong signature down the line.

I lost a few hours trying to find out why my signatures were not matching. I eventually found out by running the Node.js snippet and comparing the generated parameter strings.

The workaround is to implement http_build_query yourself. I ended up using this https://stackoverflow.com/a/16451823/11178709

Twillio outbound caller ID issue

I have to add user as an outbound caller in to my twillio account. The following code is unsing to add a user to my account
` const accountSid = 'xxxxxxxxxxxxxxxxxxxxxxxxx';
const authToken = 'xxxxxxxxxxxxxxxxxxxxxxxxxx';
const client = require('twilio')(accountSid, authToken);

client.outgoingCallerIds
.create({
friendlyName: 'My Home Phone Number',
phoneNumber: '+14158675309',
})
.then((callerId) => process.stdout.write(callerId.sid)); `
but its giving an error message like

.create({
^
TypeError: client.outgoingCallerIds.create is not a function
at Object. (/home/jose/test/twillio/callerid.js:6:4)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:390:7)
at startup (bootstrap_node.js:150:9)
at bootstrap_node.js:505:3

Validate Twilio Request Attribute raw url

Referring to this code snippet, line 34

            var requestUrl = request.RawUrl;

was giving me everything following the host (www.google.com/x/y/z, only returning /x/y/z)

I changed to

var requestUrl = request.Url.AbsoluteUri;

in order to get the validation to work

Using nuget packages

Microsoft.AspNet.Mvc 5.2.3
Twilio 5.14.0
Twilio.Aspnet.Mvc 5.9.7

AttributeError: 'Client' object has no attribute 'fax'

Hello,

I'm using twilio==6.1.0 and Python 3.5.0. I'm using the code from basic-send.6.x.py and I'm getting an attribute error. Not really sure what's up? Do I have to use a lower version of twilio? Did the syntax change? MMS and SMS are still fine.

Thanks.

Create subaccount response differences

Today I've update from 2.x to 3.6.x. After that I had to update my code to reflect the responses, though according to the documentation it shouldn't change.
Documentation response:

{
    "sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "friendly_name": "Submarine",
    "auth_token": "redacted",
    "date_created": "Tue, 25 Jan 2011 19:24:40 +0000",
    "date_updated": "Tue, 25 Jan 2011 19:25:02 +0000",
    "status": "active",
    "subresource_uris": {
        "available_phone_numbers": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/AvailablePhoneNumbers.json",
        "calls": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls.json",
        "conferences": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Conferences.json",
        "incoming_phone_numbers": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/IncomingPhoneNumbers.json",
        "notifications": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Notifications.json",
        "outgoing_caller_ids": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/OutgoingCallerIds.json",
        "recordings": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Recordings.json",
        "sandbox": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Sandbox.json",
        "sms_messages": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/SMS/Messages.json",
        "transcriptions": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Transcriptions.json"
    },
    "type": "Full",
    "uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json"
}

Actual response:

authToken: 'XXXXX',
  dateCreated: 2017-08-09T02:36:41.000Z,
  dateUpdated: 2017-08-09T02:36:43.000Z,
  friendlyName: 'XXXXX',
  ownerAccountSid: 'ACXXXX,
  sid: 'ACXXX',
  status: 'active',
  subresourceUris:
   { applications: '/2010-04-01/Accounts/ACXXXX/Applications.json',
     authorized_connect_apps: '/2010-04-01/Accounts/ACXXXX/AuthorizedConnectApps.json',
     available_phone_numbers: '/2010-04-01/Accounts/ACXXXX/AvailablePhoneNumbers.json',
     calls: '/2010-04-01/Accounts/ACXXXX/Calls.json',
     conferences: '/2010-04-01/Accounts/ACXXXX/Conferences.json',
     connect_apps: '/2010-04-01/Accounts/ACXXXX/ConnectApps.json',
     incoming_phone_numbers: '/2010-04-01/Accounts/ACXXXX/IncomingPhoneNumbers.json',
     media: '/2010-04-01/Accounts/ACXXXX/Media.json',
     messages: '/2010-04-01/Accounts/ACXXXX/Messages.json',
     notifications: '/2010-04-01/Accounts/ACXXXX/Notifications.json',
     outgoing_caller_ids: '/2010-04-01/Accounts/ACXXXX/OutgoingCallerIds.json',
     queues: '/2010-04-01/Accounts/ACXXXX/Queues.json',
     recordings: '/2010-04-01/Accounts/ACXXXX/Recordings.json',
     sip: '/2010-04-01/Accounts/ACXXXX/SIP.json',
     sms_messages: '/2010-04-01/Accounts/ACXXXX/SMS/Messages.json',
     transcriptions: '/2010-04-01/Accounts/ACXXXXX/Transcriptions.json',
     usage: '/2010-04-01/Accounts/ACXXXX/Usage.json' },

notice how key naming changes.

Voice call list code example missing parameters

The current (v5) Twilio Voice API documentation about filtering Call List, example 4.5 (Ruby) states:

Only show completed calls started between midnight Jul 04th, 2009 and midnight Jul 06th, 2009.

Unfortunately, there are NO parameters given, so the code would not apply any of these filters.

I tried to be helpful by initiating a PR fixing this issue but observe that the CI appears to have been failing for some time for reasons unrelated to my change, and so am uncertain my contribution may be accepted.

screen shot 2018-01-30 at 10 57 28 am

PHP Snippets status

Hello,

I am curious about the state of the snippets for the PHP lang: is it up to date?

I've tried to follow suggestions from https://www.twilio.com/docs/api/rest/messaging-services, for example:

$service = $twilio->messaging->v1->services->create(
  "My First Service",
  array('statusCallback' => "http://requestb.in/1234abcd")
);

And it doesn't seem there is messaging, there is messages. Also, I wasn't able to find Services there...

Is this a correct repo to look at - https://github.com/twilio/twilio-php ?

Thank you!

create() got an unexpected keyword argument 'ttl'

I was copy/pasting some Python code from the Sync docs and it seems that the code in this snippet is erroneous.

When running the following:

list_instance = client.sync \
    .services("XXXXXXXXXXXXXXXXXXXXXXXX") \
    .sync_lists \
    .create(unique_name="ExampleList", ttl=1814400)

I get this output:

(venv) chranj@~/Documents/twilio-sync-tests$ python create_list.py 
Traceback (most recent call last):
  File "create_list.py", line 13, in <module>
    .create(unique_name="QuestList", ttl=1814400)
TypeError: create() got an unexpected keyword argument 'ttl'

Improper use of const in C# Sms Sample

Source: https://github.com/TwilioDevEd/api-snippets/blob/4715c8eb78743eb7230190043ac9922f312782b4/rest/messages/generate-twiml-dynamic-sms/generate-twiml-dynamic-sms.5.x.cs
Documentation: https://www.twilio.com/docs/sms/tutorials/how-to-receive-and-reply-csharp

Line 13:
const string requestBody = Request.Form["Body"];

It appears that the const keyword is being used here as if in javascript rather than C#.

Request.Form["Body"] is not a compile time constant in any scenario I can imagine, and a compiler error will be thrown.

It should be changed to string requestBody... or simply to var requestBody

Out of date import in "List all Phone Numbers in a Service" 7.x example

Hello, I was looking at this example to get a list of phone numbers for a given messaging service sid and noticed the import used (import com.twilio.rest.messaging.v1.service.PhoneNumber; ) does not exist in current 7.x.x Twilio versions. The most recent version I see it in is 5.7.1. @hortega (since you added the mentioned example,) would you know if there is an equivalent class in Twilio 7.x.x, and, if there is, where to find it?

Issue in old version of Twilio.Pricing in NuGet repository

Attempting to execute the code snippet get-messaging-country.cs in Visual Studio (Community Edition).

When installing Twilio.Pricing the following dependencies was solved for the framework net452:

  • RestSharp, version 105.2.3
  • Twilio, version 4.7.1
  • Twilio.Lookups, version 1.1.0
  • Twilio.Pricing, version 1.1.0

This code has 2 concrete problems:

  1. The method GetMessagingCountry is not available for the instance of PricingClient.
  2. The type InboundSmsPrice is not available.

virtualbox_ie10 - win7_06_04_2016_10_30_04

Later on I checked if the method GetMessagingCountry actually exist in the current codebase. Seems like the aforementioned method is available there.

What do you think about updating the package in NuGet to reflect the latest changes you made?

Documentation confusion with certain date filter parameters

Only noticed this with calls and messages endpoints but the documentation states that date filters can take in equality values for custom date ranges. For example, messages listing

https://www.twilio.com/docs/api/rest/message#list-get

allows DateSent<=YYYY-MM-DD and DateSent>=YYYY-MM-DD filters and calls listings

https://www.twilio.com/docs/api/rest/call#list-get

allows StartTime<=YYYY-MM-DD and StartTime>=YYYY-MM-DD

I'm not sure if this was deprecated or something but I had code that relied on these and I just realized that something was off and the wrong data was being returned now. I then checked some docu examples and the API explorer and it looks like entirely different filters are needed to do ranges (DateSentAfter/DateSentBefore for messages and StarttimeAfter/StarttimeBefore for calls)

TSLint found two errors

This is the code I use:

`function generateToken(iden,room){
const AccessToken = twilio.jwt.AccessToken;
const token = new AccessToken(
envconf.twilio.sid,
envconf.twilio.apikey,
envconf.twilio.apisecret,
)
token.identity = iden;
const grant = new twilio.jwt.AccessToken.VideoGrant()
token.addGrant(grant);
return token.toJwt();

}`

and TSLint says AccessToken does not have identity
also says toJwt() needs an argument!

Account Security API key

I'm trying to validate the signature of the webhook for an one touch request, but I'm always getting a different signature.

The documentation isn't really clear about which key is the "Account Security API key" and I have tried all the keys available to no avail.

I'm working with Node.js and the Loopback 3.x framework.

This is the code I'm using.

const sortByPropertyOnly = (x, y) => {
    const xx = x.split('=');
    const yy = y.split('=');

    if (xx < yy) {
      return -1;
    }
    if (xx > yy) {
      return 1;
    }
    return 0;
  };

const verifyCallback = (req, apiKey) => {
    const url = req.protocol + '://' + req.get('host') + req.originalUrl;
    const method = req.method;
    const params = req.body;	// needs `npm i body-parser` on Express 4

    // Sort the params
    const sortedParams = querystring
      .stringify(params, { arrayFormat: 'brackets' })
      .split('&')
      .sort(sortByPropertyOnly)
      .join('&')
      .replace(/%20/g, '+');

    // Read the nonce from the request
    const nonce = req.headers['x-authy-signature-nonce'];

    // concatinate all together and separate by '|'
    const data = nonce + '|' + method + '|' + url + '|' + sortedParams;

    // compute the signature
    const computedSig = crypto
      .createHmac('sha256', apiKey)
      .update(data)
      .digest('base64');

    const sig = req.headers['x-authy-signature'];

    // compare the message signature with your calculated signature
    return sig === computedSig;
  }

// Webhook declaration
medxUser.authyCallback = async (req, res) => {
    console.log(verifyCallback(req, process.env.AUTHY_API_KEY));
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.