2018-01-12 13:49:11 +01:00
|
|
|
# Webhooks for external integrations.
|
|
|
|
from django.http import HttpRequest, HttpResponse
|
2020-01-14 22:06:24 +01:00
|
|
|
|
2022-04-14 23:50:10 +02:00
|
|
|
from zerver.actions.message_send import check_send_private_message
|
2020-08-20 00:32:15 +02:00
|
|
|
from zerver.decorator import webhook_view
|
2023-08-12 09:34:31 +02:00
|
|
|
from zerver.lib.request import RequestNotes
|
2018-01-12 13:49:11 +01:00
|
|
|
from zerver.lib.response import json_success
|
2023-09-27 19:01:31 +02:00
|
|
|
from zerver.lib.typed_endpoint import JsonBodyPayload, typed_endpoint
|
2023-08-12 09:34:31 +02:00
|
|
|
from zerver.lib.validator import WildValue, check_int, check_string
|
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")
|
2023-08-12 09:34:31 +02:00
|
|
|
@typed_endpoint
|
2021-02-12 08:19:30 +01:00
|
|
|
def api_dialogflow_webhook(
|
|
|
|
request: HttpRequest,
|
|
|
|
user_profile: UserProfile,
|
2023-08-12 09:34:31 +02:00
|
|
|
*,
|
2023-09-27 19:01:31 +02:00
|
|
|
payload: JsonBodyPayload[WildValue],
|
2023-08-12 09:34:31 +02:00
|
|
|
email: str,
|
2021-02-12 08:19:30 +01:00
|
|
|
) -> HttpResponse:
|
2022-03-28 16:18:11 +02:00
|
|
|
status = payload["status"]["code"].tame(check_int)
|
2018-01-12 13:49:11 +01:00
|
|
|
|
|
|
|
if status == 200:
|
2022-03-28 16:18:11 +02:00
|
|
|
result = payload["result"]["fulfillment"]["speech"].tame(check_string)
|
2018-01-12 13:49:11 +01:00
|
|
|
if not result:
|
2022-03-28 16:18:11 +02:00
|
|
|
alternate_result = payload["alternateResult"]["fulfillment"]["speech"].tame(
|
|
|
|
check_string
|
|
|
|
)
|
2018-01-12 13:49:11 +01:00
|
|
|
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:
|
2022-03-28 16:18:11 +02:00
|
|
|
error_status = payload["status"]["errorDetails"].tame(check_string)
|
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)
|
2021-08-21 19:24:20 +02:00
|
|
|
client = RequestNotes.get_notes(request).client
|
2021-07-09 18:10:51 +02:00
|
|
|
assert client is not None
|
|
|
|
check_send_private_message(user_profile, client, receiving_user, body)
|
2022-01-31 13:44:02 +01:00
|
|
|
return json_success(request)
|