<commit_before>import asyncio
import json
import re

from sirbot.slack.message import SlackMessage, Attachment, Field, Button, \
    Select


class SlackEndpoint:
    def __init__(self, config):
        self.config = config

        self.config['candy']['user_regex'] = re.compile('<@U.{8}>')
        self.config['candy']['trigger_regex'] = re.compile(
            self.config['candy']['trigger']
        )

    def add(self, slack):
        slack.add_message('^help', self.help_, flags=re.IGNORECASE,
                          mention=True)
        slack.add_message('tell (<(#|@)(?P<to_id>[A-Z0-9]*)(|.*)?>)'
                          ' (?P<item>.*)',
                          self.publish, flags=re.IGNORECASE, mention=True,
                          admin=True)
        slack.add_message('hello', self.hello, mention=True,
                          flags=re.IGNORECASE)

        slack.add_command('/admin', func=self.share_admin, public=False)

        slack.add_message(self.config['candy']['trigger'],
                          self.add_candy_message)
        slack.add_command('/leaderboard', self.leaderboard, public=False)
        slack.add_event('reaction_added', self.add_candy_reaction)

        slack.add_command('/do', self.share_digital_ocean, public=True)

        slack.add_message('intro doc',
                          self.intro_doc, mention=True, flags=re.IGNORECASE)
        slack.add_message('what to do',
                          self.what_to_do, mention=True, flags=re.IGNORECASE)

        slack.add_action('choose_file', self.choose_file, public=False)
        slack.add_command('/file', self.file, public=False)

        slack.add_command('/gif', self.gif_search, public=False)
        slack.add_action('gif_search', self.gif_search_action, public=False)

        slack.add_event('team_join', self.team_join)

        slack.add_command('/pypi', self.pypi_search, public=True)

    async def hello(self, message, slack, *_):
        response = message.response()
        response.text = 'Hello'
        await slack.send(response)

    async def publish(self, message, slack, _, match):
        response = message.response()

        to_id = match.group('to_id')
        item = match.group('item')

        if to_id.startswith('C'):
            to = await slack.channels.get(to_id)
            if to:
                response.text = item
                response.to = to
            else:
                response.text = 'Sorry I can not understand the destination.'
                response.to = response.frm
        elif to_id.startswith('U'):
            to = await slack.users.get(to_id, dm=True)
            if to:
                response.text = item
                response.to = to
            else:
                response.text = 'Sorry I can not understand the destination.'
                response.to = response.frm
        else:
            response.text = 'Sorry I can not understand the destination.'
            response.to = response.frm

        await slack.send(response)

    async def help_(self, message, slack, *_):
        response = message.response()
        response.text = 'Help of the good Sir-bot-a-lot'

        help_msg = Attachment(fallback='help', color='good',
                              title='Common commands')
        hello_help = Field(title='Hello',
                           value='Say hello to Sir-bot-a-lot.'
                                 '\n`@sir-bot-a-lot hello`',
                           short=True)
        admin_help = Field(title='Admin',
                           value='Send a message to the pythondev admin team.'
                                 '\n `@sir-bot-a-lot admin ...`',
                           short=True)
        intro_doc_help = Field(title='Intro doc',
                               value='Link the intro doc.'
                                     '\n `@sir-bot-a-lot intro doc`',
                               short=True)
        what_to_do_help = Field(title='What to do',
                                value='Link the what to do doc.'
                                      '\n `@sir-bot-a-lot what to do`',
                                short=True)
        help_msg.fields.extend(
            (hello_help, admin_help, intro_doc_help, what_to_do_help))

        gif_help = Attachment(fallback='gif help', color='good',
                              title='Gif commands')
        gif_random_help = Field(title='Random',
                                value='Get a random gif.'
                                      '\n`@sir-bot-a-lot gif`',
                                short=True)
        gif_search_help = Field(title='Search',
                                value='Search for a gif.'
                                      '\n`@sir-bot-a-lot gif search ...`',
                                short=True)
        gif_trending_help = Field(title='Trending',
                                  value='Get a trending gif.'
                                        '\n`@sir-bot-a-lot gif trending`',
                                  short=True)
        gif_by_id_help = Field(title='By ID',
                               value='''Get a gif by it's id.
                               \n`@sir-bot-a-lot gif <gif_id>`''',
                               short=True)
        gif_help.fields.extend(
            (gif_random_help, gif_search_help, gif_trending_help,
             gif_by_id_help))

        response.attachments.extend((help_msg, gif_help))
        await slack.send(response)

    async def share_admin(self, command, slack, facades):

        response = command.response()
        to = await slack.groups.get('G1DRT62UC')

        att = Attachment(
            fallback='admin message',
            text=command.text,
            title='Message to the admin team by <@{}>'.format(command.frm.id),
        )

        response.to = to
        response.attachments.append(att)
        await slack.send(response)

    async def add_candy_message(self, message, slack, facades, *_):
        users_raw = self.config['candy']['user_regex'].findall(message.text)
        users = [user[2:-1] for user in users_raw if
                 user[2:-1] != message.frm.id]

        if not users:
            return

        candy = facades.get('candy')
        response = message.response()
        count = len(
            self.config['candy']['trigger_regex'].findall(message.text)
        )

        receivers_messages = list()
        for user in users:
            slack_user = await slack.users.get(user, dm=True)
            user_count = await candy.add(user, count)
            msg = response.clone()
            msg.to = slack_user
            msg.text = '<@{sender}> gave you {count} {trigger}.' \
                       ' You now have {user_count} {trigger}.'
            msg.text.format(
                sender=message.frm.id,
                count=count,
                trigger=self.config['candy']['trigger'],
                user_count=user_count
            )
            receivers_messages.append(msg)

        response.to = message.frm
        response.text = 'You gave {count} {trigger} to <@{user}>'.format(
            count=count,
            trigger=self.config['candy']['trigger'],
            user=', '.join(users))

        await slack.send(response)
        for msg in receivers_messages:
            await slack.send(msg)

    async def add_candy_reaction(self, event, slack, facades):
        if event['reaction'] == 'bdfl' and event['user'] != event['item_user']:
            candy = facades.get('candy')
            user_count = await candy.add(event['item_user'])<commit_msg>Fixes #34 - formatting dm messages fix (#35)<commit_after>import asyncio
import json
import re

from sirbot.slack.message import SlackMessage, Attachment, Field, Button, \
    Select


class SlackEndpoint:
    def __init__(self, config):
        self.config = config

        self.config['candy']['user_regex'] = re.compile('<@U.{8}>')
        self.config['candy']['trigger_regex'] = re.compile(
            self.config['candy']['trigger']
        )

    def add(self, slack):
        slack.add_message('^help', self.help_, flags=re.IGNORECASE,
                          mention=True)
        slack.add_message('tell (<(#|@)(?P<to_id>[A-Z0-9]*)(|.*)?>)'
                          ' (?P<item>.*)',
                          self.publish, flags=re.IGNORECASE, mention=True,
                          admin=True)
        slack.add_message('hello', self.hello, mention=True,
                          flags=re.IGNORECASE)

        slack.add_command('/admin', func=self.share_admin, public=False)

        slack.add_message(self.config['candy']['trigger'],
                          self.add_candy_message)
        slack.add_command('/leaderboard', self.leaderboard, public=False)
        slack.add_event('reaction_added', self.add_candy_reaction)

        slack.add_command('/do', self.share_digital_ocean, public=True)

        slack.add_message('intro doc',
                          self.intro_doc, mention=True, flags=re.IGNORECASE)
        slack.add_message('what to do',
                          self.what_to_do, mention=True, flags=re.IGNORECASE)

        slack.add_action('choose_file', self.choose_file, public=False)
        slack.add_command('/file', self.file, public=False)

        slack.add_command('/gif', self.gif_search, public=False)
        slack.add_action('gif_search', self.gif_search_action, public=False)

        slack.add_event('team_join', self.team_join)

        slack.add_command('/pypi', self.pypi_search, public=True)

    async def hello(self, message, slack, *_):
        response = message.response()
        response.text = 'Hello'
        await slack.send(response)

    async def publish(self, message, slack, _, match):
        response = message.response()

        to_id = match.group('to_id')
        item = match.group('item')

        if to_id.startswith('C'):
            to = await slack.channels.get(to_id)
            if to:
                response.text = item
                response.to = to
            else:
                response.text = 'Sorry I can not understand the destination.'
                response.to = response.frm
        elif to_id.startswith('U'):
            to = await slack.users.get(to_id, dm=True)
            if to:
                response.text = item
                response.to = to
            else:
                response.text = 'Sorry I can not understand the destination.'
                response.to = response.frm
        else:
            response.text = 'Sorry I can not understand the destination.'
            response.to = response.frm

        await slack.send(response)

    async def help_(self, message, slack, *_):
        response = message.response()
        response.text = 'Help of the good Sir-bot-a-lot'

        help_msg = Attachment(fallback='help', color='good',
                              title='Common commands')
        hello_help = Field(title='Hello',
                           value='Say hello to Sir-bot-a-lot.'
                                 '\n`@sir-bot-a-lot hello`',
                           short=True)
        admin_help = Field(title='Admin',
                           value='Send a message to the pythondev admin team.'
                                 '\n `@sir-bot-a-lot admin ...`',
                           short=True)
        intro_doc_help = Field(title='Intro doc',
                               value='Link the intro doc.'
                                     '\n `@sir-bot-a-lot intro doc`',
                               short=True)
        what_to_do_help = Field(title='What to do',
                                value='Link the what to do doc.'
                                      '\n `@sir-bot-a-lot what to do`',
                                short=True)
        help_msg.fields.extend(
            (hello_help, admin_help, intro_doc_help, what_to_do_help))

        gif_help = Attachment(fallback='gif help', color='good',
                              title='Gif commands')
        gif_random_help = Field(title='Random',
                                value='Get a random gif.'
                                      '\n`@sir-bot-a-lot gif`',
                                short=True)
        gif_search_help = Field(title='Search',
                                value='Search for a gif.'
                                      '\n`@sir-bot-a-lot gif search ...`',
                                short=True)
        gif_trending_help = Field(title='Trending',
                                  value='Get a trending gif.'
                                        '\n`@sir-bot-a-lot gif trending`',
                                  short=True)
        gif_by_id_help = Field(title='By ID',
                               value='''Get a gif by it's id.
                               \n`@sir-bot-a-lot gif <gif_id>`''',
                               short=True)
        gif_help.fields.extend(
            (gif_random_help, gif_search_help, gif_trending_help,
             gif_by_id_help))

        response.attachments.extend((help_msg, gif_help))
        await slack.send(response)

    async def share_admin(self, command, slack, facades):

        response = command.response()
        to = await slack.groups.get('G1DRT62UC')

        att = Attachment(
            fallback='admin message',
            text=command.text,
            title='Message to the admin team by <@{}>'.format(command.frm.id),
        )

        response.to = to
        response.attachments.append(att)
        await slack.send(response)

    async def add_candy_message(self, message, slack, facades, *_):
        users_raw = self.config['candy']['user_regex'].findall(message.text)
        users = [user[2:-1] for user in users_raw if
                 user[2:-1] != message.frm.id]

        if not users:
            return

        candy = facades.get('candy')
        response = message.response()
        count = len(
            self.config['candy']['trigger_regex'].findall(message.text)
        )

        receivers_messages = list()
        for user in users:
            slack_user = await slack.users.get(user, dm=True)
            user_count = await candy.add(user, count)
            msg = response.clone()
            msg.to = slack_user

            text_message = '<@{sender}> gave you {count} {trigger}.' \
                           ' You now have {user_count} {trigger}.'
            msg.text = text_message.format(
                sender=message.frm.id,
                count=count,
                trigger=self.config['candy']['trigger'],
                user_count=user_count
            )
            receivers_messages.append(msg)

        response.to = message.frm
        response.text = 'You gave {count} {trigger} to <@{user}>'.format(
            count=count,
            trigger=self.config['candy']['trigger'],
            user=', '.join(users))

        await slack.send(response)
        for msg in receivers_messages:
            await slack.send(msg)

    async def add_candy_reaction(self, event, slack, facades):
        if event['reaction'] == 'bdfl' and event['user'] != event['item_user']:
            candy = facades.get('candy')
            user_count = await candy.add(event['item_user'])
{'fraction_non_alphanumeric': 0.11874386653581943, 'fraction_numerical': 0.0015701668302257115, 'mean_word_length': 1.5869013369436453, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 24, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2068489', 'n_tokens_mistral': 4442, 'n_tokens_neox': 4231, 'n_words': 858}