예제 #1
0
    def test_name(self):
        self.object.name = self.test_room_name
        assert self.object.name == self.test_room_name

        self.object = SlackConversation(self.test_id,
                                        name=self.test_room_name,
                                        api_client=mock.Mock())
        assert self.object.name == self.test_room_name
예제 #2
0
class TSlackRoom(object):
    room_class = None
    test_id = None
    test_room_name = None

    def setup(self):
        self.object = self.room_class(self.test_id, sc=mock.Mock())
        self.object._sc.api_call.return_value = {self.object.ATTRIBUTE_KEY: {}}

    def teardown(self):
        self.object = None

    def test_init(self):
        assert self.object.id == self.test_id
        for attr in self.room_class.BASE_ATTRIBUTES + self.room_class.EXTRA_ATTRIBUTES:
            if isinstance(attr, tuple):
                attr, attr_class = attr
            assert hasattr(self.object, attr)

    def test_channelid(self):
        assert self.object.channelid == self.test_id

    def test_channel(self):
        self.object.name = self.test_room_name
        assert self.object.channel == self.test_room_name

    def test_name(self):
        self.object.name = self.test_room_name
        assert self.object.name == self.test_room_name

        self.object = SlackConversation(self.test_id,
                                        name=self.test_room_name,
                                        api_client=mock.Mock())
        assert self.object.name == self.test_room_name

    def test_get_channel(self):
        test_channel = mock.Mock()
        test_channel.id = self.test_id
        test_channel.name = self.test_room_name
        self.object.api_client.server.channels.find.return_value = test_channel
        channel = self.room_class.get_channel(self.object.api_client,
                                              self.test_room_name)
        assert isinstance(channel, self.room_class)

    def test_set_topic(self):
        api_name = self.room_class.API_PREFIX + ".setTopic"
        new_topic_name = "A new topic"
        self.object.set_topic(new_topic_name)
        self.object.api_client.api_call.assert_called_with(
            api_name, channel=self.test_id, topic=new_topic_name)
예제 #3
0
async def dev_console(bot):
    import readline  # noqa -- only the import is needed for readline support in input

    banner = "Slackminion: Starting DEV MODE"
    if hasattr(bot, "user_manager"):
        delattr(bot, "user_manager")
    await asyncio.sleep(1)
    print(banner)
    print("=" * len(banner))
    print("""
    Note: Plugins loaded in this mode will send all output to
    the test window, rather than to slack.

    However, the commands themselves are not modified in any way.
    Typing commands from any loaded plugins ** WILL ACTUALLY RUN THE COMMAND **
    and any backend code associated. Only OUTPUT is suppressed.
    """)
    while not bot.webserver.thread.is_alive:
        print("Waiting for webserver to start...")
        await asyncio.sleep(1)
    while bot.runnable:
        try:
            command = input(
                "Slackminion DEV_MODE (type a !command.  use 'exit' to leave)> "
            )
            if command.lower() in ["quit", "exit"]:
                bot.runnable = False
                continue
            elif len(command) == 0:
                continue
        except (KeyboardInterrupt, EOFError) as e:
            bot.log.exception("Caught {}".format(e))
            bot.runnable = False
            raise
        user = SlackUser(user_info={
            "id": "UDEVMODE",
            "name": getpass.getuser()
        })
        user.set_admin(True)
        user.groups = ["sre"]
        channel = SlackConversation(
            conversation={
                "name": "#srebot_dev",
                "id": "CDEVMODE",
            },
            api_client=None,
        )
        payload = {
            "data": {
                "user": user,
                "channel": channel,
                "text": command,
                "ts": None,
            }
        }
        bot._bot_channels = {"CDEVMODE": channel}
        await bot._event_message(**payload)
        await asyncio.sleep(0.5)
예제 #4
0
 async def get_channel(self, channel_id):
     if channel_id in self.channels.keys():
         channel = self.channels.get(channel_id)
     else:
         channel = SlackConversation(None, self.api_client)
         await channel.load(channel_id)
         self._channels.update({channel_id: channel})
     if channel:
         return channel
예제 #5
0
 async def _event_channel_joined(self, **payload):
     try:
         self.log.debug(f'Channel joined: {payload}')
         channel_info = payload.get('data').get('channel')
         channel = SlackConversation(conversation=channel_info,
                                     api_client=self.api_client)
         self._channels.update({channel.id: channel})
     except Exception:  # noqa
         self.log.exception('Uncaught exception')
예제 #6
0
 async def _event_channel_joined(self, **payload):
     try:
         event_type, data = self._unpack_payload(**payload)
         self.log.debug(f"Received channel_joined event: {data}")
         channel_info = data.get("channel")
         channel = SlackConversation(conversation=channel_info,
                                     api_client=self.api_client)
         self._channels.update({channel.id: channel})
     except Exception:  # noqa
         self.log.exception("Uncaught exception")
예제 #7
0
async def dev_console(bot):
    import readline  # noqa -- only the import is needed for readline support in input
    banner = 'Slackminion: Starting DEV MODE'
    if hasattr(bot, 'user_manager'):
        delattr(bot, 'user_manager')
    await asyncio.sleep(1)
    print(banner)
    print('=' * len(banner))
    print("""
    Note: Plugins loaded in this mode will send all output to
    the test window, rather than to slack.

    However, the commands themselves are not modified in any way.
    Typing commands from any loaded plugins ** WILL ACTUALLY RUN THE COMMAND **
    and any backend code associated. Only OUTPUT is suppressed.
    """)
    while not bot.webserver.thread.is_alive:
        print('Waiting for webserver to start...')
        await asyncio.sleep(1)
    while bot.runnable:
        try:
            command = input("Slackminion DEV_MODE (type a !command.  use 'exit' to leave)> ")
            if command.lower() in ['quit', 'exit']:
                bot.runnable = False
                continue
            elif len(command) == 0:
                continue
        except (KeyboardInterrupt, EOFError) as e:
            bot.log.exception('Caught {}'.format(e))
            bot.runnable = False
            raise
        user = SlackUser(user_info={
            'id': 'UDEVMODE',
            'name': getpass.getuser()
        })
        user.set_admin(True)
        user.groups = ['sre']
        channel = SlackConversation(conversation={
            'name': '#srebot_dev',
            'id': 'CDEVMODE',
        }, api_client=None)
        payload = {
            'data': {
                'user': user,
                'channel': channel,
                'text': command,
                'ts': None,
            }
        }
        bot._bot_channels = {'CDEVMODE': channel}
        await bot._event_message(**payload)
        await asyncio.sleep(0.5)
예제 #8
0
    async def update_channels(self):
        self.log.debug("Starting update_channels")
        try:
            resp = await self.get_my_conversations()
            results = resp.get("channels")

            while resp.get("response_metadata").get("next_cursor"):
                cursor = resp.get("response_metadata").get("next_cursor")
                resp = await self.get_my_conversations(cursor=cursor)
                results.extend(resp.get("channels"))
                await asyncio.sleep(1)

            for channel in results:
                self._channels.update({
                    channel.get("id"):
                    SlackConversation(conversation=channel,
                                      api_client=self.api_client)
                })
        except Exception:  # noqa
            self.log.exception("update_channels failed due to exception")
        self.log.debug(f"Loaded {len(self.channels)} channels.")
예제 #9
0
    async def update_channels(self):
        self.log.debug('Starting update_channels')
        try:
            resp = await self.get_my_conversations()
            results = resp.get('channels')

            while resp.get('response_metadata').get('next_cursor'):
                cursor = resp.get('response_metadata').get('next_cursor')
                resp = await self.get_my_conversations(cursor=cursor)
                results.extend(resp.get('channels'))
                await asyncio.sleep(1)

            for channel in results:
                self._channels.update({
                    channel.get('id'):
                    SlackConversation(conversation=channel,
                                      api_client=self.api_client)
                })
        except Exception:  # noqa
            self.log.exception('update_channels failed due to exception')
        self.log.debug(f'Loaded {len(self.channels)} channels.')
예제 #10
0
    },
}

test_channel = {
    "name": test_channel_name,
    "id": test_channel_id,
    "is_channel": True,
    "is_im": False,
    "name_normalized": test_channel_name.lower(),
    "previous_names": [f"{test_channel_name}-old"],
}

test_dm = {
    "name": test_channel_name,
    "id": test_channel_id,
    "is_channel": True,
    "is_im": True,
}

test_user_response = {
    "ok": True,
    "user": {
        "id": test_user_id,
        "name": test_user_name,
    },
}

test_user = SlackUser(user_info=test_user_response["user"],
                      api_client=mock.Mock())
test_conversation = SlackConversation(test_channel, api_client=mock.Mock())