pythonslackslack-api

Slack SocketModeClient - Respond Only to Messages That Mention App in Channels


I am attempting to create Slack bot using SocketModeClient that only responds to messages in channels where it has explicitly been mentioned. My initial thought process was to do something as follows:

    socket_mode_client = SocketModeClient(
        # This app-level token will be used only for establishing a connection
        app_token=os.environ['APP_TOKEN'],  # xapp-A111-222-xyz
        # You will be using this WebClient for performing Web API calls in listeners
        web_client=WebClient(token=os.environ['TOKEN']),  # xoxb-111-222-xyz
    )

    def _process_websocket_message(client: SocketModeClient, request: SocketModeRequest):
        # Acknowledge the request
        response = SocketModeResponse(envelope_id=request.envelope_id)
        client.send_socket_mode_response(response)

        if request.type != 'events_api':
            return

        # ignore duplicated requests
        if request.retry_attempt is not None and request.retry_attempt > 0:
            return

        payload_event = request.payload['event']

        if payload_event['type'] == 'app_mention' and '<app_user_id>' in payload_event['<some-attr>']:
            # respond

The idea here is to check the text of the message for the user ID of the app and only respond if it is in there. However, I am not entirely certain how I can get the user ID of the app. I know that with the users_profile_get() method of the WebClient, I can get the bot ID and the app ID, but these are not IDs present in the text when the app is mentioned.

I am open to trying a different approach as well.


Solution

  • I think the correct way to go about this is to only subscribe to the app_mention event and not message.channels (via the app). I noticed that I had subscribed to both and unsubscribed from the latter. That worked.

    However, if there is some reason for both of the events to be subscribed to, and you only want to respond when the app is mentioned, you can use the auth_test() method offered by WebClient in order to extract the user ID of the bot and then check for it in the text as explained in the question above.