Exemplo n.º 1
0
    def start_group_chats(self):
        """
        Groups all participating people randomly and start group chats. Called by schedule_group_chats()
        """
        db = DataBaseUtils(channel_name=self.channel_name)
        users_in_person = db.get_users(participate=True, virtual=False)
        users_virtual = db.get_users(participate=True, virtual=True)

        random.seed(round(time.time()) % 1e5 ) ## put random seed to make sure we don't get the same groups everytime
        random_groups_in_person = self._assign_random_groups(users_in_person)
        random_groups_virtual = self._assign_random_groups(users_virtual)

        # random_groups = random_groups_in_person + random_groups_virtual

        client = WebClient(token=os.environ.get(self.bot_token))

        # initialize chats for each random group
        for group in random_groups_in_person:
            try:
                result = client.conversations_open(
                    token=self.bot_token,
                    users=','.join(group))

                #TODO: edit the message to look better
                client.chat_postMessage(
                    token=self.bot_token,
                    channel=result['channel']['id'],
                    text="Ta daa! \nDestiny created this group. Everyone here is up for IN-PERSON meetup. "+\
                         "Consider using <https://www.when2meet.com|when2meet> to schedule a time.\n"+\
                         "Now, answer the following question: \n\n" +
                         random.sample(self.chat_prompts['responses'], 1)[0])

            except SlackApiError as e:
                self.logger.error(f"Error scheduling message for users {group}: {e}")

        self.logger.info("finieshed creating in person random groups")

        for group in random_groups_virtual:
            try:
                result = client.conversations_open(
                    token=self.bot_token,
                    users=','.join(group))

                #TODO: edit the message to look better
                client.chat_postMessage(
                    token=self.bot_token,
                    channel=result['channel']['id'],
                    text="Ta daa! \nDestiny created this group. Everyone here is up for VIRTUAL meetup. "+\
                         "Consider using <https://www.when2meet.com|when2meet> to schedule a time.\n"+\
                         "Now, answer the following question: \n\n" +
                         random.sample(self.chat_prompts['responses'], 1)[0])

            except SlackApiError as e:
                self.logger.error(f"Error scheduling message for users {group}: {e}")

        self.logger.info("finieshed creating virtual random groups")
Exemplo n.º 2
0
class SlackClient(object):
    def __init__(self, token=None):
        self.client = WebClient(token=token or Config.SLACK_OAUTH_ACCESS_TOKEN)

    def post_message_to_channel(self, channel: str, message: str):
        try:
            response = self.client.chat_postMessage(channel=channel,
                                                    text=message)
            return response.get('message')
        except SlackApiError as e:
            # You will get a SlackApiError if "ok" is False
            print(f"Got an error: {e.response['error']}")

    def post_blocks_message_to_channel(self, channel: str, blocks: list):
        try:
            response = self.client.chat_postMessage(channel=channel,
                                                    blocks=blocks)
            return response.get('message')
        except SlackApiError as e:
            print(f"Got an error: {e.response['error']}")

    def create_direct_message(self, users: list):
        response = self.client.conversations_open(users=users)
        if response.data.get('ok'):
            return response.get('channel')

    def get_user_by_email(self, email: str) -> SlackResponse:
        user = self.client.api_call(api_method='users.lookupByEmail',
                                    params={"email": email})
        if user.data.get('ok'):
            return user.data.get('user')
Exemplo n.º 3
0
 def send(message):
     try:
         client = WebClient(token=config.token)
         channel = client.conversations_open(
             users=config.admins)['channel']['id']
         client.chat_postMessage(channel=channel, text=message)
     except Exception:
         traceback.print_exc()
Exemplo n.º 4
0
 def send_dm(self, message_text, user_slack_id):
     if message_text is None or message_text == "":
         return
     try:
         client = WebClient(token=self.token)
         im = client.conversations_open(users=user_slack_id)
         channel_id = im["channel"]["id"]
         self.send_message(message_text, channel_id)
     except SlackApiError:
         logging.exception("Error sending DM response to: " +
                           str(user_slack_id))
Exemplo n.º 5
0
class SlackManager:
    def __init__(self, token):
        self.client = WebClient(token=token)

    def send_message(self, user, message):
        response = self.client.users_lookupByEmail(email=user.email)
        if not response.data['ok']:
            return False
        user_slack_id = response.data['user']['id']
        response = self.client.conversations_open(users=user_slack_id)
        if not response.data['ok']:
            return False
        channel = response.data['channel']['id']
        self.client.chat_postMessage(channel=channel, text=message)
Exemplo n.º 6
0
 def wrapper(config, *args, **kwargs):
     try:
         return f(config, *args, **kwargs)
     except HandledError:
         pass
     except (json.JSONDecodeError, requests.ConnectionError,
             requests.HTTPError, requests.ReadTimeout) as e:
         # Exception type leaked from the bugzilla API.  Assume transient
         # network problem; don't send message.
         print(e)
     except (socket.timeout, urllib.error.URLError) as e:
         # Exception type leaked from the slack_sdk API.  Assume transient
         # network problem; don't send message.
         print(e)
     except Exception:
         try:
             message = f'Caught exception:\n```\n{traceback.format_exc()}```'
             client = WebClient(token=config.slack_token)
             channel = client.conversations_open(
                 users=[config.error_notification])['channel']['id']
             client.chat_postMessage(channel=channel, text=message)
         except Exception:
             traceback.print_exc()
Exemplo n.º 7
0
    def send_message(self, user_id):
        """
        Ask a user whether he/she would like to participate in the upcoming round of random group.

        :param user_id: a string that represents a user id
        :return: None
        """
        client = WebClient(token=os.environ.get(self.bot_token))

        try:
            result = client.conversations_open(
                token=self.bot_token,
                users=user_id)
            with open('responses/rg_participation_message.json') as f:
                js_message = json.loads(f.read())
            # interactive message asking if they will participate
            client.chat_postMessage(
                token=self.bot_token,
                channel=result['channel']['id'],
                text="Would you like to participate in this week's random groups?",
                blocks=js_message)

        except SlackApiError as e:
            self.logger.error(f"Error scheduling message for user {user_id}: {e}")
Exemplo n.º 8
0
class SlackClient(object):
    def __init__(self, config: dict):
        assert (config.get("SLACK_BOT_TOKEN")
                is not None), "SLACK_BOT_TOKEN required config"
        self.config = config
        self.client = WebClient(config["SLACK_BOT_TOKEN"])

    def open_conversation(self, user: str) -> Optional[str]:
        try:
            response = self.client.conversations_open(users=user)
            channel = response.data.get("channel", {}).get("id")
            if channel:
                return channel
        except SlackApiError as e:
            logger.error("Exception in open_conversation", exc_info=e)
        return None

    def send_text_message(self, channel: str, message: str):
        try:
            self.client.chat_postMessage(channel=channel, text=message)
            return True
        except SlackApiError as e:
            logger.error("Exception in send_text_message", exc_info=e)
        return False