示例#1
0
def test_token_refresh_failed():
    # Client should raise TokenRefreshError is token refresh returns error
    def token_update_callback(update_data):
        return update_data

    sc = SlackClient(
        client_id="12345",
        client_secret="12345",
        refresh_token="refresh_token",
        token_update_callback=token_update_callback,
    )

    with pytest.raises(TokenRefreshError):
        with responses.RequestsMock() as rsps:
            rsps.add(
                responses.POST,
                "https://slack.com/api/channels.list",
                status=200,
                json={
                    "ok": False,
                    "error": "invalid_auth"
                },
            )

            rsps.add(
                responses.POST,
                "https://slack.com/api/oauth.access",
                status=200,
                json={
                    "ok": False,
                    "error": "invalid_auth"
                },
            )

            sc.api_call("channels.list")
示例#2
0
def test_token_refresh_on_initial_api_request():
    # Client should fetch and append an access token on the first API request

    # When the token is refreshed, the client will call this callback
    access_token = "xoxa-2-abcdef"
    client_args = {}

    def token_update_callback(update_data):
        client_args[update_data["team_id"]] = update_data

    sc = SlackClient(
        client_id="12345",
        client_secret="12345",
        refresh_token="refresh_token",
        token_update_callback=token_update_callback,
    )

    # The client starts out with an empty token
    assert sc.token is None

    # Mock both the main API request and the token refresh request
    with responses.RequestsMock() as rsps:
        rsps.add(
            responses.POST,
            "https://slack.com/api/auth.test",
            status=200,
            json={"ok": True},
        )

        rsps.add(
            responses.POST,
            "https://slack.com/api/oauth.access",
            status=200,
            json={
                "ok": True,
                "access_token": access_token,
                "token_type": "app",
                "expires_in": 3600,
                "team_id": "T2U81E2FP",
                "enterprise_id": "T2U81ELK",
            },
        )

        # Calling the API for the first time will trigger a token refresh
        sc.api_call("auth.test")

        # Store the calls in order
        calls = {}
        for index, call in enumerate(rsps.calls):
            calls[index] = {"url": call.request.url}

        # After the initial call, the refresh method will update the client's token,
        # then the callback will update client_args
        assert sc.token == access_token
        assert client_args["T2U81E2FP"]["access_token"] == access_token

        # Verify that the client first tried to call the API, refreshed the token, then retried
        assert calls[0]["url"] == "https://slack.com/api/oauth.access"
        assert calls[1]["url"] == "https://slack.com/api/auth.test"
示例#3
0
def test_token_refresh_on_expired_token():
    # Client should fetch and append an access token on the first API request

    # When the token is refreshed, the client will call this callback
    client_args = {}

    def token_update_callback(update_data):
        client_args[update_data["team_id"]] = update_data

    sc = SlackClient(
        client_id="12345",
        client_secret="12345",
        refresh_token="refresh_token",
        token_update_callback=token_update_callback,
    )

    # Set the token TTL to some time in the past
    sc.access_token_expires_at = 0

    # Mock both the main API request and the token refresh request
    with responses.RequestsMock() as rsps:
        rsps.add(
            responses.POST,
            "https://slack.com/api/auth.test",
            status=200,
            json={"ok": True},
        )

        rsps.add(
            responses.POST,
            "https://slack.com/api/oauth.access",
            status=200,
            json={
                "ok": True,
                "access_token": "xoxa-2-abcdef",
                "token_type": "app",
                "expires_in": 3600,
                "team_id": "T2U81E2FP",
                "enterprise_id": "T2U81ELK",
            },
        )

        # Calling the API for the first time will trigger a token refresh
        sc.api_call("auth.test")

        # Store the calls in order
        calls = {}
        for index, call in enumerate(rsps.calls):
            calls[index] = {"url": call.request.url}

        # Verify that the client first fetches the token, then submits the request
        assert calls[0]["url"] == "https://slack.com/api/oauth.access"
        assert calls[1]["url"] == "https://slack.com/api/auth.test"
示例#4
0
def test_no_RTM_with_workspace_tokens():
    def token_update_callback(update_data):
        return update_data

    with pytest.raises(TokenRefreshError):
        sc = SlackClient(
            client_id="12345",
            client_secret="12345",
            refresh_token="refresh_token",
            token_update_callback=token_update_callback,
        )

        sc.rtm_connect()
示例#5
0
def post_slack():
    payload = parse_request(request)
    print(payload)
    slack_client = get_slackclient()
    channel = payload['channel']['id']
    if payload['actions'][0]['name'] == 'yes':
        info = payload['actions'][0]['value']
        info = info.split(';')
        command = info[0]
        state = int(info[1])
        action = ActionBuilder.build(command)
        response = action.execute(state)
        print(
            slack_client.api_call("chat.postMessage",
                                  channel=channel,
                                  text=response,
                                  as_user=True))
        return "Done!"
    else:
        print((SlackClient(get_env("SLACK_TOKEN")).api_call(
            "chat.delete",
            channel=channel,
            ts=payload['actions'][0]['value'],
        )))
        return "No problem, let me know if you need anything else."
示例#6
0
def test_noncallable_refresh_callback():
    with pytest.raises(TokenRefreshError):
        SlackClient(
            client_id="12345",
            client_secret="12345",
            refresh_token="refresh_token",
            token_update_callback="THIS IS A STRING, NOT A CALLABLE METHOD",
        )
示例#7
0
def __main__():
    speak_response("The cooker bot is starting now.")
    token = 'xxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    sc = SlackClient(token)
    if sc.rtm_connect():
        print("success.")

        order = re.compile('.*set_temperature:(\d+).*')
        order_report = re.compile('.*report_temperature.*')

        try:
            while True:
                messages = sc.rtm_read()
                for m in messages:
                    if 'attachments' in m and 'pretext' in m['attachments'][0]:
                        match = order.match(m['attachments'][0]['pretext'])
                        match_report = order_report.match(
                            m['attachments'][0]['pretext'])
                        if match:
                            print(match.group(1))
                            value = float(match.group(1))
                            print("ok, let's set %s" % {value})
                            current = set_temp(value)
                            speak_response(
                                "The target temperature has been updated to %s degrees"
                                % {current})
                        elif match_report:
                            current = get_current_temp()
                            print("current " + current)
                            speak_response(
                                "The cooker's current temperature is %s degrees"
                                % {current})
                        else:
                            print(m['content'])
                    else:
                        print(messages)
        except KeyboardInterrupt:
            print("done")
            return 0

        time.sleep(1)

    else:
        print("failed")
示例#8
0
def test_api_not_ok(slackclient):
    # Testing for rate limit retry headers
    client = SlackClient("xoxp-1234123412341234-12341234-1234")

    with responses.RequestsMock() as rsps:
        rsps.add(
            responses.POST,
            "https://slack.com/api/im.open",
            status=200,
            json={
                "ok": False,
                "error": "invalid_auth"
            },
            headers={},
        )

        client.api_call("im.open", user="******")

        for call in rsps.calls:
            assert call.response.status_code == 200
            assert call.request.url in ["https://slack.com/api/im.open"]
def test_proxy():
    proxies = {'http': 'some-bad-proxy', 'https': 'some-bad-proxy'}
    client = SlackClient('xoxp-1234123412341234-12341234-1234',
                         proxies=proxies)
    server = client.server

    assert server.proxies == proxies

    with pytest.raises(ProxyError):
        server.rtm_connect()

    with pytest.raises(SlackConnectionError):
        server.connect_slack_websocket(
            'wss://mpmulti-xw58.slack-msgs.com/websocket/bad-token')

    api_requester = server.api_requester
    assert api_requester.proxies == proxies
    with pytest.raises(ProxyError):
        api_requester.do('xoxp-1234123412341234-12341234-1234',
                         request='channels.list')
示例#10
0
def test_proxy():
    proxies = {"http": "some-bad-proxy", "https": "some-bad-proxy"}
    client = SlackClient("xoxp-1234123412341234-12341234-1234",
                         proxies=proxies)
    server = client.server

    assert server.proxies == proxies

    with pytest.raises(ProxyError):
        server.rtm_connect()

    with pytest.raises(SlackConnectionError):
        server.connect_slack_websocket(
            "wss://mpmulti-xw58.slack-msgs.com/websocket/bad-token")

    api_requester = server.api_requester
    assert api_requester.proxies == proxies
    with pytest.raises(ProxyError):
        api_requester.do("xoxp-1234123412341234-12341234-1234",
                         request="channels.list")
示例#11
0
def slackclient():
    my_slackclient = SlackClient('xoxp-1234123412341234-12341234-1234')
    return my_slackclient