Ejemplo n.º 1
0
async def init_application(loop, config):
    app = web.Application(loop=loop, debug=config["debug"])

    executor = ProcessPoolExecutor(MAX_WORKERS)

    slack_client = Slacker(SLACK_BOT_TOKEN)
    giphy_client = GiphyClient(loop, GIPHY_API_KEY, config["request_timeout"])

    handler = MainHandler(
        loop,
        executor,
        slack_client,
        giphy_client,
    )

    model_path = Path(config["model_path"])

    setup_main_handler(app, handler)

    app.on_startup.append(
        setup_startup_hooks(
            loop,
            executor,
            model_path,
            MAX_WORKERS,
        ))

    app.on_cleanup.append(
        setup_cleanup_hooks([
            partial(executor.shutdown, wait=True),
            slack_client.close,
            giphy_client.close,
        ]))

    return app
Ejemplo n.º 2
0
 async def send_message_to_each(self, users: list = None):
     """Send message to each user and/or channel."""
     if users is None:
         users = self.users
     async with Slacker(self.token) as slack:
         for user in users:
             await slack.chat.post_message(channel=user,
                                           text=self.text,
                                           attachments=json.dumps(
                                               self.attachments))
Ejemplo n.º 3
0
    def __init__(self, loop=None):
        self.slacker = Slacker(token=os.getenv("BOT_TOKEN", ""))
        self.websocket = None
        self.keepalive = None
        self.reconnecting = False
        self.listening = True
        self._message_id = 0

        if not loop:
            loop = asyncio.get_event_loop()

        self.loop = loop
Ejemplo n.º 4
0
    async def send_message_to_multiparty(self):
        """Send message to Slack 'multiparty direct message'.
        Minimal 2 and maximal 8 participants."""
        async with Slacker(self.token) as slack:
            if self.bot_id is None:
                self.bot_id = (await self.get_users_dict())[self.bot_name]

            response = await slack.mpim.open(self.users + [self.bot_id])
            self.channel_id = response.body['group']['id']
            print(
                f"Message was send to multiparty chat {self.channel_id} to users:"
            )
            print(', '.join(self.users))
            await self.send_message_to_each([self.channel_id])
Ejemplo n.º 5
0
 def __init__(self, config, opsdroid=None):
     """Create the connector."""
     super().__init__(config, opsdroid=opsdroid)
     _LOGGER.debug("Starting Slack connector")
     self.name = "slack"
     self.default_target = config.get("default-room", "#general")
     self.icon_emoji = config.get("icon-emoji", ':robot_face:')
     self.token = config["api-token"]
     self.slacker = Slacker(self.token)
     self.websocket = None
     self.bot_name = config.get("bot-name", 'opsdroid')
     self.known_users = {}
     self.keepalive = None
     self.reconnecting = False
     self.listening = True
     self._message_id = 0
Ejemplo n.º 6
0
    async def invite_people_in_private_channel(self,
                                               channel_id: str = None,
                                               users: list = None):
        """Invite people in the private channel (group). SUPER_TOKEN is needed."""
        if channel_id is None:
            channel_id = self.channel_id
        if users is None:
            users = self.users

        async with Slacker(self.token) as slack:
            res = await slack.groups.info(channel_id)
            members = res.body['group']['members']
            for user in users:
                if user not in members:
                    await slack.groups.invite(channel_id, user)
                    print(
                        f'User {user} was added into the group {channel_id}.')
Ejemplo n.º 7
0
    async def create_private_channel(self, channel_name: str) -> str:
        """Create private channel (group) and invite 'iwant-bot'.
        SUPER_TOKEN is needed for this action."""
        async with Slacker(self.token) as slack:
            response = await slack.groups.create(channel_name)
            self.channel_id = response.body['group']['id']
            print(
                f'Private channel <#{self.channel_id}|{channel_name}> was created.'
            )

            # Once the bot is added into the group, just 'BOT_TOKEN' is sufficient for posting.
            if self.bot_id is None:
                self.bot_id = (await self.get_users_dict())[self.bot_name]

            await self.invite_people_in_private_channel(users=[self.bot_id])
            print(f"<@{self.bot_id}|iwant-bot> was added into the"
                  f" private channel <#{self.channel_id}|{channel_name}>.")
        return self.channel_id
Ejemplo n.º 8
0
    async def post(self, slack_actions):
        token = Configuration()['slack-token']

        async with Slacker(token) as slack:
            for slack_action in slack_actions:
                channel = slack_action.destination
                style = slack_action.style
                try:
                    if style == 'brief':
                        await self.post_brief(slack, channel)
                    elif style == 'full':
                        await self.post_full(slack, channel)
                    else:
                        raise ValueError("Don't know slack message style: %s" %
                                         style)
                except SlackerError as error:
                    logging.error("SlackMessage.post: error=%s", error)
                    logging.error("SlackMessage.post: channel=%s", channel)
Ejemplo n.º 9
0
 async def get_users_dict(self) -> dict:
     async with Slacker(self.token) as slack:
         response = await slack.users.list()
     return {user['name']: user['id'] for user in response.body['members']}
Ejemplo n.º 10
0
 def _slacker():
     client = Slacker(token=self.slack_user_token)
     yield client
     client.close()
Ejemplo n.º 11
0
    # if request.method == 'POST':
    if 'challenge' in response:
        return web.json_response(data={"challenge": response.get('challenge')})

    print(response.get('event'))
    if response["event"]["type"] == "message":
        await reply_to_message(response["event"])

    return web.Response()

    # return web.json_response(data=response)


async def reply_to_message(event):
    text = (f"Ой <@{event['user']}>, я еще такой глупый! ")

    await slack_client.chat.post_message(event["channel"], text=text)


santa_app = web.Application()
santa_app.add_routes([
    web.get('/', handle),
    web.get('/msg', incomming_message),
    web.post('/msg', incomming_message),
    web.get('/{url}', unknown),
])

if __name__ == '__main__':
    slack_client = Slacker(SLACK_BOT_TOKEN)
    web.run_app(santa_app, port=80)