This is the API V2 documentation. To switch out of beta revert back to our API V1.

Open SidemenuDocs
Docs
Close Sidemenu
Choose:
PythonRubyNode
PythonRubyNode

Meeting Schedulermeeting-scheduler

15 minutes build time || Difficulty Level: Intermediate || Github RepoTelnyx Developers

Pre-reqspre-reqs

Configurationconfiguration

Firstly, create a config_file.cfg file in your project directory. Flask will load this at startup.

API_KEY='YOUR_API_KEY'
FROM_NUMBER='YOUR_TELNYX_NUMBER'

Note: This file contains a secret key, it should not be committed to source control.

We’ll also place Flask in debug mode and assume all numbers are in the U.S.

DEBUG=True
COUNTRY_CODE='+1'

Install the necessary packages for the application

$ pip install telnyx
$ pip install flask
$ pip install celery
$ pip install redis

Server Initializationserver-initialization

Create a file schedule_meeting_server.py and install the basic requirements

The first piece of our application sets up the Telnyx library, Flask, and Celery.

import uuid
from datetime import datetime, timedelta

import telnyx
from celery import Celery
from flask import Flask, request, render_template, flash

app = Flask(__name__)
app.secret_key = uuid.uuid4()
app.config.from_pyfile('config_file.cfg')
celery = Celery('schedule_meeting_server', broker='redis://localhost:6379')

telnyx.api_key = app.config['API_KEY']

Collect User Inputcollect-user-input

We'll create a simple HTML form which collects the meeting date, time, customer name, and phone number.

The Flask route: @app.route('/', methods=['GET', 'POST']) will serve the files created in the folder "templates"

$ mkdir templates
$ touch templates/index.html
$ touch templates/success.html

index.htmlindex-html

Inside the newly created templates/index.html

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html> <head>
<meta charset="utf-8">
<title>Telnyx Meeting Scheduler</title>
</head>

<body>
<!--If form submission results in error, flash error message -->
{% with messages = get_flashed_messages() %}
  {% if messages %}
    <ul class=flashes>
    {% for message in messages %}
      <li>{{ message }}</li>
    {% endfor %}
    </ul>
  {% endif %}
{% endwith %}

<div>
  <h1>Telnyx Meeting Scheduling</h1>
  <form action="{{ url_for('schedule_meeting') }}" method="post">
  <div>
    <label for="name">Your name: </label>
    <input type="text" name="customer_name" required>
  </div>
  <div>
    <label for="treatment">Meeting name: </label>
    <input type="text" name="meeting_name" required>
  </div>
  <div>
    <label for="meeting-date">Appointment date: </label>
    <input type="date" id="meeting_date" name="meeting_date" required>
  </div>
  <div>
    <label for="meeting_time">Meeting time: </label>
    <input type="time" id="meeting_time" name="meeting_time" required>
  </div>
  <div>
    <label for="phone">Your mobile number: </label>
    <input type="tel" id="phone" name="phone" required>
  </div>
  <div>
    <input type="submit" value="Schedule now!">
  </div>
  </form>

</div>

</body> </html>

success.htmlsuccess-html

Inside templates/success.html

<html>
  <head>
    <title>Telnyx Meeting Scheduler</title>
  </head>
<body>
    <p>{{name}}, thanks for booking a meeting for <em>{{meeting_name}}</em>!</p>
    <p>You are scheduled for {{meetingDT}} and will receive a courtesy reminder at {{phone}} three hours before your meeting.</p>
  </body>
</html>

Implement the SMS Notificationimplement-the-sms-notification

Create a simple function that sends an SMS message parameterized on the destination number and message. The decorator @celery.task allows us to schedule this function to run in the future.

@celery.task
def send_reminder(to, message):
    telnyx.Message.create(
        to=to,
        from_=app.config['FROM_NUMBER'],
        text=message
    )

Note: from is a reserved word in Python. The Telnyx Python Library adds an underscore character to any parameter that would conflict with a reserved keyword.

Parse User Input and Schedule the Messageparse-user-input-and-schedule-the-message

Setup our route which will handle both GET and POST requests.

@app.route('/', methods=['GET', 'POST'])
def schedule_meeting():
    if request.method == "POST":
        # ...
    return render_template('index.html')

Now, within the conditional, first parse the user date/time input.

meeting_date = datetime.strptime(request.form['meeting_date'], '%Y-%m-%d')
meeting_time = datetime.strptime(request.form['meeting_time'], '%H:%M').time()
meeting_datetime = datetime.combine(meeting_date, meeting_time)

Next, only allow meetings to be scheduled that are three hours and five minutes in the future or later.

now = datetime.now()
if meeting_datetime - timedelta(hours=3, minutes=5) < now:
    flash('Appointment time must be at least 3:05 hours from now')
    return render_template('index.html')

Then, compute the reminder time and message, and schedule the reminder.

Remind the Userremind-the-user

Remind the user 3 hours before the meeting.

reminder_datetime = meeting_datetime - timedelta(hours=3)

message = "{customer_name}, you have a meeting scheduled for {meeting_time}".format(customer_name=request.form['customer_name'], meeting_time=str(meeting_datetime))
to = "{country_code}{phone}".format(country_code=app.config['COUNTRY_CODE'], phone=request.form['phone'])

send_reminder.apply_async([to, message], eta=reminder_datetime)

Finally, render the success template.

return render_template('success.html',
                       name=request.form['customer_name'],
                       meeting_name=request.form['meeting_name'],
                       phone=request.form['phone'],
                       meeting_datetime=str(meeting_datetime))

And at the end of the file, start the server.

if __name__ == '__main__':
    app.run(port=5010)

Final schedule_meeting_server.pyfinal-schedule_meeting_server-py

All together your schedule_meeting_server.py file should look something like:

import uuid
from datetime import datetime, timedelta

import telnyx
from celery import Celery
from flask import Flask, request, render_template, flash

app = Flask(__name__)
app.secret_key = uuid.uuid4()
app.config.from_pyfile('config_file.cfg')
celery = Celery('schedule_meeting_server', broker='redis://localhost:6379')

telnyx.api_key = app.config['API_KEY']

@celery.task
def send_reminder(to, message):
    telnyx.Message.create(
        to=to,
        from_=app.config['FROM_NUMBER'],
        text=message
    )

@app.route('/', methods=['GET', 'POST'])
def schedule_meeting():
    if request.method == "POST":
        meeting_date = datetime.strptime(request.form['meeting_date'], '%Y-%m-%d')
        meeting_time = datetime.strptime(request.form['meeting_time'], '%H:%M').time()
        meeting_datetime = datetime.combine(meeting_date, meeting_time)

        now = datetime.now()

        if meeting_datetime - timedelta(hours=3, minutes=5) < now:
            flash('Appointmenttest time must be at least 3:05 hours from now')
            return render_template('index.html')

        reminder_datetime = meeting_datetime - timedelta(hours=3)

        message = "{customer_name}, you have a meeting scheduled for {meeting_time}".format(customer_name=request.form['customer_name'], meeting_time=str(meeting_datetime))
        to = "{country_code}{phone}".format(country_code=app.config['COUNTRY_CODE'], phone=request.form['phone'])

        send_reminder.apply_async([to, message], eta=reminder_datetime)

        return render_template('success.html', name=request.form['customer_name'], meeting_name=request.form['meeting_name'],
                               phone=request.form['phone'], meeting_datetime=str(meeting_datetime))

    return render_template('index.html')

if __name__ == '__main__':
    app.run(port=5010)

Running the Projectrunning-the-project

Make sure redisTelnyx Developers is running in the background, and then start the Celery task and Python server. Assuming your code is in schedule_meeting_server.py.

In one terminal, launch the Celery worker (be sure to activate your virtual environment)

$ celery worker -A schedule_meeting_server.celery --loglevel=info

Then launch the python flask server

$ python schedule_meeting_server.py

Was this page helpful?was-this-page-helpful