How to use slackeventsapi - 10 common examples

To help you get started, we’ve selected a few slackeventsapi examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github slackapi / python-slack-events-api / tests / test_server.py View on Github external
def test_existing_flask():
    valid_flask = Flask(__name__)
    valid_adapter = SlackEventAdapter("vFO9LARnLI7GflLR8tGqHgdy", "/slack/events", valid_flask)
    assert isinstance(valid_adapter, SlackEventAdapter)
github slackapi / python-slack-events-api / tests / test_events.py View on Github external
import pytest
from slackeventsapi import SlackEventAdapter

ADAPTER = SlackEventAdapter('vFO9LARnLI7GflLR8tGqHgdy')


def test_event_emission(client):
    # Events should trigger an event
    data = pytest.reaction_event_fixture

    @ADAPTER.on('reaction_added')
    def event_handler(event):
        assert event["reaction"] == 'grinning'

    res = client.post(
        '/slack/events',
        data=data,
        content_type='application/json'
    )
github slackapi / python-slack-events-api / tests / test_server.py View on Github external
def test_server_not_flask():
    with pytest.raises(TypeError) as e:
        invalid_flask = "I am not a Flask"
        SlackEventAdapter("vFO9LARnLI7GflLR8tGqHgdy", "/slack/events", invalid_flask)
    assert e.value.args[0] == 'Server must be an instance of Flask'
github slackapi / python-slack-events-api / tests / test_server.py View on Github external
def test_version_header(client):
    # Verify [package metadata header is set
    package_info = SlackEventAdapter("token").server.package_info

    data = pytest.reaction_event_fixture
    res = client.post(
        '/slack/events',
        data=data,
        content_type='application/json')

    assert res.status_code == 200
    assert res.headers["X-Slack-Powered-By"] == package_info
github slackapi / python-slack-events-api / tests / test_server.py View on Github external
def test_existing_flask():
    valid_flask = Flask(__name__)
    valid_adapter = SlackEventAdapter("vFO9LARnLI7GflLR8tGqHgdy", "/slack/events", valid_flask)
    assert isinstance(valid_adapter, SlackEventAdapter)
github seratch / slack-app-examples / reacjilator-python3 / app.py View on Github external
# Slack
import slack
from slackeventsapi import SlackEventAdapter

# --------------------
# Slack API
# Slack Web API Client with sufficient permissions
slack_web_api_client = slack.WebClient(token=os.environ['SLACK_API_TOKEN'])

# In order for our application to verify the authenticity
# of requests from Slack, we'll compare the request signature
slack_signing_secret = os.environ["SLACK_SIGNING_SECRET"]

# Create an instance of SlackEventAdapter, passing in our Flask server so it can bind the
# Slack specific routes. The `endpoint` param specifies where to listen for Slack event traffic.
slack_events_adapter = SlackEventAdapter(
    slack_signing_secret,
    endpoint="/slack/events"
)

# --------------------
# Google Translate API

# https://console.cloud.google.com/apis/credentials?project={project id}
# export GOOGLE_APPLICATION_CREDENTIALS=/path/to/{service-account-key}.json
translate_client = translate.Client()

# --------------------
# Load language mapping data
langcode: dict = {}
with open('./langcode.json') as langcode_file:
    langcode = json.load(langcode_file)
github slackapi / python-slack-events-api / slackeventsapi / server.py View on Github external
if request.method == 'GET':
                return make_response("These are not the slackbots you're looking for.", 404)

            # Each request comes with request timestamp and request signature
            # emit an error if the timestamp is out of range
            req_timestamp = request.headers.get('X-Slack-Request-Timestamp')
            if abs(time() - int(req_timestamp)) > 60 * 5:
                slack_exception = SlackEventAdapterException('Invalid request timestamp')
                self.emitter.emit('error', slack_exception)
                return make_response("", 403)

            # Verify the request signature using the app's signing secret
            # emit an error if the signature can't be verified
            req_signature = request.headers.get('X-Slack-Signature')
            if not self.verify_signature(req_timestamp, req_signature):
                slack_exception = SlackEventAdapterException('Invalid request signature')
                self.emitter.emit('error', slack_exception)
                return make_response("", 403)

            # Parse the request payload into JSON
            event_data = json.loads(request.data.decode('utf-8'))

            # Echo the URL verification challenge code back to Slack
            if "challenge" in event_data:
                return make_response(
                    event_data.get("challenge"), 200, {"content_type": "application/json"}
                )

            # Parse the Event payload and emit the event to the event listener
            if "event" in event_data:
                event_type = event_data["event"]["type"]
                self.emitter.emit(event_type, event_data)
github slackapi / python-slack-events-api / slackeventsapi / server.py View on Github external
def event():
            # If a GET request is made, return 404.
            if request.method == 'GET':
                return make_response("These are not the slackbots you're looking for.", 404)

            # Each request comes with request timestamp and request signature
            # emit an error if the timestamp is out of range
            req_timestamp = request.headers.get('X-Slack-Request-Timestamp')
            if abs(time() - int(req_timestamp)) > 60 * 5:
                slack_exception = SlackEventAdapterException('Invalid request timestamp')
                self.emitter.emit('error', slack_exception)
                return make_response("", 403)

            # Verify the request signature using the app's signing secret
            # emit an error if the signature can't be verified
            req_signature = request.headers.get('X-Slack-Signature')
            if not self.verify_signature(req_timestamp, req_signature):
                slack_exception = SlackEventAdapterException('Invalid request signature')
                self.emitter.emit('error', slack_exception)
                return make_response("", 403)

            # Parse the request payload into JSON
            event_data = json.loads(request.data.decode('utf-8'))

            # Echo the URL verification challenge code back to Slack
            if "challenge" in event_data:
github slackapi / python-slack-events-api / slackeventsapi / server.py View on Github external
def get_package_info(self):
        client_name = __name__.split('.')[0]
        client_version = __version__  # Version is returned from version.py

        # Collect the package info, Python version and OS version.
        package_info = {
            "client": "{0}/{1}".format(client_name, client_version),
            "python": "Python/{v.major}.{v.minor}.{v.micro}".format(v=sys.version_info),
            "system": "{0}/{1}".format(platform.system(), platform.release())
        }

        # Concatenate and format the user-agent string to be passed into request headers
        ua_string = []
        for key, val in package_info.items():
            ua_string.append(val)

        return " ".join(ua_string)
github apache / infrastructure-puppet / modules / gnomebot / files / gnomebot.py View on Github external
print(f"Response from {hook_name} was not serializable JSON!")
                except Exception as e:
                    print(f"Action parsing function {hook_name} errored out: {e}")
                    backtrace()
                break

    resp = flask.Response('{}', mimetype='application/json')
    return resp


if __name__ == "__main__":
    config = yaml.safe_load(open('gnomebot.yaml').read())

    # Initialize a Flask app to host the events adapter
    app = flask.Flask(__name__)
    event_adapter = slackeventsapi.SlackEventAdapter(config['server']['slack_secret'], "/slack/events", app)

    # Message events (slack module knows what to do)
    @event_adapter.on("message")  # HOST:PORT/slack/events
    def deliver(payload):
        return handle_message(payload)

    # Interactive events (slack module does not know how to handle this, so native flask..)
    @app.route("/slack/interactive", methods=["POST"])  # HOST:PORT/slack/interactive
    def deliver():
        return handle_event()


    # Initialize a Web API client
    slack_web_client = slack.WebClient(token=config['server']['slack_token'])
    config['whoami'] = slack_web_client.api_call("auth.test")["user_id"]

slackeventsapi

Python Slack Events API adapter for Flask

MIT
Latest version published 12 months ago

Package Health Score

71 / 100
Full package analysis

Similar packages