Python slack.WebClient() Examples
The following are 30
code examples of slack.WebClient().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
slack
, or try the search function
.
Example #1
Source File: test_admin_usergroups.py From python-slackclient with MIT License | 6 votes |
def setUp(self): self.logger = logging.getLogger(__name__) self.org_admin_token = os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN] self.sync_client: WebClient = WebClient( token=self.org_admin_token, run_async=False, loop=asyncio.new_event_loop() ) self.async_client: WebClient = WebClient(token=self.org_admin_token, run_async=True) self.team_id = os.environ[SLACK_SDK_TEST_GRID_TEAM_ID] self.idp_usergroup_id = os.environ[SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID] if not hasattr(self, "channel_ids"): team_admin_token = os.environ[SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN] client = WebClient(token=team_admin_token, run_async=False, loop=asyncio.new_event_loop()) convs = client.conversations_list(exclude_archived=True, limit=100) self.channel_ids = [c["id"] for c in convs["channels"] if c["name"] == "general"]
Example #2
Source File: test_web_client.py From python-slackclient with MIT License | 6 votes |
def test_response_can_be_paginated_multiple_times_use_sync_aiohttp(self): self.client = WebClient( token="xoxp-1234", base_url="http://localhost:8888", run_async=False, use_sync_aiohttp=True, ) self.client.token = "xoxb-channels_list_pagination" # This test suite verifies the changes in #521 work as expected response = self.client.channels_list(limit=1) ids = [] for page in response: ids.append(page["channels"][0]["id"]) self.assertEqual(ids, ["C1", "C2", "C3"]) # The second iteration starting with page 2 # (page1 is already cached in `response`) self.client.token = "xoxb-channels_list_pagination2" ids = [] for page in response: ids.append(page["channels"][0]["id"]) self.assertEqual(ids, ["C1", "C2", "C3"])
Example #3
Source File: Slack_test.py From content with MIT License | 6 votes |
def test_get_user_by_id_async_user_exists(mocker): from Slack import get_user_by_id_async # Set async def api_call(method: str, http_verb: str = 'POST', file: str = None, params=None, json=None, data=None): if method == 'users.info': return {'user': js.loads(USERS)[0]} mocker.patch.object(demisto, 'getIntegrationContext', side_effect=get_integration_context) mocker.patch.object(demisto, 'setIntegrationContext', side_effect=set_integration_context) mocker.patch.object(slack.WebClient, 'api_call', side_effect=api_call) user_id = 'U012A3CDE' # Arrange user = await get_user_by_id_async(slack.WebClient, user_id) # Assert assert slack.WebClient.api_call.call_count == 0 assert demisto.setIntegrationContext.call_count == 0 assert user['name'] == 'spengler'
Example #4
Source File: test_rtm_client_functional.py From python-slackclient with MIT License | 6 votes |
def setUp(self): setup_mock_web_api_server(self) self.loop = asyncio.new_event_loop() asyncio.set_event_loop(self.loop) task = asyncio.ensure_future(self.mock_server(), loop=self.loop) self.loop.run_until_complete(asyncio.wait_for(task, 0.1)) self.client = slack.RTMClient( token="xoxb-valid", base_url="http://localhost:8765", auto_reconnect=False, run_async=False, ) self.client._web_client = slack.WebClient( token="xoxb-valid", base_url="http://localhost:8888", run_async=False, )
Example #5
Source File: test_rtm_client_functional.py From python-slackclient with MIT License | 6 votes |
def test_run_async_valid(self): client = slack.RTMClient( token="xoxb-valid", base_url="http://localhost:8765", run_async=True, ) client._web_client = slack.WebClient( token="xoxb-valid", base_url="http://localhost:8888", run_async=True, ) self.called = False @slack.RTMClient.run_on(event="open") async def handle_open_event(**payload): self.called = True client.start() # intentionally no await here await asyncio.sleep(3) self.assertTrue(self.called)
Example #6
Source File: test_slack_response.py From python-slackclient with MIT License | 6 votes |
def test_issue_559(self): response = SlackResponse( client=WebClient(token="xoxb-dummy"), http_verb="POST", api_url="http://localhost:3000/api.test", req_args={}, data={ "ok": True, "args": { "hello": "world" } }, headers={}, status_code=200, ) self.assertTrue("ok" in response.data) self.assertTrue("args" in response.data) self.assertFalse("error" in response.data)
Example #7
Source File: async_app.py From python-slackclient with MIT License | 6 votes |
def onboarding_message(**payload): """Create and send an onboarding welcome message to new users. Save the time stamp of this message so we can update this message in the future. """ # Get WebClient so you can communicate back to Slack. web_client = payload["web_client"] # Get the id of the Slack user associated with the incoming event user_id = payload["data"]["user"]["id"] # Open a DM with the new user. response = web_client.im_open(user_id) channel = response["channel"]["id"] # Post the onboarding message. await start_onboarding(web_client, user_id, channel) # ============= Reaction Added Events ============= # # When a users adds an emoji reaction to the onboarding message, # the type of the event will be 'reaction_added'. # Here we'll link the update_emoji callback to the 'reaction_added' event.
Example #8
Source File: test_rtm_client_functional.py From python-slackclient with MIT License | 6 votes |
def test_run_async_invalid(self): client = slack.RTMClient( token="xoxb-valid", base_url="http://localhost:8765", run_async=True, ) client._web_client = slack.WebClient( token="xoxb-valid", base_url="http://localhost:8888", run_async=True, ) self.called = False @slack.RTMClient.run_on(event="open") def handle_open_event(**payload): self.called = True client.start() # intentionally no await here await asyncio.sleep(3) self.assertFalse(self.called)
Example #9
Source File: Slack_test.py From content with MIT License | 6 votes |
def test_get_conversation_by_name_not_exists(self, mocker): """ Given: - Conversation to find When: - Conversation do not exists. Then: - Check no conversation was returned. - Check that a API command was called. """ from Slack import get_conversation_by_name self.set_conversation_mock(mocker) conversation_name = 'no exists' conversation = get_conversation_by_name(conversation_name) assert not conversation assert slack.WebClient.api_call.call_count == 1
Example #10
Source File: Slack_test.py From content with MIT License | 6 votes |
def test_get_conversation_by_name_exists_in_context(self, mocker): """ Given: - Conversation to find When: - Conversation exists in context Then: - Check if the right conversation returned - Check that no API command was called. """ from Slack import get_conversation_by_name self.set_conversation_mock(mocker) conversation_name = 'general' conversation = get_conversation_by_name(conversation_name) # Assertions assert conversation_name == conversation['name'] assert slack.WebClient.api_call.call_count == 0
Example #11
Source File: test_web_client.py From python-slackclient with MIT License | 6 votes |
def test_uploading_file_with_token_param(self): client = WebClient() current_dir = os.path.dirname(__file__) file = f"{current_dir}/../../tests/data/slack_logo.png" upload = client.files_upload( token=self.bot_token, channels=self.channel_id, title="Good Old Slack Logo", filename="slack_logo.png", file=file, ) self.assertIsNotNone(upload) deletion = client.files_delete( token=self.bot_token, file=upload["file"]["id"], ) self.assertIsNotNone(deletion)
Example #12
Source File: test_web_client.py From python-slackclient with MIT License | 6 votes |
def test_uploading_file_with_token_param_async(self): client = WebClient(run_async=True) current_dir = os.path.dirname(__file__) file = f"{current_dir}/../../tests/data/slack_logo.png" upload = await client.files_upload( token=self.bot_token, channels=self.channel_id, title="Good Old Slack Logo", filename="slack_logo.png", file=file, ) self.assertIsNotNone(upload) deletion = client.files_delete( token=self.bot_token, file=upload["file"]["id"], ) self.assertIsNotNone(deletion) # ------------------------- # pagination
Example #13
Source File: slack_noti.py From Osmedeus with MIT License | 6 votes |
def slack_file(options, filename, token=None): try: if not token: token = options.get('SLACK_BOT_TOKEN') client = slack.WebClient(token=token) channel = options.get('REPORT_CHANNEL') if channel is None: return client.files_upload( channels=channel, file=filename, title=filename, filetype='text' ) except: pass
Example #14
Source File: slack_noti.py From Osmedeus with MIT License | 6 votes |
def slack_status(options): channel = options.get('STATUS_CHANNEL', None) if channel is None: return module = options.get('CURRENT_MODULE') target = options.get('TARGET') message = f':ghost: Start *{module}* on *{target}*' client = slack.WebClient(token=options.get('SLACK_BOT_TOKEN')) client.chat_postMessage( channel=channel, blocks=[ { "type": "section", "text": { "type": "mrkdwn", "text": message, }, }, { "type": "divider" } ] )
Example #15
Source File: test_rtm_client.py From python-slackclient with MIT License | 6 votes |
def test_basic_operations_async(self): self.sent_text: str = None self.rtm_client = RTMClient(token=self.bot_token, run_async=True) self.async_web_client = WebClient(token=self.bot_token, run_async=True) @RTMClient.run_on(event="message") async def send_reply(**payload): self.logger.debug(payload) self.sent_text = payload['data']['text'] # intentionally not waiting here self.rtm_client.start() self.assertIsNone(self.sent_text) await asyncio.sleep(5) text = "This message was sent by <https://slack.dev/python-slackclient/|python-slackclient>! (test_basic_operations_async)" new_message = await self.async_web_client.chat_postMessage(channel=self.channel_id, text=text) self.assertFalse("error" in new_message) await asyncio.sleep(5) self.assertEqual(self.sent_text, text)
Example #16
Source File: SlackCommunicator.py From ngraph-onnx with Apache License 2.0 | 6 votes |
def send_message(self, message, quiet=False): """ Send queued messages as single communication. :param message: Final message's content :param quiet: Flag for disabling sending report through Slack :type message: String :type quiet: Boolean """ if self._slack_client is None: try: self._slack_client = slack.WebClient(self._slack_token, proxy=self._proxy, ssl=False) except Exception: print('!!CRITICAL!! SlackCommunicator::CRITICAL: Could not create client') raise for channel, message_queue in self._queued_messages.items(): final_message = message + '\n\n' + '\n'.join(message_queue) print(final_message) if not quiet and message_queue: self._send_to_channel(final_message, channel)
Example #17
Source File: issue_497.py From python-slackclient with MIT License | 6 votes |
def per_request_async(): try: # This is not optimal and the host should have a large number of FD (File Descriptor) loop_for_this_request = asyncio.new_event_loop() async_client = WebClient( token=os.environ["SLACK_BOT_TOKEN"], run_async=True, loop=loop_for_this_request ) future = async_client.chat_postMessage( channel="#random", text="You used the singleton WebClient for posting this message!" ) response = loop_for_this_request.run_until_complete(future) return str(response) except SlackApiError as e: return make_response(str(e), 400)
Example #18
Source File: async_app.py From python-slackclient with MIT License | 6 votes |
def start_onboarding(web_client: slack.WebClient, user_id: str, channel: str): # Create a new onboarding tutorial. onboarding_tutorial = OnboardingTutorial(channel) # Get the onboarding message payload message = onboarding_tutorial.get_message_payload() # Post the onboarding message in Slack response = await web_client.chat_postMessage(**message) # Capture the timestamp of the message we've just posted so # we can use it to update the message after a user # has completed an onboarding task. onboarding_tutorial.timestamp = response["ts"] # Store the message sent in onboarding_tutorials_sent if channel not in onboarding_tutorials_sent: onboarding_tutorials_sent[channel] = {} onboarding_tutorials_sent[channel][user_id] = onboarding_tutorial # ================ Team Join Event =============== # # When the user first joins a team, the type of the event will be 'team_join'. # Here we'll link the onboarding_message callback to the 'team_join' event.
Example #19
Source File: Slack_test.py From content with MIT License | 5 votes |
def test_get_user_by_name_paging(mocker): from Slack import get_user_by_name # Set def api_call(method: str, http_verb: str = 'POST', file: str = None, params=None, json=None, data=None): if len(params) == 1: return {'members': js.loads(USERS), 'response_metadata': { 'next_cursor': 'dGVhbTpDQ0M3UENUTks=' }} else: return {'members': [{ 'id': 'U248918AB', 'name': 'alexios' }], 'response_metadata': { 'next_cursor': '' }} mocker.patch.object(demisto, 'getIntegrationContext', side_effect=get_integration_context) mocker.patch.object(demisto, 'setIntegrationContext', side_effect=set_integration_context) mocker.patch.object(slack.WebClient, 'api_call', side_effect=api_call) # Arrange user = get_user_by_name('alexios') args = slack.WebClient.api_call.call_args_list first_args = args[0][1] second_args = args[1][1] # Assert assert len(first_args['params']) == 1 assert first_args['params']['limit'] == 200 assert len(second_args['params']) == 2 assert second_args['params']['cursor'] == 'dGVhbTpDQ0M3UENUTks=' assert user['id'] == 'U248918AB' assert slack.WebClient.api_call.call_count == 2
Example #20
Source File: Slack_test.py From content with MIT License | 5 votes |
def test_handle_dm_non_create_nonexisting_user(mocker): from Slack import handle_dm # Set async def api_call(method: str, http_verb: str = 'POST', file: str = None, params=None, json=None, data=None): if method == 'conversations.open': return { 'channel': { 'id': 'ey' }} else: return 'sup' mocker.patch.object(demisto, 'getIntegrationContext', side_effect=get_integration_context) mocker.patch.object(demisto, 'findUser', return_value=None) mocker.patch.object(demisto, 'directMessage', return_value=None) mocker.patch.object(slack.WebClient, 'api_call', side_effect=api_call) user = js.loads(USERS)[0] # Arrange await handle_dm(user, 'wazup', slack.WebClient) message = demisto.directMessage.call_args[0][0] username = demisto.directMessage.call_args[0][1] email = demisto.directMessage.call_args[0][2] allow = demisto.directMessage.call_args[0][3] # Assert assert message == 'wazup' assert username == 'spengler' assert email == 'spengler@ghostbusters.example.com' assert allow is False
Example #21
Source File: Slack_test.py From content with MIT License | 5 votes |
def test_handle_dm_nondemisto_user_should_create(mocker): import Slack mocker.patch.object(demisto, 'params', return_value={'allow_incidents': 'true'}) Slack.init_globals() # Set async def fake_translate(message: str, user_name: str, user_email: str, demisto_user: dict): return "sup" async def api_call(method: str, http_verb: str = 'POST', file: str = None, params=None, json=None, data=None): if method == 'conversations.open': return { 'channel': { 'id': 'ey' }} else: return 'sup' mocker.patch.object(demisto, 'getIntegrationContext', side_effect=get_integration_context) mocker.patch.object(demisto, 'findUser', return_value=None) mocker.patch.object(Slack, 'translate_create', side_effect=fake_translate) mocker.patch.object(slack.WebClient, 'api_call', side_effect=api_call) user = js.loads(USERS)[0] # Arrange await Slack.handle_dm(user, 'create incident abc', slack.WebClient) # Assert assert Slack.translate_create.call_count == 1 demisto_user = Slack.translate_create.call_args[0][3] assert demisto_user is None
Example #22
Source File: slack_noti.py From Osmedeus with MIT License | 5 votes |
def slack_done(options): utils.print_info(f"Sending {noti_type} notification to slack") channel = options.get('STATUS_CHANNEL') module = options.get('CURRENT_MODULE') target = options.get('TARGET') emoji = get_emoji() message = f'{emoji} Done *{module}* on *{target}*' client = slack.WebClient(token=options.get('SLACK_BOT_TOKEN')) client.chat_postMessage( channel=channel, blocks=[ { "type": "section", "text": { "type": "mrkdwn", "text": message, }, # "accessory": { # "type": "image", # "image_url": get_emoji(), # "alt_text": 'status', # } }, { "type": "divider" } ] )
Example #23
Source File: Slack_test.py From content with MIT License | 5 votes |
def test_handle_text(mocker): import Slack # Set async def fake_clean(text, client): return 'מה הולך' mocker.patch.object(demisto, 'getIntegrationContext', side_effect=get_integration_context) mocker.patch.object(demisto, 'setIntegrationContext', side_effect=set_integration_context) mocker.patch.object(demisto, 'addEntry') mocker.patch.object(Slack, 'clean_message', side_effect=fake_clean) user = js.loads(USERS)[0] investigation_id = '999' text = 'מה הולך' # Arrange await Slack.handle_text(slack.WebClient, investigation_id, text, user) entry_args = demisto.addEntry.call_args[1] # Assert assert demisto.addEntry.call_count == 1 assert entry_args['id'] == '999' assert entry_args['entry'] == 'מה הולך' assert entry_args['username'] == 'spengler' assert entry_args['email'] == 'spengler@ghostbusters.example.com' assert entry_args['footer'] == '\n**From Slack**'
Example #24
Source File: slack_noti.py From Osmedeus with MIT License | 5 votes |
def slack_monitor(options, filename, monitor_type='new'): try: if options.get('SLACK_MONITOR_TOKEN') and options.get('SLACK_MONITOR_TOKEN') != 'None': token = options.get('SLACK_MONITOR_TOKEN') else: token = options.get('SLACK_BOT_TOKEN') client = slack.WebClient(token=token) if monitor_type == 'new': channel = options.get('NEW_CHANNEL', None) if channel is None: return elif monitor_type == 'missing': channel = options.get('MISSING_CHANNEL', None) if channel is None: return client.files_upload( channels=channel, file=filename, title=filename, filetype='text' ) except: pass # shortcut for sending noti to slack
Example #25
Source File: Slack_test.py From content with MIT License | 5 votes |
def test_send_request_no_user(mocker, capfd): import Slack # Set def api_call(method: str, http_verb: str = 'POST', file: str = None, params=None, json=None, data=None): if method == 'users.list': return {'members': js.loads(USERS)} elif method == 'conversations.list': return {'channels': js.loads(CONVERSATIONS)} elif method == 'conversations.open': return {'channel': {'id': 'im_channel'}} return {} mocker.patch.object(demisto, 'getIntegrationContext', side_effect=get_integration_context) mocker.patch.object(demisto, 'setIntegrationContext', side_effect=set_integration_context) return_error_mock = mocker.patch(RETURN_ERROR_TARGET, side_effect=InterruptedError()) mocker.patch.object(slack.WebClient, 'api_call', side_effect=api_call) mocker.patch.object(Slack, 'send_file', return_value='neat') mocker.patch.object(Slack, 'send_message', return_value='cool') # Arrange with capfd.disabled(): with pytest.raises(InterruptedError): Slack.slack_send_request('alexios', None, None, message='Hi') err_msg = return_error_mock.call_args[0][0] calls = slack.WebClient.api_call.call_args_list users_call = [c for c in calls if c[0][0] == 'users.list'] # Assert assert return_error_mock.call_count == 1 assert err_msg == 'Could not find any destination to send to.' assert len(users_call) == 1 assert Slack.send_message.call_count == 0 assert Slack.send_file.call_count == 0
Example #26
Source File: oauth_v2.py From python-slackclient with MIT License | 5 votes |
def oauth_callback(): # Retrieve the auth code and state from the request params if "code" in request.args: state = request.args["state"] if state_service.consume(state): code = request.args["code"] client = WebClient() # no prepared token needed for this app response = client.oauth_v2_access( client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, code=code ) logger.info(f"oauth.v2.access response: {response}") database.save(response) return "Thanks for installing this app!" else: return make_response(f"Try the installation again (the state value is already expired)", 400) error = request.args["error"] if "error" in request.args else "" return make_response(f"Something is wrong with the installation (error: {error})", 400) # --------------------- # Flask App for Slack events # ---------------------
Example #27
Source File: issue_714.py From python-slackclient with MIT License | 5 votes |
def async_call(): client = WebClient( token=os.environ["SLACK_API_TOKEN"], proxy="http://localhost:9000", run_async=True ) response = await client.auth_test() logger.info(f"async response: {response}")
Example #28
Source File: issue_497.py From python-slackclient with MIT License | 5 votes |
def singleton_async(): try: future = singleton_async_client.chat_postMessage( channel="#random", text="You used the singleton WebClient for posting this message!" ) # blocking here!!! # as described at https://github.com/slackapi/python-slackclient/issues/497 # until this completion, other simultaneous requests get "RuntimeError: This event loop is already running" response = singleton_loop.run_until_complete(future) return str(response) except SlackApiError as e: return make_response(str(e), 400)
Example #29
Source File: issue_497.py From python-slackclient with MIT License | 5 votes |
def singleton(): try: # blocking here!!! # as described at https://github.com/slackapi/python-slackclient/issues/497 # until this completion, other simultaneous requests get "RuntimeError: This event loop is already running" response = singleton_client.chat_postMessage( channel="#random", text="You used the singleton WebClient for posting this message!" ) return str(response) except SlackApiError as e: return make_response(str(e), 400)
Example #30
Source File: Connectors.py From Scrummage with GNU General Public License v3.0 | 5 votes |
def Slack_Main(Description): Slack_Details = Load_Slack_Configuration() if Slack_Details: try: client = slack.WebClient(token=Slack_Details[0]) client.chat_postMessage(channel=Slack_Details[1], text=Description) logging.info(f"{Date()} Connectors Library - New Slack Notification created.") except Exception as e: logging.warning(f"{Date()} Connectors Library - {str(e)}.")