Skip to content

Instantly share code, notes, and snippets.

@MemphisMeng
Last active August 19, 2020 21:48
Show Gist options
  • Save MemphisMeng/d24b5f35b9baabdf1ad2eea3a855a2fc to your computer and use it in GitHub Desktop.
Save MemphisMeng/d24b5f35b9baabdf1ad2eea3a855a2fc to your computer and use it in GitHub Desktop.
# if the request was not get, it must be POST and we can just proceed with sending a message back to user
else:
# get whatever message a user sent the bot
output = request.get_json()
for event in output['entry']:
messaging = event['messaging']
for message in messaging:
if message.get('message'):
# Facebook Messenger ID for user so we know where to send response back to
recipient_id = message['sender']['id']
if message['message'].get('text'):
# NLP detection
if message['message'].get('nlp'):
try:
# detected English
if 'en' in message['message']['nlp']['detected_locales'][0]['locale']:
# greeting detected
if message['message']['nlp']['entities'].get('greetings') and \
message['message']['nlp']['entities']['greetings'][0]['confidence'] >= 0.9:
response = "Hello! Nice to meet you!"
bot.send_text_message(recipient_id, response)
continue
# bye detected
elif message['message']['nlp']['entities'].get('bye') and \
message['message']['nlp']['entities']['bye'][0]['confidence'] >= 0.9:
response = "See you next time!"
bot.send_text_message(recipient_id, response)
continue
# thank detected
elif message['message']['nlp']['entities'].get('thanks') and \
message['message']['nlp']['entities']['thanks'][0]['confidence'] >= 0.9:
response = "You are welcome!"
bot.send_text_message(recipient_id, response)
continue
# detected Spanish
elif 'es' in message['message']['nlp']['detected_locales'][0]['locale']:
# greeting detected
if message['message']['nlp']['entities'].get('greetings') and \
message['message']['nlp']['entities']['greetings'][0]['confidence'] >= 0.6:
response = "¡Mucho gusto! ¿Cómo estás?"
bot.send_text_message(recipient_id, response)
continue
elif message['message']['nlp']['entities'].get('bye') and \
message['message']['nlp']['entities']['bye'][0]['confidence'] >= 0.6:
response = "¡Adíos!"
bot.send_text_message(recipient_id, response)
continue
elif message['message']['nlp']['entities'].get('thanks') and \
message['message']['nlp']['entities']['thanks'][0]['confidence'] >= 0.6:
response = "¡De nada!"
bot.send_text_message(recipient_id, response)
continue
except KeyError:
print('NLP is not deployed.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment