pythonslack-bolt

How to read headers that are sent in the webhook URL request


I'm trying to read the additional custom headers that were sent when I made the curl request using the webhook URL of a Slack channel but I cannot find a way to read the custom header or query parameters. May I know if there is any way to determine them?

from typing import Optional
import slack_sdk
import os
import logging
from pathlib import Path
from dotenv import load_dotenv
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler

logging.basicConfig(level=logging.DEBUG)
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)

SLACK_VERIFICATION_TOKEN = os.environ['SLACK_VERIFICATION_TOKEN']
SLACK_SIGNING_SECRET = os.environ['SLACK_SIGNING_SECRET']
SLACK_BOT_TOKEN = os.environ['SLACK_BOT_TOKEN']
SLACK_APP_TOKEN = os.environ['SLACK_APP_TOKEN']

# Install the Slack app and get xoxb- token in advance
app = App(token=SLACK_BOT_TOKEN, signing_secret=SLACK_SIGNING_SECRET)
    
@app.event("message")
def handle_message(event, say, context):
    text = event["text"]
    channel = event["channel"]
    target_channel='#slave2_public'

    # Access query parameters
    # query_params = context.request.query
    # print("Query Parameters:", query_params)

    # Access headers from the event
    headers = event.get("headers")
    print("Headers:", headers)

    # Access headers
    # headers = context.request.headers
    # print("Headers:", headers)
        

if __name__ == "__main__":
    # export SLACK_APP_TOKEN=xapp-***
    # export SLACK_BOT_TOKEN=xoxb-***
    handler = SocketModeHandler(app, SLACK_APP_TOKEN)
    handler.start()

My curl request to webhook URL:-

curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' -H "Channel_Name:slave1_private" <webhook URL>

Solution

  • Webhook will just trigger the bot_message event, You can handle the bot_message event in slack app and there you can read event payload of the webhook's message, you can send some metadata from the webhook's message, and you can get that information on event handling time.