예제 #1
0
class EmbeddedBotHandler:
    def __init__(self, user_profile: UserProfile) -> None:
        # Only expose a subset of our UserProfile's functionality
        self.user_profile = user_profile
        self._rate_limit = RateLimit(20, 5)
        self.full_name = user_profile.full_name
        self.email = user_profile.email
        self.storage = StateHandler(user_profile)
        self.user_id = user_profile.id

    def send_message(self, message: Dict[str, Any]) -> None:
        if not self._rate_limit.is_legal():
            self._rate_limit.show_error_and_exit()

        if message['type'] == 'stream':
            internal_send_stream_message(self.user_profile.realm, self.user_profile, message['to'],
                                         message['topic'], message['content'])
            return

        assert message['type'] == 'private'
        # Ensure that it's a comma-separated list, even though the
        # usual 'to' field could be either a List[str] or a str.
        recipients = ','.join(message['to']).split(',')

        if len(message['to']) == 1:
            recipient_user = get_active_user(recipients[0], self.user_profile.realm)
            internal_send_private_message(self.user_profile.realm, self.user_profile,
                                          recipient_user, message['content'])
        else:
            internal_send_huddle_message(self.user_profile.realm, self.user_profile,
                                         recipients, message['content'])

    def send_reply(self, message: Dict[str, Any], response: str) -> None:
        if message['type'] == 'private':
            self.send_message(dict(
                type='private',
                to=[x['email'] for x in message['display_recipient']],
                content=response,
                sender_email=message['sender_email'],
            ))
        else:
            self.send_message(dict(
                type='stream',
                to=message['display_recipient'],
                topic=get_topic_from_message_info(message),
                content=response,
                sender_email=message['sender_email'],
            ))

    # The bot_name argument exists only to comply with ExternalBotHandler.get_config_info().
    def get_config_info(self, bot_name: str, optional: bool=False) -> Dict[str, str]:
        try:
            return get_bot_config(self.user_profile)
        except ConfigError:
            if optional:
                return dict()
            raise

    def quit(self, message: str= "") -> None:
        raise EmbeddedBotQuitException(message)
예제 #2
0
class EmbeddedBotHandler:
    def __init__(self, user_profile: UserProfile) -> None:
        # Only expose a subset of our UserProfile's functionality
        self.user_profile = user_profile
        self._rate_limit = RateLimit(20, 5)
        self.full_name = user_profile.full_name
        self.email = user_profile.email
        self.storage = StateHandler(user_profile)

    def send_message(self, message: Dict[str, Any]) -> None:
        if not self._rate_limit.is_legal():
            self._rate_limit.show_error_and_exit()

        if message['type'] == 'stream':
            internal_send_stream_message(self.user_profile.realm, self.user_profile, message['to'],
                                         message['subject'], message['content'])
            return

        assert message['type'] == 'private'
        # Ensure that it's a comma-separated list, even though the
        # usual 'to' field could be either a List[str] or a str.
        recipients = ','.join(message['to']).split(',')

        if len(message['to']) == 1:
            recipient_user = get_user(recipients[0], self.user_profile.realm)
            internal_send_private_message(self.user_profile.realm, self.user_profile,
                                          recipient_user, message['content'])
        else:
            internal_send_huddle_message(self.user_profile.realm, self.user_profile,
                                         recipients, message['content'])

    def send_reply(self, message: Dict[str, Any], response: str) -> None:
        if message['type'] == 'private':
            self.send_message(dict(
                type='private',
                to=[x['email'] for x in message['display_recipient']],
                content=response,
                sender_email=message['sender_email'],
            ))
        else:
            self.send_message(dict(
                type='stream',
                to=message['display_recipient'],
                subject=message['subject'],
                content=response,
                sender_email=message['sender_email'],
            ))

    # The bot_name argument exists only to comply with ExternalBotHandler.get_config_info().
    def get_config_info(self, bot_name: str, optional: bool=False) -> Dict[str, str]:
        try:
            return get_bot_config(self.user_profile)
        except ConfigError:
            if optional:
                return dict()
            raise

    def quit(self, message: str= "") -> None:
        raise EmbeddedBotQuitException(message)
예제 #3
0
class EmbeddedBotHandler(object):
    def __init__(self, user_profile):
        # type: (UserProfile) -> None
        # Only expose a subset of our UserProfile's functionality
        self.user_profile = user_profile
        self._rate_limit = RateLimit(20, 5)
        self.full_name = user_profile.full_name
        self.email = user_profile.email
        self.state = StateHandler(user_profile)

    def send_message(self, message):
        # type: (Dict[str, Any]) -> None
        if self._rate_limit.is_legal():
            internal_send_message(realm=self.user_profile.realm,
                                  sender_email=message['sender_email'],
                                  recipient_type_name=message['type'],
                                  recipients=message['to'],
                                  subject=message['subject'],
                                  content=message['content'])
        else:
            self._rate_limit.show_error_and_exit()

    def send_reply(self, message, response):
        # type: (Dict[str, Any], str) -> None
        if message['type'] == 'private':
            self.send_message(
                dict(
                    type='private',
                    to=[
                        x['email'] for x in message['display_recipient']
                        if self.email != x['email']
                    ],
                    content=response,
                    sender_email=message['sender_email'],
                ))
        else:
            self.send_message(
                dict(
                    type='stream',
                    to=message['display_recipient'],
                    subject=message['subject'],
                    content=response,
                    sender_email=message['sender_email'],
                ))

    def get_config_info(self, bot_name, section=None):
        # type: (str, Optional[str]) -> Dict[str, Any]
        conf_file_path = os.path.realpath(
            os.path.join(our_dir, '..', 'bots', bot_name, bot_name + '.conf'))
        section = section or bot_name
        config = configparser.ConfigParser()
        config.readfp(
            open(conf_file_path))  # type: ignore # likely typeshed issue
        return dict(config.items(section))
예제 #4
0
파일: bot_lib.py 프로젝트: sonu96/zulip
class EmbeddedBotHandler:
    def __init__(self, user_profile):
        # type: (UserProfile) -> None
        # Only expose a subset of our UserProfile's functionality
        self.user_profile = user_profile
        self._rate_limit = RateLimit(20, 5)
        self.full_name = user_profile.full_name
        self.email = user_profile.email
        self.storage = StateHandler(user_profile)

    def send_message(self, message):
        # type: (Dict[str, Any]) -> None
        if self._rate_limit.is_legal():
            recipients = message['to'] if message[
                'type'] == 'stream' else ','.join(message['to'])
            internal_send_message(realm=self.user_profile.realm,
                                  sender_email=self.user_profile.email,
                                  recipient_type_name=message['type'],
                                  recipients=recipients,
                                  topic_name=message.get('subject', None),
                                  content=message['content'])
        else:
            self._rate_limit.show_error_and_exit()

    def send_reply(self, message, response):
        # type: (Dict[str, Any], str) -> None
        if message['type'] == 'private':
            self.send_message(
                dict(
                    type='private',
                    to=[x['email'] for x in message['display_recipient']],
                    content=response,
                    sender_email=message['sender_email'],
                ))
        else:
            self.send_message(
                dict(
                    type='stream',
                    to=message['display_recipient'],
                    subject=message['subject'],
                    content=response,
                    sender_email=message['sender_email'],
                ))

    def get_config_info(self):
        # type: () -> Dict[Text, Text]
        return get_bot_config(self.user_profile)
예제 #5
0
class EmbeddedBotHandler(object):
    def __init__(self, user_profile):
        # type: (UserProfile) -> None
        # Only expose a subset of our UserProfile's functionality
        self.user_profile = user_profile
        self._rate_limit = RateLimit(20, 5)
        self.full_name = user_profile.full_name
        self.email = user_profile.email
        self.storage = StateHandler(user_profile)

    def send_message(self, message):
        # type: (Dict[str, Any]) -> None
        if self._rate_limit.is_legal():
            recipients = message['to'] if message['type'] == 'stream' else ','.join(message['to'])
            internal_send_message(realm=self.user_profile.realm, sender_email=self.user_profile.email,
                                  recipient_type_name=message['type'], recipients=recipients,
                                  topic_name=message.get('subject', None), content=message['content'])
        else:
            self._rate_limit.show_error_and_exit()

    def send_reply(self, message, response):
        # type: (Dict[str, Any], str) -> None
        if message['type'] == 'private':
            self.send_message(dict(
                type='private',
                to=[x['email'] for x in message['display_recipient']],
                content=response,
                sender_email=message['sender_email'],
            ))
        else:
            self.send_message(dict(
                type='stream',
                to=message['display_recipient'],
                subject=message['subject'],
                content=response,
                sender_email=message['sender_email'],
            ))

    def get_config_info(self, bot_name, section=None):
        # type: (str, Optional[str]) -> Dict[str, Any]
        conf_file_path = os.path.realpath(os.path.join(
            our_dir, '..', 'bots', bot_name, bot_name + '.conf'))
        section = section or bot_name
        config = configparser.ConfigParser()
        config.readfp(open(conf_file_path))  # type: ignore # likely typeshed issue
        return dict(config.items(section))
예제 #6
0
class EmbeddedBotHandler:
    def __init__(self, user_profile: UserProfile) -> None:
        # Only expose a subset of our UserProfile's functionality
        self.user_profile = user_profile
        self._rate_limit = RateLimit(20, 5)
        self.full_name = user_profile.full_name
        self.email = user_profile.email
        self.storage = StateHandler(user_profile)
        self.user_id = user_profile.id

    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

    def send_message(self, message: Dict[str, Any]) -> Dict[str, Any]:
        if not self._rate_limit.is_legal():
            self._rate_limit.show_error_and_exit()

        if message["type"] == "stream":
            message_id = internal_send_stream_message_by_name(
                self.user_profile.realm,
                self.user_profile,
                message["to"],
                message["topic"],
                message["content"],
            )
            return {"id": message_id}

        assert message["type"] == "private"
        # Ensure that it's a comma-separated list, even though the
        # usual 'to' field could be either a List[str] or a str.
        recipients = ",".join(message["to"]).split(",")

        if len(message["to"]) == 0:
            raise EmbeddedBotEmptyRecipientsList(
                _("Message must have recipients!"))
        elif len(message["to"]) == 1:
            recipient_user = get_active_user(recipients[0],
                                             self.user_profile.realm)
            message_id = internal_send_private_message(self.user_profile,
                                                       recipient_user,
                                                       message["content"])
        else:
            message_id = internal_send_huddle_message(self.user_profile.realm,
                                                      self.user_profile,
                                                      recipients,
                                                      message["content"])
        return {"id": message_id}

    def send_reply(self,
                   message: Dict[str, Any],
                   response: str,
                   widget_content: Optional[str] = None) -> Dict[str, Any]:
        if message["type"] == "private":
            result = self.send_message(
                dict(
                    type="private",
                    to=[x["email"] for x in message["display_recipient"]],
                    content=response,
                    sender_email=message["sender_email"],
                ))
        else:
            result = self.send_message(
                dict(
                    type="stream",
                    to=message["display_recipient"],
                    topic=get_topic_from_message_info(message),
                    content=response,
                    sender_email=message["sender_email"],
                ))
        return {"id": result["id"]}

    def update_message(self, message: Dict[str, Any]) -> None:
        pass  # Not implemented

    # The bot_name argument exists only to comply with ExternalBotHandler.get_config_info().
    def get_config_info(self,
                        bot_name: str,
                        optional: bool = False) -> Dict[str, str]:
        try:
            return get_bot_config(self.user_profile)
        except ConfigError:
            if optional:
                return {}
            raise

    def quit(self, message: str = "") -> None:
        raise EmbeddedBotQuitException(message)