Skip to content

Instantly share code, notes, and snippets.

@anapaulagomes
Last active September 7, 2020 10:27
Show Gist options
  • Save anapaulagomes/5978f88056dcc599a5f3778ec6a82189 to your computer and use it in GitHub Desktop.
Save anapaulagomes/5978f88056dcc599a5f3778ec6a82189 to your computer and use it in GitHub Desktop.
Twilio Call Queue
from flask import Flask, request
from twilio.twiml.voice_response import Dial, VoiceResponse, Gather
from calls import CallQueue
call_queue = CallQueue("support")
app = Flask(__name__)
AGENTS = {
"+000000000001": "Ana",
"+000000000000": "Miguel",
}
@app.route("/voice", methods=['GET', 'POST'])
def voice():
"""Respond to incoming phone calls with a menu of options"""
resp = VoiceResponse()
agent = AGENTS.get(request.values.get("Caller"))
if 'Digits' in request.values:
choice = request.values['Digits']
if agent:
if choice == '1':
resp.say('You will get the next call.')
dial = Dial()
dial.queue('support')
resp.append(dial)
else:
resp.say("Sorry, I don't understand that choice.")
else:
queue_size = call_queue.size()
if agent:
gather = Gather(num_digits=1)
gather.say(f'Hello, {agent}. There are {queue_size} callers in the queue, press 1 to answer the next call')
resp.append(gather)
else:
# customer
resp.say(f'There are {queue_size} people ahead of you. An agent will talk to you soon.')
# in case you want to play a message before
#resp.play(
# 'http://com.twilio.sounds.music.s3.amazonaws.com/MARKOVICHAMP-Borghestral.mp3'
#)
resp.enqueue('support')
# wait_url = 'http://demo.twilio.com/docs/voice.xml'
# If the caller doesn't select an option, redirect them into a loop
resp.redirect('/voice')
return str(resp)
if __name__ == "__main__":
app.run(debug=True)
from twilio.rest import Client
class CallQueue:
def __init__(self, name):
self.name = name
self.client = Client()
self.sid = self._create()
def __repr__(self):
return f"{self.name} ({self.sid})"
def _create(self):
current_queues = self.client.queues.list()
for queue in current_queues:
if self.name == queue.friendly_name:
return queue.sid
else:
new_queue = self.client.queues.create(friendly_name=self.name)
return new_queue.sid
def size(self):
queue = self.client.queues(self.sid).fetch()
return queue.current_size
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment