2020-06-11 00:54:34 +02:00
|
|
|
import importlib
|
2017-10-20 17:24:09 +02:00
|
|
|
import json
|
2017-06-21 20:43:26 +02:00
|
|
|
import os
|
2021-03-26 02:27:19 +01:00
|
|
|
from typing import Any, Callable, Dict, Optional
|
2017-06-21 20:43:26 +02:00
|
|
|
|
2021-04-05 01:09:36 +02:00
|
|
|
from django.conf import settings
|
2021-04-16 00:57:30 +02:00
|
|
|
from django.utils.translation import gettext as _
|
2019-01-07 16:20:21 +01:00
|
|
|
|
2020-06-11 00:54:34 +02:00
|
|
|
from zerver.lib.actions import (
|
|
|
|
internal_send_huddle_message,
|
|
|
|
internal_send_private_message,
|
|
|
|
internal_send_stream_message_by_name,
|
|
|
|
)
|
|
|
|
from zerver.lib.bot_config import ConfigError, get_bot_config
|
|
|
|
from zerver.lib.bot_storage import (
|
|
|
|
get_bot_storage,
|
|
|
|
is_key_in_bot_storage,
|
|
|
|
remove_bot_storage,
|
|
|
|
set_bot_storage,
|
|
|
|
)
|
|
|
|
from zerver.lib.integrations import EMBEDDED_BOTS
|
|
|
|
from zerver.lib.topic import get_topic_from_message_info
|
|
|
|
from zerver.models import UserProfile, get_active_user
|
2017-06-21 20:43:26 +02:00
|
|
|
|
|
|
|
our_dir = os.path.dirname(os.path.abspath(__file__))
|
|
|
|
|
2021-03-26 02:27:19 +01:00
|
|
|
from zulip_bots.lib import BotIdentity, RateLimit
|
2017-06-21 20:43:26 +02:00
|
|
|
|
2020-06-11 00:54:34 +02:00
|
|
|
|
2017-11-05 11:15:10 +01:00
|
|
|
def get_bot_handler(service_name: str) -> Any:
|
2017-07-21 17:54:34 +02:00
|
|
|
|
2017-07-25 19:03:09 +02:00
|
|
|
# Check that this service is present in EMBEDDED_BOTS, add exception handling.
|
2020-03-02 20:38:35 +01:00
|
|
|
configured_service = ""
|
|
|
|
for embedded_bot_service in EMBEDDED_BOTS:
|
|
|
|
if service_name == embedded_bot_service.name:
|
|
|
|
configured_service = embedded_bot_service.name
|
|
|
|
if not configured_service:
|
2017-07-25 19:03:09 +02:00
|
|
|
return None
|
2021-02-12 08:20:45 +01:00
|
|
|
bot_module_name = f"zulip_bots.bots.{configured_service}.{configured_service}"
|
python: Convert assignment type annotations to Python 3.6 style.
This commit was split by tabbott; this piece covers the vast majority
of files in Zulip, but excludes scripts/, tools/, and puppet/ to help
ensure we at least show the right error messages for Xenial systems.
We can likely further refine the remaining pieces with some testing.
Generated by com2ann, with whitespace fixes and various manual fixes
for runtime issues:
- invoiced_through: Optional[LicenseLedger] = models.ForeignKey(
+ invoiced_through: Optional["LicenseLedger"] = models.ForeignKey(
-_apns_client: Optional[APNsClient] = None
+_apns_client: Optional["APNsClient"] = None
- notifications_stream: Optional[Stream] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
- signup_notifications_stream: Optional[Stream] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
+ notifications_stream: Optional["Stream"] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
+ signup_notifications_stream: Optional["Stream"] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
- author: Optional[UserProfile] = models.ForeignKey('UserProfile', blank=True, null=True, on_delete=CASCADE)
+ author: Optional["UserProfile"] = models.ForeignKey('UserProfile', blank=True, null=True, on_delete=CASCADE)
- bot_owner: Optional[UserProfile] = models.ForeignKey('self', null=True, on_delete=models.SET_NULL)
+ bot_owner: Optional["UserProfile"] = models.ForeignKey('self', null=True, on_delete=models.SET_NULL)
- default_sending_stream: Optional[Stream] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
- default_events_register_stream: Optional[Stream] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
+ default_sending_stream: Optional["Stream"] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
+ default_events_register_stream: Optional["Stream"] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
-descriptors_by_handler_id: Dict[int, ClientDescriptor] = {}
+descriptors_by_handler_id: Dict[int, "ClientDescriptor"] = {}
-worker_classes: Dict[str, Type[QueueProcessingWorker]] = {}
-queues: Dict[str, Dict[str, Type[QueueProcessingWorker]]] = {}
+worker_classes: Dict[str, Type["QueueProcessingWorker"]] = {}
+queues: Dict[str, Dict[str, Type["QueueProcessingWorker"]]] = {}
-AUTH_LDAP_REVERSE_EMAIL_SEARCH: Optional[LDAPSearch] = None
+AUTH_LDAP_REVERSE_EMAIL_SEARCH: Optional["LDAPSearch"] = None
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-22 01:09:50 +02:00
|
|
|
bot_module: Any = importlib.import_module(bot_module_name)
|
2017-07-21 17:54:34 +02:00
|
|
|
return bot_module.handler_class()
|
|
|
|
|
2017-10-12 16:34:05 +02:00
|
|
|
|
2017-11-05 11:37:41 +01:00
|
|
|
class StateHandler:
|
2021-04-05 01:09:36 +02:00
|
|
|
storage_size_limit: int = settings.USER_STATE_SIZE_LIMIT
|
2017-10-12 16:34:05 +02:00
|
|
|
|
2017-11-05 11:15:10 +01:00
|
|
|
def __init__(self, user_profile: UserProfile) -> None:
|
2017-10-12 16:34:05 +02:00
|
|
|
self.user_profile = user_profile
|
2020-07-01 01:50:08 +02:00
|
|
|
self.marshal: Callable[[object], str] = lambda obj: json.dumps(obj)
|
|
|
|
self.demarshal: Callable[[str], object] = lambda obj: json.loads(obj)
|
2017-10-12 16:34:05 +02:00
|
|
|
|
2020-07-01 01:50:08 +02:00
|
|
|
def get(self, key: str) -> object:
|
2017-11-24 10:18:29 +01:00
|
|
|
return self.demarshal(get_bot_storage(self.user_profile, key))
|
2017-10-12 16:34:05 +02:00
|
|
|
|
2020-07-01 01:50:08 +02:00
|
|
|
def put(self, key: str, value: object) -> None:
|
2017-11-24 10:18:29 +01:00
|
|
|
set_bot_storage(self.user_profile, [(key, self.marshal(value))])
|
2017-10-12 16:34:05 +02:00
|
|
|
|
2018-05-10 19:13:36 +02:00
|
|
|
def remove(self, key: str) -> None:
|
2017-11-24 10:18:29 +01:00
|
|
|
remove_bot_storage(self.user_profile, [key])
|
2017-10-26 16:02:35 +02:00
|
|
|
|
2018-05-10 19:13:36 +02:00
|
|
|
def contains(self, key: str) -> bool:
|
2017-11-24 10:18:29 +01:00
|
|
|
return is_key_in_bot_storage(self.user_profile, key)
|
2017-10-12 16:34:05 +02:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2018-02-08 15:51:38 +01:00
|
|
|
class EmbeddedBotQuitException(Exception):
|
|
|
|
pass
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2019-01-07 16:20:21 +01:00
|
|
|
class EmbeddedBotEmptyRecipientsList(Exception):
|
|
|
|
pass
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2017-11-05 11:37:41 +01:00
|
|
|
class EmbeddedBotHandler:
|
2017-11-05 11:15:10 +01:00
|
|
|
def __init__(self, user_profile: UserProfile) -> None:
|
2017-06-21 20:43:26 +02:00
|
|
|
# Only expose a subset of our UserProfile's functionality
|
|
|
|
self.user_profile = user_profile
|
|
|
|
self._rate_limit = RateLimit(20, 5)
|
2017-07-17 19:30:48 +02:00
|
|
|
self.full_name = user_profile.full_name
|
|
|
|
self.email = user_profile.email
|
2017-10-20 17:42:57 +02:00
|
|
|
self.storage = StateHandler(user_profile)
|
2018-12-17 22:26:59 +01:00
|
|
|
self.user_id = user_profile.id
|
2017-06-21 20:43:26 +02:00
|
|
|
|
2021-03-26 02:27:19 +01:00
|
|
|
def identity(self) -> BotIdentity:
|
|
|
|
return BotIdentity(self.full_name, self.email)
|
|
|
|
|
|
|
|
def react(self, message: Dict[str, Any], emoji_name: str) -> Dict[str, Any]:
|
|
|
|
return {} # Not implemented
|
|
|
|
|
2017-11-05 11:15:10 +01:00
|
|
|
def send_message(self, message: Dict[str, Any]) -> None:
|
2017-11-27 01:53:28 +01:00
|
|
|
if not self._rate_limit.is_legal():
|
2017-06-21 20:43:26 +02:00
|
|
|
self._rate_limit.show_error_and_exit()
|
2017-11-27 02:00:04 +01:00
|
|
|
|
2021-02-12 08:20:45 +01:00
|
|
|
if message["type"] == "stream":
|
2019-02-09 03:01:35 +01:00
|
|
|
internal_send_stream_message_by_name(
|
2021-02-12 08:19:30 +01:00
|
|
|
self.user_profile.realm,
|
|
|
|
self.user_profile,
|
2021-02-12 08:20:45 +01:00
|
|
|
message["to"],
|
|
|
|
message["topic"],
|
|
|
|
message["content"],
|
2019-02-08 03:13:14 +01:00
|
|
|
)
|
2017-11-27 02:00:04 +01:00
|
|
|
return
|
|
|
|
|
2021-02-12 08:20:45 +01:00
|
|
|
assert message["type"] == "private"
|
2017-11-27 02:00:04 +01:00
|
|
|
# Ensure that it's a comma-separated list, even though the
|
|
|
|
# usual 'to' field could be either a List[str] or a str.
|
2021-02-12 08:20:45 +01:00
|
|
|
recipients = ",".join(message["to"]).split(",")
|
2017-11-27 02:00:04 +01:00
|
|
|
|
2021-02-12 08:20:45 +01:00
|
|
|
if len(message["to"]) == 0:
|
|
|
|
raise EmbeddedBotEmptyRecipientsList(_("Message must have recipients!"))
|
|
|
|
elif len(message["to"]) == 1:
|
2018-05-21 05:04:16 +02:00
|
|
|
recipient_user = get_active_user(recipients[0], self.user_profile.realm)
|
2021-02-18 19:58:04 +01:00
|
|
|
internal_send_private_message(self.user_profile, recipient_user, message["content"])
|
2017-11-27 02:00:04 +01:00
|
|
|
else:
|
2021-02-12 08:19:30 +01:00
|
|
|
internal_send_huddle_message(
|
2021-02-12 08:20:45 +01:00
|
|
|
self.user_profile.realm, self.user_profile, recipients, message["content"]
|
2021-02-12 08:19:30 +01:00
|
|
|
)
|
2017-06-21 20:43:26 +02:00
|
|
|
|
2021-03-26 02:27:19 +01:00
|
|
|
def send_reply(
|
|
|
|
self, message: Dict[str, Any], response: str, widget_content: Optional[str] = None
|
|
|
|
) -> None:
|
2021-02-12 08:20:45 +01:00
|
|
|
if message["type"] == "private":
|
2021-02-12 08:19:30 +01:00
|
|
|
self.send_message(
|
|
|
|
dict(
|
2021-02-12 08:20:45 +01:00
|
|
|
type="private",
|
|
|
|
to=[x["email"] for x in message["display_recipient"]],
|
2021-02-12 08:19:30 +01:00
|
|
|
content=response,
|
2021-02-12 08:20:45 +01:00
|
|
|
sender_email=message["sender_email"],
|
2021-02-12 08:19:30 +01:00
|
|
|
)
|
|
|
|
)
|
2017-07-17 19:30:48 +02:00
|
|
|
else:
|
2021-02-12 08:19:30 +01:00
|
|
|
self.send_message(
|
|
|
|
dict(
|
2021-02-12 08:20:45 +01:00
|
|
|
type="stream",
|
|
|
|
to=message["display_recipient"],
|
2021-02-12 08:19:30 +01:00
|
|
|
topic=get_topic_from_message_info(message),
|
|
|
|
content=response,
|
2021-02-12 08:20:45 +01:00
|
|
|
sender_email=message["sender_email"],
|
2021-02-12 08:19:30 +01:00
|
|
|
)
|
|
|
|
)
|
2017-06-21 20:43:26 +02:00
|
|
|
|
2021-03-26 02:27:19 +01:00
|
|
|
def update_message(self, message: Dict[str, Any]) -> None:
|
|
|
|
pass # Not implemented
|
|
|
|
|
2018-01-07 19:17:25 +01:00
|
|
|
# The bot_name argument exists only to comply with ExternalBotHandler.get_config_info().
|
2021-02-12 08:19:30 +01:00
|
|
|
def get_config_info(self, bot_name: str, optional: bool = False) -> Dict[str, str]:
|
2018-01-07 19:17:25 +01:00
|
|
|
try:
|
|
|
|
return get_bot_config(self.user_profile)
|
|
|
|
except ConfigError:
|
|
|
|
if optional:
|
2020-09-02 08:14:51 +02:00
|
|
|
return {}
|
2018-01-07 19:17:25 +01:00
|
|
|
raise
|
2018-02-08 15:51:38 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
def quit(self, message: str = "") -> None:
|
2018-02-08 15:51:38 +01:00
|
|
|
raise EmbeddedBotQuitException(message)
|