2018-01-12 13:49:11 +01:00
|
|
|
# Webhooks for external integrations.
|
2018-05-10 19:34:01 +02:00
|
|
|
from typing import Any, Dict
|
2020-01-14 22:06:24 +01:00
|
|
|
|
2018-01-12 13:49:11 +01:00
|
|
|
from django.http import HttpRequest, HttpResponse
|
2020-01-14 22:06:24 +01:00
|
|
|
|
2020-08-20 00:32:15 +02:00
|
|
|
from zerver.decorator import webhook_view
|
2018-01-12 13:49:11 +01:00
|
|
|
from zerver.lib.actions import check_send_private_message
|
|
|
|
from zerver.lib.request import REQ, has_request_variables
|
|
|
|
from zerver.lib.response import json_success
|
2021-03-01 21:51:21 +01:00
|
|
|
from zerver.models import UserProfile, get_user
|
2018-01-12 13:49:11 +01:00
|
|
|
|
2020-01-14 22:06:24 +01:00
|
|
|
|
2020-10-23 02:43:28 +02:00
|
|
|
@webhook_view("Dialogflow")
|
2018-01-12 13:49:11 +01:00
|
|
|
@has_request_variables
|
2021-02-12 08:19:30 +01:00
|
|
|
def api_dialogflow_webhook(
|
|
|
|
request: HttpRequest,
|
|
|
|
user_profile: UserProfile,
|
2021-02-12 08:20:45 +01:00
|
|
|
payload: Dict[str, Any] = REQ(argument_type="body"),
|
2021-02-12 08:19:30 +01:00
|
|
|
email: str = REQ(),
|
|
|
|
) -> HttpResponse:
|
2018-01-12 13:49:11 +01:00
|
|
|
status = payload["status"]["code"]
|
|
|
|
|
|
|
|
if status == 200:
|
|
|
|
result = payload["result"]["fulfillment"]["speech"]
|
|
|
|
if not result:
|
|
|
|
alternate_result = payload["alternateResult"]["fulfillment"]["speech"]
|
|
|
|
if not alternate_result:
|
2020-10-23 02:43:28 +02:00
|
|
|
body = "Dialogflow couldn't process your query."
|
2018-01-12 13:49:11 +01:00
|
|
|
else:
|
|
|
|
body = alternate_result
|
|
|
|
else:
|
|
|
|
body = result
|
|
|
|
else:
|
|
|
|
error_status = payload["status"]["errorDetails"]
|
2020-06-09 00:25:09 +02:00
|
|
|
body = f"{status} - {error_status}"
|
2018-01-12 13:49:11 +01:00
|
|
|
|
2021-03-01 21:51:21 +01:00
|
|
|
receiving_user = get_user(email, user_profile.realm)
|
|
|
|
check_send_private_message(user_profile, request.client, receiving_user, body)
|
2018-01-12 13:49:11 +01:00
|
|
|
return json_success()
|