Beispiel #1
0
    def send_card(self,
                  body: str = '',
                  to: Identifier = None,
                  in_reply_to: Message = None,
                  summary: str = None,
                  title: str = '',
                  link: str = None,
                  image: str = None,
                  thumbnail: str = None,
                  color: str = 'green',
                  fields: Tuple[Tuple[str, str], ...] = ()) -> None:
        """
        Sends a card.

        A Card is a special type of preformatted message. If it matches with a backend similar concept like on
        Slack or Hipchat it will be rendered natively, otherwise it will be sent as a regular formatted message.

        :param body: main text of the card in markdown.
        :param to: the card is sent to this identifier (Room, RoomOccupant, Person...).
        :param in_reply_to: the original message this message is a reply to (optional).
        :param summary: (optional) One liner summary of the card, possibly collapsed to it.
        :param title: (optional) Title possibly linking.
        :param link: (optional) url the title link is pointing to.
        :param image: (optional) link to the main image of the card.
        :param thumbnail: (optional) link to an icon / thumbnail.
        :param color: (optional) background color or color indicator.
        :param fields: (optional) a tuple of (key, value) pairs.
        """
        frm = in_reply_to.to if in_reply_to else self.bot_identifier
        if to is None:
            if in_reply_to is None:
                raise ValueError('Either to or in_reply_to needs to be set.')
            to = in_reply_to.frm
        self._bot.send_card(Card(body, frm, to, in_reply_to, summary, title, link, image, thumbnail, color, fields))
Beispiel #2
0
    def send_card(self, card: Card):
        if isinstance(card.to, RoomOccupant):
            card.to = card.to.room
        to_humanreadable, to_channel_id = self._prepare_message(card)
        attachment = {}
        if card.summary:
            attachment['pretext'] = card.summary
        if card.title:
            attachment['title'] = card.title
        if card.link:
            attachment['title_link'] = card.link
        if card.image:
            attachment['image_url'] = card.image
        if card.thumbnail:
            attachment['thumb_url'] = card.thumbnail
        attachment['text'] = card.body

        if card.color:
            attachment['color'] = COLORS[card.color] if card.color in COLORS else card.color

        if card.fields:
            attachment['fields'] = [{'title': key, 'value': value, 'short': True} for key, value in card.fields]

        data = {'text': ' ', 'channel': to_channel_id, 'attachments': json.dumps([attachment]), 'as_user': '******'}
        try:
            log.debug('Sending data:\n%s', data)
            self.api_call('chat.postMessage', data=data)
        except Exception:
            log.exception(
                "An exception occurred while trying to send a card to %s.[%s]" % (to_humanreadable, card)
            )
Beispiel #3
0
    def send_card(self, card: Card):
        if isinstance(card.to, RoomOccupant):
            card.to = card.to.room
        to_humanreadable, to_channel_id = self._prepare_message(card)
        attachment = {}
        if card.summary:
            attachment['pretext'] = card.summary
        if card.title:
            attachment['title'] = card.title
        if card.link:
            attachment['title_link'] = card.link
        if card.image:
            attachment['image_url'] = card.image
        if card.thumbnail:
            attachment['thumb_url'] = card.thumbnail

        if card.color:
            attachment['color'] = COLORS[
                card.color] if card.color in COLORS else card.color

        if card.fields:
            attachment['fields'] = [{
                'title': key,
                'value': value,
                'short': True
            } for key, value in card.fields]

        limit = min(self.bot_config.MESSAGE_SIZE_LIMIT, SLACK_MESSAGE_LIMIT)
        # Slack attachment text will not display an empty string.  Use an empty string when no
        # message body has been supplied to handle github issue #1202
        if card.body:
            parts = self.prepare_message_body(card.body, limit)
        else:
            parts = [""]
        part_count = len(parts)
        footer = attachment.get("footer", "")
        for i in range(part_count):
            if part_count > 1:
                attachment["footer"] = "{} [{}/{}]".format(
                    footer, i + 1, part_count)
            attachment["text"] = parts[i]
            data = {
                'text': ' ',
                'channel': to_channel_id,
                'attachments': json.dumps([attachment]),
                'link_names': '1',
                'as_user': '******'
            }
            try:
                log.debug('Sending data:\n%s', data)
                self.api_call('chat.postMessage', data=data)
            except Exception:
                log.exception(
                    "An exception occurred while trying to send a card to %s.[%s]"
                    % (to_humanreadable, card))
Beispiel #4
0
    def send_text_with_buttons(self, recipient_id, message, buttons):
        if len(buttons) > 5:
            logging.warn("Slack API currently allows only up to 5 buttons."
                         "If you add more, all will be ignored.")
            return self.send_text_message(recipient_id, message)
        card = Card(summary=message,
                    title="Nachricht vom {}".format(self.bot.bot_identifier),
                    to=self._evaluate_identifier_by_recipient_id(recipient_id),
                    fields=self._convert_to_slack_buttons(buttons))

        self._send_to_card_or_text(card, recipient_id)
    def send_card(self, card: Card):
        if isinstance(card.to, RoomOccupant):
            card.to = card.to.room

        to_humanreadable, to_channel_id = self._prepare_message(card)

        attachment = {}
        if card.summary:
            attachment["pretext"] = card.summary
        if card.title:
            attachment["title"] = card.title
        if card.link:
            attachment["title_link"] = card.link
        if card.image:
            attachment["image_url"] = card.image
        if card.thumbnail:
            attachment["thumb_url"] = card.thumbnail
        attachment["text"] = card.body

        if card.color:
            attachment["color"] = (COLORS[card.color]
                                   if card.color in COLORS else card.color)

        if card.fields:
            attachment["fields"] = [{
                "title": key,
                "value": value,
                "short": True
            } for key, value in card.fields]

        data = {"attachments": [attachment]}

        if card.to:
            if isinstance(card.to, MattermostRoom):
                data["channel"] = card.to.name

        try:
            log.debug("Sending data:\n%s", data)
            # We need to send a webhook - mattermost has no api endpoint for attachments/cards
            # For this reason, we need to build our own url, since we need /hooks and not /api/v4
            # Todo: Reminder to check if this is still the case
            self.driver.webhooks.call_webhook(self.cards_hook, options=data)
        except (
                InvalidOrMissingParameters,
                NotEnoughPermissions,
                ContentTooLarge,
                FeatureDisabled,
                NoAccessTokenProvided,
        ):
            log.exception(
                "An exception occurred while trying to send a card to %s.[%s]"
                % (to_humanreadable, card))
	def send_card(self, card: Card):
		if isinstance(card.to, RoomOccupant):
			card.to = card.to.room

		to_humanreadable, to_channel_id = self._prepare_message(card)

		attachment = {}
		if card.summary:
			attachment['pretext'] = card.summary
		if card.title:
			attachment['title'] = card.title
		if card.link:
			attachment['title_link'] = card.link
		if card.image:
			attachment['image_url'] = card.image
		if card.thumbnail:
			attachment['thumb_url'] = card.thumbnail
		attachment['text'] = card.body

		if card.color:
			attachment['color'] = COLORS[card.color] if card.color in COLORS else card.color

		if card.fields:
			attachment['fields'] = [{'title': key, 'value': value, 'short': True} for key, value in card.fields]

		data = {
			'attachments': [attachment]
		}

		if card.to:
			if isinstance(card.to, MattermostRoom):
				data['channel'] = card.to.name

		try:
			log.debug('Sending data:\n%s', data)
			# We need to send a webhook - mattermost has no api endpoint for attachments/cards
			# For this reason, we need to build our own url, since we need /hooks and not /api/v4
			# Todo: Reminder to check if this is still the case
			self.driver.webhooks.call_webhook(self.cards_hook, options=data)
		except (
					InvalidOrMissingParameters,
					NotEnoughPermissions,
					ContentTooLarge,
					FeatureDisabled,
					NoAccessTokenProvided
				):
			log.exception(
				"An exception occurred while trying to send a card to %s.[%s]" % (to_humanreadable, card)
			)
Beispiel #7
0
    def send_card(self, card: Card):
        if isinstance(card.to, RoomOccupant):
            card.to = card.to.room
        to_humanreadable, to_channel_id = self._prepare_message(card)
        attachment = {}
        if card.summary:
            attachment['pretext'] = card.summary
        if card.title:
            attachment['title'] = card.title
        if card.link:
            attachment['title_link'] = card.link
        if card.image:
            attachment['image_url'] = card.image
        if card.thumbnail:
            attachment['thumb_url'] = card.thumbnail

        if card.color:
            attachment['color'] = COLORS[
                card.color] if card.color in COLORS else card.color

        if card.fields:
            attachment['fields'] = [{
                'title': key,
                'value': value,
                'short': True
            } for key, value in card.fields]

        limit = min(self.bot_config.MESSAGE_SIZE_LIMIT, SLACK_MESSAGE_LIMIT)
        parts = self.prepare_message_body(card.body, limit)
        part_count = len(parts)
        footer = attachment.get('footer', '')
        for i in range(part_count):
            if part_count > 1:
                attachment['footer'] = f'{footer} [{i + 1}/{part_count}]'
            attachment['text'] = parts[i]
            data = {
                'text': ' ',
                'channel': to_channel_id,
                'attachments': json.dumps([attachment]),
                'link_names': '1',
                'as_user': '******'
            }
            try:
                log.debug('Sending data:\n%s', data)
                self.api_call('chat.postMessage', data=data)
            except Exception:
                log.exception(
                    f'An exception occurred while trying to send a card to {to_humanreadable}.[{card}]'
                )
Beispiel #8
0
    def send_card(self, card: Card):
        if isinstance(card.to, RoomOccupant):
            card.to = card.to.room
        to_humanreadable, to_channel_id = self._prepare_message(card)
        attachment = {}
        if card.summary:
            attachment["pretext"] = card.summary
        if card.title:
            attachment["title"] = card.title
        if card.link:
            attachment["title_link"] = card.link
        if card.image:
            attachment["image_url"] = card.image
        if card.thumbnail:
            attachment["thumb_url"] = card.thumbnail

        if card.color:
            attachment["color"] = (COLORS[card.color]
                                   if card.color in COLORS else card.color)

        if card.fields:
            attachment["fields"] = [{
                "title": key,
                "value": value,
                "short": True
            } for key, value in card.fields]

        limit = min(self.bot_config.MESSAGE_SIZE_LIMIT, SLACK_MESSAGE_LIMIT)
        parts = self.prepare_message_body(card.body, limit)
        part_count = len(parts)
        footer = attachment.get("footer", "")
        for i in range(part_count):
            if part_count > 1:
                attachment["footer"] = f"{footer} [{i + 1}/{part_count}]"
            attachment["text"] = parts[i]
            data = {
                "channel": to_channel_id,
                "attachments": json.dumps([attachment]),
                "link_names": "1",
                "as_user": "******",
            }
            try:
                log.debug("Sending data:\n%s", data)
                self.webclient.chat_postMessage(**data)
            except Exception:
                log.exception(
                    f"An exception occurred while trying to send a card to {to_humanreadable}.[{card}]"
                )
        return None
Beispiel #9
0
    def send_card(self, card: Card):
        if isinstance(card.to, RoomOccupant):
            card.to = card.to.room
        to_humanreadable, to_channel_id = self._prepare_message(card)
        attachment = {}
        if card.summary:
            attachment['pretext'] = card.summary
        if card.title:
            attachment['title'] = card.title
        if card.link:
            attachment['title_link'] = card.link
        if card.image:
            attachment['image_url'] = card.image
        if card.thumbnail:
            attachment['thumb_url'] = card.thumbnail

        if card.color:
            attachment['color'] = COLORS[card.color] if card.color in COLORS else card.color

        if card.fields:
            attachment['fields'] = [{'title': key, 'value': value, 'short': True} for key, value in card.fields]

        limit = min(self.bot_config.MESSAGE_SIZE_LIMIT, SLACK_MESSAGE_LIMIT)
        parts = self.prepare_message_body(card.body, limit)
        part_count = len(parts)
        footer = attachment.get("footer", "")
        for i in range(part_count):
            if part_count > 1:
                attachment["footer"] = "{} [{}/{}]".format(footer, i + 1, part_count)
            attachment["text"] = parts[i]
            data = {
                'text': ' ',
                'channel': to_channel_id,
                'attachments': json.dumps([attachment]),
                'link_names': '1',
                'as_user': '******'
            }
            try:
                log.debug('Sending data:\n%s', data)
                self.api_call('chat.postMessage', data=data)
            except Exception:
                log.exception(
                    "An exception occurred while trying to send a card to %s.[%s]" % (to_humanreadable, card)
                )
    def send_slack_attachment_action(self,
                                     body: str = '',
                                     to: Identifier = None,
                                     in_reply_to: Message = None,
                                     summary: str = None,
                                     title: str = '',
                                     link: str = None,
                                     image: str = None,
                                     thumbnail: str = None,
                                     color: str = 'green',
                                     fields: Tuple[Tuple[str, str], ...] = (),
                                     callback_id: str = None,
                                     fallback: str = None,
                                     actions=[]) -> None:
        """
        send attachment message.
        this code is customized from errbot.botplugin and errbot.backends.slack
        """

        frm = in_reply_to.to if in_reply_to else self.bot_identifier
        if to is None:
            if in_reply_to is None:
                raise ValueError('Either to or in_reply_to needs to be set.')
            to = in_reply_to.frm

        if isinstance(to, RoomOccupant):
            to = to.room
        to_humanreadable, to_channel_id = self._bot._prepare_message(
            Card(body, frm, to, in_reply_to, summary, title, link, image,
                 thumbnail, color, fields))
        attachment = {}
        if actions:
            attachment['actions'] = actions
        if callback_id:
            attachment['callback_id'] = callback_id

        if summary:
            attachment['pretext'] = summary
        if title:
            attachment['title'] = title
        if link:
            attachment['title_link'] = link
        if image:
            attachment['image_url'] = image
        if thumbnail:
            attachment['thumb_url'] = thumbnail
        if fallback:
            attachment['fallback'] = fallback
        attachment['text'] = body

        if color:
            attachment['color'] = self.COLORS[color] if color in self.COLORS else color

        if fields:
            attachment['fields'] = [{
                'title': key,
                'value': value,
                'short': True
            } for key, value in fields]

        data = {
            'text': ' ',
            'channel': to_channel_id,
            'attachments': json.dumps([attachment]),
            'link_names': '1',
            'as_user': '******'
        }
        try:
            self.log.debug('Sending data:\n%s', data)
            self._bot.api_call('chat.postMessage', data=data)
        except Exception as e:
            self.log.exception(
                "An exception occurred while trying to send a card to %s.[%s]"
                % (to_humanreadable, data))