Skip to content

Instantly share code, notes, and snippets.

@miguelgrinberg
Last active May 19, 2020 11:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miguelgrinberg/a95dfa31b0dd78e7a0c476cb87f7d670 to your computer and use it in GitHub Desktop.
Save miguelgrinberg/a95dfa31b0dd78e7a0c476cb87f7d670 to your computer and use it in GitHub Desktop.
webhook featured in the COVID-19 Twilio Autopilot bot tutorial
from datetime import datetime
import json
import random
from flask import Flask, request
from covid import Covid
from iso3166 import countries
app = Flask(__name__)
covid = Covid()
stat_name = {
'confirmed': 'confirmed cases',
'deaths': 'confirmed deaths',
'active': 'active cases',
'recovered': 'recovered cases'
}
@app.route('/covidbot', methods=['POST'])
def covidbot():
stat = request.form.get('Field_stat_Value')
country = request.form.get('Field_country_Value')
memory = json.loads(request.form['Memory'])
if stat is None:
stat = memory.get('stat')
if country is None:
country = memory.get('country')
message = None
if stat is None or country is None:
message = 'Sorry, I do not understand. Can you repeat?'
if message is None:
try:
country_name = countries.get(country).name
except KeyError:
message = 'Sorry, I do not recognize that country.'
if country == 'USA':
country_key = 'US'
else:
country_key = country_name
if message is None:
results = covid.get_status_by_country_name(country_key)
last_update = datetime.utcfromtimestamp(
results['last_update'] / 1000).strftime('%Y-%m-%d')
message = random.choice([
(f'As of {last_update}, {country_name} has '
f'{results[stat]} {stat_name[stat]}.'),
(f'There are {results[stat]} {stat_name[stat]} in {country_name}, '
f'as of {last_update}.'),
(f'{country_name} has {results[stat]} {stat_name[stat]} as of '
f'{last_update}.')
])
return {
'actions': [
{'say': message},
{'remember': {'stat': stat, 'country': country}},
{'listen': True},
]
}
beautifulsoup4==4.9.0
certifi==2020.4.5.1
chardet==3.0.4
click==7.1.2
covid==2.2.8
Flask==1.1.2
idna==2.9
iso3166==1.0.1
itsdangerous==1.1.0
Jinja2==2.11.2
MarkupSafe==1.1.1
pydantic==1.5.1
python-dotenv==0.13.0
requests==2.23.0
soupsieve==2.0
urllib3==1.25.9
Werkzeug==1.0.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment