def test_helper_get_users_in_channel_returns_users():
    # Given
    channel_id = "foo"
    channel_ids = [channel_id]
    channel_names = ["foo"]
    expected_user_ids = ["1", "2", "3"]
    expected_user_names = [
        "a", "b", "c"
    ]  # needed for mock class even though unused by this test

    mock_python_slackclient = tests.common.mocks.MockPythonSlackclient(
        injectable_public_channels=channel_ids,
        injectable_channel_names=channel_names,
        injectable_user_ids=expected_user_ids,
        injectable_user_names=expected_user_names,
    )

    sut = SimpleSlackBot()
    sut._python_slackclient = mock_python_slackclient

    # When
    actual_user_names = sut.helper_get_users_in_channel(channel_names[0])

    # Then
    assert expected_user_names == actual_user_names
def test_helper_get_user_ids_returns_empty_list_when_found_zero_user_ids():
    # Given
    expected_user_ids = []
    mock_python_slackclient = tests.common.mocks.MockPythonSlackclient(
        injectable_user_ids=expected_user_ids)
    sut = SimpleSlackBot()
    sut._python_slackclient = mock_python_slackclient

    # When
    actual_user_ids = sut.helper_get_user_ids()

    # Then
    assert expected_user_ids == actual_user_ids
def test_helper_get_private_channel_ids_returns_private_channel_ids():
    # Given
    expected_private_channel_ids = ["1", "2", "3"]
    mock_python_slackclient = tests.common.mocks.MockPythonSlackclient(
        injectable_private_channels=expected_private_channel_ids)
    sut = SimpleSlackBot()
    sut._python_slackclient = mock_python_slackclient

    # When
    actual_private_channel_ids = sut.helper_get_private_channel_ids()

    # Then
    assert expected_private_channel_ids == actual_private_channel_ids
def test_helper_get_user_names_returns_empty_list_when_found_zero_user_names():
    # Given
    user_ids = ["1", "2",
                "3"]  # needed for mock class even though unused by this test
    expected_user_names = []
    mock_python_slackclient = tests.common.mocks.MockPythonSlackclient(
        injectable_user_ids=user_ids,
        injectable_user_names=expected_user_names)
    sut = SimpleSlackBot()
    sut._python_slackclient = mock_python_slackclient

    # When
    actual_user_names = sut.helper_get_user_names()

    # Then
    assert expected_user_names == actual_user_names
def test_helper_user_id_to_user_name_returns_user_name_when_found():
    # Given
    expected_user_names = ["foo"]
    expected_user_ids = ["bar"]

    mock_python_slackclient = tests.common.mocks.MockPythonSlackclient(
        injectable_user_ids=expected_user_ids,
        injectable_user_names=expected_user_names)

    sut = SimpleSlackBot()
    sut._python_slackclient = mock_python_slackclient

    # When
    actual_user_name = sut.helper_user_id_to_user_name(expected_user_ids[0])

    # Then
    assert expected_user_names[0] is actual_user_name
def test_helper_get_public_channel_ids_returns_empty_list_when_found_zero_public_channel_ids(
):
    # Given
    expected_public_channel_ids = []
    user_names = ["a", "b",
                  "c"]  # needed for mock class even though unused by this test
    mock_python_slackclient = tests.common.mocks.MockPythonSlackclient(
        injectable_public_channels=expected_public_channel_ids,
        injectable_user_names=user_names)
    sut = SimpleSlackBot()
    sut._python_slackclient = mock_python_slackclient

    # When
    actual_public_channel_ids = sut.helper_get_public_channel_ids()

    # Then
    assert expected_public_channel_ids == actual_public_channel_ids
def test_extract_slack_socket_reponse_returns_none_when_non_exiterror_slack_socket_exception_occurs(
    slacksocket_error, ):
    # Given
    mock_iterator = MockIterator(injectable_exception=slacksocket_error)

    mock_slack_socket = MockSlackSocket()
    mock_slack_socket.mock_iterator = mock_iterator

    sut = SimpleSlackBot("mock slack bot token")
    sut._slack_socket = mock_slack_socket

    expected_response = None

    # When
    actual_response = sut.extract_slack_socket_response()

    # Then
    assert expected_response == actual_response
def test_listen_stops_listening_when_slack_socket_keyboard_interrupt_exception_occurs(
    caplog, ):
    # Given
    mock_iterator = MockIterator(
        injectable_exception=slacksocket.errors.ExitError)

    mock_slack_socket = MockSlackSocket()
    mock_slack_socket.mock_iterator = mock_iterator

    sut = SimpleSlackBot("mock slack bot token")
    sut._slack_socket = mock_slack_socket

    # When
    with caplog.at_level(logging.INFO):
        sut.listen()

    # Then
    assert SimpleSlackBot.KEYBOARD_INTERRUPT_EXCEPTION_LOG_MESSAGE in caplog.text
def test_helper_user_id_to_user_name_returns_none_when_nothing_is_found():
    # Given
    expected_user_names = []
    expected_user_ids = []

    mock_python_slackclient = tests.common.mocks.MockPythonSlackclient(
        injectable_user_ids=expected_user_ids,
        injectable_user_names=expected_user_names)

    sut = SimpleSlackBot()
    sut._python_slackclient = mock_python_slackclient

    # When
    actual_user_name = sut.helper_user_id_to_user_name(expected_user_ids)

    # Then

    assert None is actual_user_name
class TestSimpleSlackBotParameterized(ParametrizedTestCase):
    def setUp(self):
        self.sut = SimpleSlackBot(slack_bot_token="MOCK BOT TOKEN")

    def tearDown(self):
        self.sut = None

    def test_register_actually_registers(self):
        # Given

        # When
        @self.sut.register(self.param)
        def mock_function():
            print("Mock function")

        # Then
        self.assertTrue(
            len(self.sut._registrations) == 1,
            "We only registered one function, therefore the count should be 1")
        self.assertTrue(
            len(self.sut._registrations[self.param]) == 1,
            "We only registered one function of this type, therefore the count should be 1"
        )

    def test_route_request_to_callbacks_actually_calls_callback(self):
        # Given
        registered_callback_was_called = False

        @self.sut.register(self.param)
        def mock_function(mock_slack_request):
            nonlocal registered_callback_was_called
            registered_callback_was_called = True

        # When
        self.sut.route_request_to_callbacks(
            SlackRequest(None, SlackEvent({"type": self.param})))

        # Then
        self.assertTrue(
            registered_callback_was_called,
            "We registered a function of this type and triggered it, so it should be called"
        )
def test_peek_returns_none_if_next_raises_stopiteration():
    # Given
    mock_iterator = MockIterator()
    mock_iterator.injectable_exception = StopIteration
    expected_yield = None

    # When
    actual_yield = SimpleSlackBot.peek(mock_iterator)

    # Then
    assert expected_yield == actual_yield
def test_extract_slack_socket_reponse_returns_response_when_no_exception_is_raised(
):
    # Given
    mock_iterator = MockIterator(injectable_yield=42)

    mock_slack_socket = MockSlackSocket()
    mock_slack_socket.mock_iterator = mock_iterator

    sut = SimpleSlackBot("mock slack bot token")
    sut._slack_socket = mock_slack_socket

    expected_first_value = 42
    expected_second_value_type = typing.Iterable

    # When
    actual_response = sut.extract_slack_socket_response()

    # Then
    assert expected_first_value == actual_response[0]
    assert isinstance(actual_response[1], expected_second_value_type)
def test_peek_returns_first_and_original_iterator():
    # Given
    mock_iterator = MockIterator()
    expected_yield = (42, mock_iterator)
    mock_iterator.injectable_yield = expected_yield[0]

    # When
    actual_yield = SimpleSlackBot.peek(mock_iterator)

    # Then
    assert expected_yield[0] == actual_yield[0]
    assert expected_yield[1] == mock_iterator
def test_init_adds_streamhandler_with_debug_level_when_init_is_called_with_debug(
):
    # Given
    mock_logger = MockLogger()
    SimpleSlackBot.logger = mock_logger

    # When
    SimpleSlackBot(slack_bot_token="mock_slack_bot_token", debug=True)

    # Then
    assert mock_logger.stream_handler is True
    assert mock_logger.logging_level == logging.DEBUG
def test_helper_channel_name_to_channel_id_returns_channel_name_when_found():
    # Given
    expected_channel_ids = ["foo"]
    expected_channel_names = ["bar"]
    user_names = ["baz"
                  ]  # needed for mock class even though unused by this test

    mock_python_slackclient = tests.common.mocks.MockPythonSlackclient(
        injectable_public_channels=expected_channel_ids,
        injectable_channel_names=expected_channel_names,
        injectable_user_names=user_names,
    )

    sut = SimpleSlackBot()
    sut._python_slackclient = mock_python_slackclient

    # When
    actual_channel_id = sut.helper_channel_name_to_channel_id(
        expected_channel_names[0])

    # Then
    assert expected_channel_ids[0] is actual_channel_id
def test_helper_channel_id_to_channel_name_returns_none_when_nothing_is_found(
):
    # Given
    expected_channel_names = []
    expected_channel_ids = []
    user_names = []  # needed for mock class even though unused by this test

    mock_python_slackclient = tests.common.mocks.MockPythonSlackclient(
        injectable_public_channels=expected_channel_ids,
        injectable_channel_names=expected_channel_names,
        injectable_user_names=user_names,
    )

    sut = SimpleSlackBot()
    sut._python_slackclient = mock_python_slackclient

    # When
    actual_channel_id = sut.helper_channel_id_to_channel_name(
        expected_channel_ids)

    # Then
    assert None is actual_channel_id
def test_init_prefers_parameters_over_environment_variables():
    # Given
    slack_bot_token = "token1"
    os.environ["SLACK_BOT_TOKEN"] = "token2"

    # When
    sut = SimpleSlackBot(slack_bot_token=slack_bot_token)

    # Then
    assert (
        sut._slack_bot_token == slack_bot_token
    ), "Should prioritize this value when storing over environment variable"
    assert (sut._slack_bot_token != os.environ["SLACK_BOT_TOKEN"]
            ), "Should not use this value, priorizing the paramter"
def test_register_actually_registers():
    # Given
    sut = SimpleSlackBot(slack_bot_token="MOCK BOT TOKEN")

    # When
    @sut.register("message")
    def mock_function():
        print("Mock function")

    # Then
    assert (len(sut._registrations) == 1
            ), "We only registered one function, therefore the count should be"
    assert (
        len(sut._registrations["message"]) == 1
    ), "We only registered one function of this type, therefore the count should be 1"
def test_init_raises_systemexit_exception_when_not_passed_slack_bot_token_or_has_environment_variable_to_fall_back_on(
):
    # Given
    # unset any state that may have been set by user or other tests prior
    if "SLACK_BOT_TOKEN" in os.environ:
        temp_slack_bot_token = os.environ["SLACK_BOT_TOKEN"]
        del os.environ["SLACK_BOT_TOKEN"]

    # When

    with pytest.raises(SystemExit):
        sut = SimpleSlackBot()

    # Then
    # reset environment variable if it was unset
    if "temp_slack_bot_token" in locals():
        os.environ["SLACK_BOT_TOKEN"] = temp_slack_bot_token
def test_start_errors_out_if_slackclient_rtm_has_invalid_ok():
    # Given
    sut = SimpleSlackBot("mock slack bot token")

    sut.connect = mock_connect

    mock_python_slackclient = tests.common.mocks.MockPythonSlackclient(False)
    sut._python_slackclient = mock_python_slackclient

    mock_listen = MockListen()
    sut.listen = mock_listen.mock_listen

    # When
    sut.start()

    # Then
    assert mock_listen.was_mock_listen_called is False
def test_route_request_to_callbacks_routes_correct_type_to_correct_callback():
    # Given
    class Monitor:
        was_called = False

        def monitor_if_called(self, request):
            Monitor.was_called = True

    mockslack_event = SlackEvent({"type": "message"})
    mock_slackrequest = SlackRequest(python_slackclient=None,
                                     slack_event=mockslack_event)
    sut = SimpleSlackBot(slack_bot_token="Mock slack bot token")
    monitor = Monitor()
    sut._registrations = {}
    sut._registrations["message"] = [monitor.monitor_if_called]

    # When
    sut.route_request_to_callbacks(mock_slackrequest)

    # Then
    assert Monitor.was_called is True
Example #22
0
from simple_slack_bot.simple_slack_bot import SimpleSlackBot

simple_slack_bot = SimpleSlackBot()


@simple_slack_bot.register("message")
def pong_callback(request):
    """This function is called every time a message is sent to a channel out Bot is in

    :param request: the SlackRequest we receive along with the event. See the README.md for full documentation
    :return: None
    """
    if request.message.lower() == "ping":
        request.write("Pong")


def main():
    simple_slack_bot.start()


if __name__ == "__main__":
    main()
Example #23
0
from simple_slack_bot.simple_slack_bot import SimpleSlackBot

simple_slack_bot = SimpleSlackBot(debug=True)


@simple_slack_bot.register("message")
def pong_callback(request):
    """This function is called every time a message is sent to a channel out Bot is in

    :param request: the SlackRequest we receive along with the event. See the README.md for full documentation
    :return: None
    """
    if request.message.lower() == "ping":
        request.write("Pong")


def main():
    simple_slack_bot.start()


if __name__ == "__main__":
    main()
Example #24
0
from simple_slack_bot.simple_slack_bot import SimpleSlackBot
import random
import requests
import re
import pyjosa
import time
import threading
from bs4 import BeautifulSoup

simple_slack_bot = SimpleSlackBot(debug=True)


@simple_slack_bot.register("hello")
def hello_callback(request):
    request.write("너하-! 난 너굴맨이라구 필요한게 있으면 불러달라구:racoon_man:")


def manage_cnt_after_time(user, sec):
    time.sleep(sec)
    if user_call_dict[user]['request_cnt'] > 0:
        user_call_dict[user]['request_cnt'] -= 1


# 타이핑 할 때마다 이벤트 발생
# @simple_slack_bot.register("user_typing")
# def user_typing_callback(request):
#     user_id = simple_slack_bot.helper_user_id_to_user_name(request._slack_event.event['user'])
#     request.write(f"I see you typing {user_id}")
#

# global var
 def setUp(self):
     self.sut = SimpleSlackBot(slack_bot_token="MOCK BOT TOKEN")
     self.mock_slacker = MockSlacker()
class TestSimpleSlackBot(unittest.TestCase):
    def setUp(self):
        self.sut = SimpleSlackBot(slack_bot_token="MOCK BOT TOKEN")
        self.mock_slacker = MockSlacker()

    def tearDown(self):
        self.sut = None

    # Getter tests
    def test_get_slacker_with_invalid_slacker(self):
        # Given

        # When
        actual_slacker = self.sut.get_slacker()

        # Then
        self.assertIsNone(
            actual_slacker,
            "The actual_slacker should be None, as we did not set it in Given")

    def test_get_slacker_with_valid_slacker(self):
        # Given
        expected_slack_socket = object
        self.sut._slacker = expected_slack_socket

        # When
        actual_slacker = self.sut.get_slacker()

        # Then
        self.assertEqual(
            expected_slack_socket, actual_slacker,
            "The actual_slacker should be the one we set in Given")

    def test_get_slack_socket_with_invalid_slack_socket(self):
        # Given

        # When
        retrieved_slack_socket = self.sut.get_slack_socket()

        # Then
        self.assertIsNone(
            retrieved_slack_socket,
            "The actual_slack_socket should be None, as we did not set in Given"
        )

    def test_get_slack_socket_with_valid_slack_socket(self):
        # Given
        expected_slack_socket = object
        self.sut._slackSocket = expected_slack_socket

        # When
        actual_slack_socket = self.sut.get_slack_socket()

        # Then
        self.assertEqual(
            expected_slack_socket, actual_slack_socket,
            "The actual_slack_socket should be the one we set in Given")

    # Helper function tests
    def test_helper_get_public_channel_ids_with_slacker_as_none(self):
        # Given
        # We purposefully don't set anything here so that sut's _slacker object is None
        expected_public_channel_ids = []

        # When
        actual_public_channel_ids = self.sut.helper_get_public_channel_ids()

        # Then
        self.assertEqual(
            expected_public_channel_ids, actual_public_channel_ids,
            "With no slacker set under the hood, there should be no public channel ids to retreive"
        )

    def test_helper_get_public_channel_ids_with_slacker_and_zero_channels(
            self):
        # Given
        self.mock_slacker.channels = []
        self.sut._slacker = self.mock_slacker
        expected_public_channel_ids = []

        # When
        actual_public_channel_ids = self.sut.helper_get_public_channel_ids()

        # Then
        self.assertEqual(
            expected_public_channel_ids, actual_public_channel_ids,
            "Slacker under the hood has no channels set, so there should be no public channel ids to retreive"
        )

    def test_helper_get_private_channel_ids_with_slacker_and_zero_channels(
            self):
        # Given
        self.sut._slacker = self.mock_slacker
        expected_private_channel_ids = []

        # When
        actual_private_channel_ids = self.sut.helper_get_private_channel_ids()

        # Then
        self.assertEqual(
            expected_private_channel_ids, actual_private_channel_ids,
            "Slacker under the hood has no channels set, so there should be no private channel ids to retreive"
        )
 def setUp(self):
     self.sut = SimpleSlackBot(slack_bot_token="MOCK BOT TOKEN")
Example #28
0
from simple_slack_bot.simple_slack_bot import SimpleSlackBot
from slackclient import SlackClient

# Put # before name if it's a public channel. Make sure your bot is a channel member
# You must define REPORTS_CHANNEL key in Heroku
REPORTS_CHANNEL = os.environ.get("REPORTS_CHANNEL")

# This is the link of the repo where the bot code is available (Make sure it doesn't end with "/" )
# You must define BOT_REPO key in Heroku
BOT_REPO_URL = os.environ.get("BOT_REPO")

# Bot name and username
# You must define BOT_NAME key in Heroku
BOT_NAME = os.environ.get("BOT_NAME")

stan = SimpleSlackBot()
sc = SlackClient(os.environ.get("SLACK_BOT_TOKEN"))
reps = replies.Replies()

simple_mess = [
    "What did you do today?", "Are there any obstacles impeding your progress?"
]

detail_mess = [
    "What did you do yesterday?", "What are you going to do today?",
    "Are there any obstacles impeding your progress?"
]


@stan.register("app_mention")
def mentions(request):
Example #29
0
from yaml import load
from redis import Redis
from dndtextapi_client import DNDTextAPIClient

from simple_slack_bot.simple_slack_bot import SimpleSlackBot

# Read in config from config.yml
f = open('config.yml', 'r')
config = load(f)
f.close()

# Set up config required by simple slack bot
environ['SLACK_BOT_TOKEN'] = config['slack']['apitoken']

# Creating SimpleSlackBot automatically checks connectivity to the API on startup
simple_slack_bot = SimpleSlackBot(debug=True)
bot_mention = '<@{}>'.format(simple_slack_bot._BOT_ID).lower()

# Connect to the Redis store
REDIS_HOST = config['redis']['host']
REDIS_PORT = config['redis']['port']
redis = Redis(host=REDIS_HOST, port=REDIS_PORT)

# TODO: What does __name__ here do?
logger = logging.getLogger(__name__)

API_HOST = config['api']['host']
api_client = DNDTextAPIClient(API_HOST)


@simple_slack_bot.register("message")