diff --git a/.env.example b/.env.example index 7b068e0..d2dc9b2 100644 --- a/.env.example +++ b/.env.example @@ -1,4 +1,16 @@ -export TWILIO_ACCOUNT_SID=ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX -export TWILIO_AUTH_TOKEN=your_auth_token -export TWILIO_TWIML_APP_SID=APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX -export TWILIO_CALLER_ID=+1XXXYYYZZZZ +TWILIO_ACCOUNT_SID=ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX +TWILIO_CALLER_ID=+1XXXYYYZZZZ + +# SID of your TwiML Application +# https://www.twilio.com/console/voice/twiml/apps +# OR +# twilio api:core:applications:create --friendly-name=voice-client-javascript +TWILIO_TWIML_APP_SID=APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX + +# Your REST API Key information +# https://www.twilio.com/console/project/api-keys +# OR +# twilio api:core:keys:create --friendly-name=voice-client-javascript -o json +# NOTE: Make sure to copy the secret, it'll will only be displayed once +API_KEY=SKXXXXXXXXXXXX +API_SECRET=XXXXXXXXXXXXXX diff --git a/.env.example.ps1 b/.env.example.ps1 index 99a6735..ed7d9cd 100644 --- a/.env.example.ps1 +++ b/.env.example.ps1 @@ -1,7 +1,8 @@ $Env:TWILIO_ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" -$Env:TWILIO_AUTH_TOKEN = "your_auth_token" $Env:TWILIO_TWIML_APP_SID = "APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" $Env:TWILIO_CALLER_ID = "+1XXXYYYZZZZ" +$Env:API_KEY = "SKXXXXXXXXXXXX" +$Env:API_SECRET = "XXXXXXXXXXXXXX" # Uncomment the following if you'd like the environment variables # to be permanently set on your user account for this machine. @@ -9,8 +10,9 @@ $Env:TWILIO_CALLER_ID = "+1XXXYYYZZZZ" <# [Environment]::SetEnvironmentVariable("TWILIO_ACCOUNT_SID", $Env:TWILIO_ACCOUNT_SID, "User") -[Environment]::SetEnvironmentVariable("TWILIO_AUTH_TOKEN", $Env:TWILIO_AUTH_TOKEN, "User") [Environment]::SetEnvironmentVariable("TWILIO_TWIML_APP_SID", $Env:TWILIO_TWIML_APP_SID, "User") [Environment]::SetEnvironmentVariable("TWILIO_CALLER_ID", $Env:TWILIO_CALLER_ID, "User") +[Environment]::SetEnvironmentVariable("API_KEY", $Env:API_KEY, "User") +[Environment]::SetEnvironmentVariable("API_SECRET", $Env:API_SECRET, "User") #> \ No newline at end of file diff --git a/.github/workflows/flask.yml b/.github/workflows/flask.yml new file mode 100644 index 0000000..f97da29 --- /dev/null +++ b/.github/workflows/flask.yml @@ -0,0 +1,36 @@ +name: Flask + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +jobs: + build: + + runs-on: ubuntu-latest + strategy: + max-parallel: 4 + matrix: + python-version: [3.6, 3.7, 3.8] + + steps: + - uses: actions/checkout@v2 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v1 + with: + python-version: ${{ matrix.python-version }} + - name: Install Dependencies + run: | + python -m pip install --upgrade pip + pip install -r requirements.txt + - name: Run Tests + run: | + python -m pytest + env: + TWILIO_ACCOUNT_SID: ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX + TWILIO_CALLER_ID: +1XXXYYYZZZZ + TWILIO_TWIML_APP_SID: APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX + API_KEY: SKXXXXXXXXXXXX + API_SECRET: XXXXXXXXXXXXXX diff --git a/.gitignore b/.gitignore index 7fd2a8c..ffbaef8 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,6 @@ _mailinglist .env .env.ps1 venv +.vscode +__pycache__ +.pytest_cache diff --git a/.mergify.yml b/.mergify.yml new file mode 100644 index 0000000..0433495 --- /dev/null +++ b/.mergify.yml @@ -0,0 +1,13 @@ +pull_request_rules: + - name: automatic merge for Dependabot pull requests + conditions: + - author=dependabot-preview[bot] + - status-success=build (macos-latest, 10) + - status-success=build (macos-latest, 12) + - status-success=build (windows-latest, 10) + - status-success=build (windows-latest, 12) + - status-success=build (ubuntu-latest, 10) + - status-success=build (ubuntu-latest, 12) + actions: + merge: + method: squash diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..2f0727e --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,73 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +- Using welcoming and inclusive language +- Being respectful of differing viewpoints and experiences +- Gracefully accepting constructive criticism +- Focusing on what is best for the community +- Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +- The use of sexualized language or imagery and unwelcome sexual attention or + advances +- Trolling, insulting/derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or electronic + address, without explicit permission +- Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at open-source@twilio.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..ad3257e --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,3 @@ +# Contributing to Twilio + +All third party contributors acknowledge that any contributions they provide will be made under the same open source license that the open source project is provided under. diff --git a/LICENSE b/LICENSE index 4bcc4c2..2c3cf9d 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,6 @@ -Copyright (c) 2015 Twilio Inc. +MIT License + +Copyright (c) 2020 Twilio Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -7,13 +9,13 @@ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index 2544387..918c57a 100644 --- a/README.md +++ b/README.md @@ -4,18 +4,20 @@ # Twilio Client Quickstart for Python + + > We are currently in the process of updating this sample template. If you are encountering any issues with the sample, please open an issue at [github.com/twilio-labs/code-exchange/issues](https://github.com/twilio-labs/code-exchange/issues) and we'll try to help you. This application should give you a ready-made starting point for writing your own voice apps with Twilio Client. Before we begin, we need to collect all the config values we need to run the application: -| Config Value | Description | +| Config Value | Description | | :------------- |:------------- | -Account SID | Your primary Twilio account identifier - find this [in the console here](https://www.twilio.com/console). -Auth Token | Used to authenticate - [just like the above, you'll find this here](https://www.twilio.com/console). -TwiML App SID | The TwiML application with a voice URL configured to access your server running this app - create one [in the console here](https://www.twilio.com//console/phone-numbers/dev-tools/twiml-apps). Also, you will need to configure the Voice "REQUEST URL" on the TwiML app once you've got your server up and running. -Twilio Phone # | A Twilio phone number in [E.164 format](https://en.wikipedia.org/wiki/E.164) - you can [get one here](https://www.twilio.com/console/phone-numbers/incoming) +`TWILIO_ACCOUNT_SID` | Your primary Twilio account identifier - find this [in the console here](https://www.twilio.com/console). +`TWILIO_TWIML_APP_SID` | The TwiML application with a voice URL configured to access your server running this app - create one [in the console here](https://www.twilio.com/console/voice/twiml/apps). Also, you will need to configure the Voice "REQUEST URL" on the TwiML app once you've got your server up and running. +`TWILIO_CALLER_ID` | A Twilio phone number in [E.164 format](https://en.wikipedia.org/wiki/E.164) - you can [get one here](https://www.twilio.com/console/phone-numbers/incoming) +`API_KEY` / `API_SECRET` | Your REST API Key information needed to create an [Access Token](https://www.twilio.com/docs/iam/access-tokens) - create [one here](https://www.twilio.com/console/project/api-keys). ## Setting Up The Python Application @@ -29,13 +31,7 @@ Begin by creating a configuration file for your application: cp .env.example .env ``` -Edit `.env` with the four configuration parameters we gathered from above. Export -the configuration in this file as system environment variables like so on Unix -based systems: - -```bash -source .env -``` +Edit `.env` with the five configuration parameters we gathered from above. ### Windows (PowerShell) @@ -59,16 +55,23 @@ your user account. ## All Platforms +Create a new virtual environment. If using vanilla [virtualenv](https://virtualenv.pypa.io/en/latest/): + +``` +virtualenv venv +source venv/bin/activate +``` + Next, we need to install our depenedencies: ```bash -pip install -r requirements.txt +pip3 install -r requirements.txt ``` -Run the application using the `python` command. +Run the application using the `python3` command or the executable for Python 3. ```bash -python app.py +python3 app.py ``` Your application should now be running at http://localhost:5000. @@ -89,7 +92,7 @@ There's just a few more steps to get Twilio's voice infrastructure talking to yo 3. When ngrok starts up, it will assign a unique URL to your tunnel. It might be something like `https://asdf456.ngrok.io`. Take note of this. -4. [Configure your TwiML app](https://www.twilio.com/console/phone-numbers/dev-tools/twiml-apps)'s +4. [Configure your TwiML app](https://www.twilio.com/console/voice/twiml/apps)'s Voice "REQUEST URL" to be your ngrok URL plus `/voice`. For example:  @@ -103,6 +106,9 @@ We'd recommend Google Chrome or Mozilla Firefox instead.  -## License +## Meta -MIT +* No warranty expressed or implied. Software is as is. Diggity. +* The CodeExchange repository can be found [here](https://github.com/twilio-labs/code-exchange/). +* [MIT License](http://www.opensource.org/licenses/mit-license.html) +* Lovingly crafted by Twilio Developer Education. diff --git a/app.py b/app.py index 423f542..3df9c3e 100755 --- a/app.py +++ b/app.py @@ -4,9 +4,13 @@ import re from flask import Flask, jsonify, request, Response from faker import Faker -from twilio.jwt.client import ClientCapabilityToken +from twilio.jwt.access_token import AccessToken +from twilio.jwt.access_token.grants import VoiceGrant from twilio.twiml.voice_response import VoiceResponse, Dial +from dotenv import load_dotenv +load_dotenv() + app = Flask(__name__) fake = Faker() alphanumeric_only = re.compile('[\W_]+') @@ -22,17 +26,26 @@ def index(): def token(): # get credentials for environment variables account_sid = os.environ['TWILIO_ACCOUNT_SID'] - auth_token = os.environ['TWILIO_AUTH_TOKEN'] application_sid = os.environ['TWILIO_TWIML_APP_SID'] + api_key = os.environ['API_KEY'] + api_secret = os.environ['API_SECRET'] # Generate a random user name identity = alphanumeric_only.sub('', fake.user_name()) + + # Create access token with credentials + token = AccessToken(account_sid, api_key, api_secret, identity=identity) + + # Create a Voice grant and add to token + voice_grant = VoiceGrant( + outgoing_application_sid=application_sid, + incoming_allow=True, + ) + token.add_grant(voice_grant) + + # Return token info as JSON + token=token.to_jwt() - # Create a Capability Token - capability = ClientCapabilityToken(account_sid, auth_token) - capability.allow_client_outgoing(application_sid) - capability.allow_client_incoming(identity) - token = capability.to_jwt() # Return token info as JSON return jsonify(identity=identity, token=token.decode('utf-8')) diff --git a/requirements.txt b/requirements.txt index 3f8b457..1f4143e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,5 @@ -flask~=1.1.0 -twilio~=6.32.0 -faker~=2.0.3 -python-dotenv==0.10.3 +flask~=1.1.2 +twilio~=6.38.1 +faker~=4.0.3 +python-dotenv==0.13.0 +pytest==5.4.1 diff --git a/static/index.html b/static/index.html index 0b1b00b..91f0cce 100644 --- a/static/index.html +++ b/static/index.html @@ -31,8 +31,9 @@
- - + + +