slackapi / python-slack-events-api

Slack Events API adapter for Python (Flask required)
https://api.slack.com/events
MIT License
343 stars 116 forks source link

WIP: Send Slack request with event data (if handler asks for it) #39

Closed datashaman closed 3 years ago

datashaman commented 6 years ago

Inspects arity of handler function to ascertain whether it should pass request with _eventdata. Does not break current implementations.

Uses inspect module to check arity of the first listener for a specific event type.

If you want an event handler to get the Slack request, define it like this:

@adapter.on('reaction_added')
def reaction_added(event_data, request):
    event = event_data['event']
    if request.headers.get('X-Slack-Retry-Num'):
        print('Event was retried')

NB: A side-effect of this is that all event handlers of the same type must have the same number of arguments!

Resolves https://github.com/slackapi/python-slack-events-api/issues/32 Requires (and is based on) https://github.com/slackapi/python-slack-events-api/pull/37

datashaman commented 6 years ago

This could be changed to send just the headers, but I thought that the whole request might make it more useful.

datashaman commented 6 years ago

Please notify me if/when the base PR is merged, and I'll rebase this on new master.

loot-king commented 4 years ago

😘

seratch commented 4 years ago

I'm sorry the team took a very long time to respond to this. I'm still not sure if this approach is the best for addressing #32 yet. Allow me to hold off making any decisions about this for now.

Lobosque commented 4 years ago

@seratch while you decide on what the best approach is, is there any way at all to access the request header while handling an event?

seratch commented 4 years ago

@Lobosque

@seratch while you decide on what the best approach is, is there any way at all to access the request header while handling an event?

As request in Flask is a thread-local value, you can access it just by importing it.

import os
from flask import request
from slackeventsapi import SlackEventAdapter

slack_signing_secret = os.environ["SLACK_SIGNING_SECRET"]
slack_events_adapter = SlackEventAdapter(slack_signing_secret, "/slack/events")

# Example reaction emoji echo
@slack_events_adapter.on("reaction_added")
def reaction_added(event_data):
    print(request.headers)
    event = event_data["event"]

After leaving the above comment, I came to think that directly accessing request is totally fine because this project doesn't have plans to support any other frameworks apart from Flask.

NB: A side-effect of this is that all event handlers of the same type must have the same number of arguments!

Considering this disadvantage, I think we don't have a strong reason to merge this PR's changes.

seratch commented 3 years ago

As I mentioned in the last comment, you can access Flask's thread-local request object. Let me close this pull request. Thanks for taking the time to send it.