I am building a voicemail application that recieves phone calls via Twilio, takes a message, and then records the information in an Airtable database. I have everything working fine but it is a lot of repeated code so I wanted to consolidate it but I'm running into errors when calling the function.
Here is what I have now...
@app.route("/call", methods=['GET', 'POST'])
def caller():
phone = request.values.get('From', None)
campaign = request.values.get('To')
if campaign == brand_1.phone:
brand = brand_1
resp = VoiceResponse()
resp.play(brand.recording)
resp.record(maxLength="30")
recording_url = request.values.get("RecordingUrl", None)
brand.at.create('Leads', data = {'Phone':phone,'Campaign':campaign, 'Voicemail':recording_url})
return str(resp)
elif campaign == brand_2.phone:
brand = brand_2
resp = VoiceResponse()
resp.play(brand.recording)
resp.record(maxLength="30")
recording_url = request.values.get("RecordingUrl", None)
brand.at.create('Leads', data = {'Phone':phone,'Campaign':campaign, 'Voicemail':recording_url})
return str(resp)
elif campaign == brand_3.phone:
brand = brand_3
resp = VoiceResponse()
resp.play(brand.recording)
resp.record(maxLength="30")
recording_url = request.values.get("RecordingUrl", None)
brand.at.create('Leads', data = {'Phone':phone,'Campaign':campaign, 'Voicemail':recording_url})
return str(resp)
return "Success!"
As you can see, I'm repeating the same code three times. It works, but it's ugly and takes up space so I wanted to create a separate function that looks like this...
def voicemail(brand, phone, campaign):
resp = VoiceResponse()
resp.play(brand.recording)
resp.record(maxLength="30")
recording_url = request.values.get("RecordingUrl", None)
brand.at.create('Leads', data = {'Phone':phone,'Campaign':campaign, 'Voicemail':recording_url})
return str(resp)
So I'd like to have look like this...
@app.route("/call", methods=['GET', 'POST'])
def caller():
phone = request.values.get('From', None)
campaign = request.values.get('To')
if campaign == brand_1.phone:
brand = brand_1
voicemail(brand, phone, campaign)
elif campaign == brand_2.phone:
brand = brand_2
voicemail(brand, phone, campaign)
elif campaign == brand_3.phone:
brand = brand_3
voicemail(brand, phone, campaign)
return "Success!"
It seems like this should work but it doesn't. Twilio just says "An application error has occurred"
What am I missing here guys?
The second pattern makes the function caller()
only returns the final "Success".
You should try :
return voicemail(brand, phone, campaign)