Slack webhooks API served by FastAPI

Overview

Slackers

Slack webhooks API served by FastAPI

What is Slackers

Slackers is a FastAPI implementation to handle Slack interactions and events. It serves endpoints to receive slash commands, app actions, interactive components. It also listens for events sent to the Slack Events API Slack Events.

Installation

You can install Slackers with pip $ pip install slackers

Configuration

SLACK_SIGNING_SECRET

You must configure the slack signing secret. This will be used to verify the incoming requests signature.
$ export SLACK_SIGNING_SECRET=your_slack_signing_secret

Example usage

Slackers will listen for activity from the Events API on /events, for interactive components on /actions and for slash commands on /commands. When an interaction is received, it will emit an event. You can listen for these events as shown in the following examples.

On receiving a request, Slackers will emit an event which you can handle yourself. Slackers will also respond to Slack with an (empty) http 200 response telling Slack all is well received.

Starting the server

As said, Slackers uses the excellent FastAPI to serve it's endpoints. Since you're here, I'm assuming you know what FastAPI is, but if you don't, you can learn all about how that works with this tutorial.

Slackers offers you a router which you can include in your own FastAPI.

from fastapi import FastAPI
from slackers.server import router

app = FastAPI()
app.include_router(router)

# Optionally you can use a prefix
app.include_router(router, prefix='/slack')

Events

Once your server is running, the events endpoint is setup at /events, or if you use the prefix as shown above, on /slack/events.

Accepting the challenge

When setting up Slack to send events, it will first send a challenge to verify your endpoint. Slackers detects when a challenge is sent. You can simply start our api and Slackers will meet the challenge automatically.

Responding to events

On receiving an event, Slackers will emit a python event, which you can act upon as shown below.

import logging
from slackers.hooks import events

log = logging.getLogger(__name__)

@events.on("app_mention")
def handle_mention(payload):
    log.info("App was mentioned.")
    log.debug(payload)

Actions

Once your server is running, the actions endpoint is setup at /actions, or if you use the prefix as shown above, on /slack/actions.

Responding to actions

On receiving an action, Slackers will emit a python event, which you can listen for as shown below. You can listen for the action type, or more specifically for the action id or callback id linked to the action.

import logging
from slackers.hooks import actions

log = logging.getLogger(__name__)

# Listening for the action type.
@actions.on("block_actions")
def handle_action(payload):
    log.info("Action started.")
    log.debug(payload)

# Listen for an action by it's action_id
@actions.on("block_actions:your_action_id")
def handle_action_by_id(payload):
    log.info("Action started.")
    log.debug(payload)

# Listen for an action by it's callback_id
@actions.on("block_actions:your_callback_id")
def handle_action_by_callback_id(payload):
    log.info(f"Action started.")
    log.debug(payload)

Interactive messages

Interactive message actions do not have an action_id. They do have a name and a type. To act upon interactive messages, you can listen for the action type, interactive_message as wel as the combination of the interactive_message and name, type or both.

import logging
from slackers.hooks import actions

log = logging.getLogger(__name__)

# Listening for the action type.
@actions.on("interactive_message")
def handle_action(payload):
    log.info("Action started.")
    log.debug(payload)

# Listen for an action by it's name
@actions.on("interactive_message:action_name")
def handle_action_by_id(payload):
    log.info("Action started.")
    log.debug(payload)

# Listen for an action by it's type
@actions.on("interactive_message:action_type")
def handle_action_by_callback_id(payload):
    log.info(f"Action started.")
    log.debug(payload)

# Listen for an action by it's name and type
@actions.on("interactive_message:action_name:action_type")
def handle_action_by_callback_id(payload):
    log.info(f"Action started.")
    log.debug(payload)

Custom responses

Slackers tries to be fast to respond to Slack. The events you are listening for with the likes of @actions.on(...) are scheduled as an async task in a fire and forget fashion. After scheduling these events, Slackers will by default return an empty 200 response which might happen before the events are handled.

In some cases you might want to act on the payload and return a custom response to Slack. For this, you can use the slackers responder decorator to define your custom handler function. This function is then used as a callback instead of returning the default response. You must ensure your custom handler returns a starlette.responses.Response or one of it's subclasses. You must furthermore ensure that there is only one responder responding to your Slack request.

Please note that the events are also emitted, so you could have both @actions.on("block_action:xyz") and @responder("block_action:xyz"). Just keep in mind that the event emissions are async and are not awaited. In other words, Slackers doesn't ensure that the response (whether your custom response or the default) is returned before or after the events are emitted.

from starlette.responses import JSONResponse
from slackers.hooks import responder

@responder("block_actions:your_callback_id")
def custom_handler(payload):
    # handle your payload
    ...
    return JSONResponse(content={"custom": "Custom Response"})

Slash commands

Once your server is running, the commands endpoint is setup at /commands, or if you use the prefix as shown above, on /slack/commands. Slackers will emit an event with the name of the command, so if your command is /engage, you can listen for the event engage (without the slash)

Responding to slash commands

On receiving a command, Slackers will emit a python event, which you can listen for as shown below.

import logging
from slackers.hooks import commands

log = logging.getLogger(__name__)


@commands.on("engage")  # responds to "/engage"  
def handle_command(payload):
    log.info("Command received")
    log.debug(payload)

Async

Since events are emitted using pyee's Async event emitter, it is possible to define your event handlers as async functions. Just keep in mind that errors are in this case emitted on the 'error' event.

import logging
from slackers.hooks import commands

log = logging.getLogger(__name__)

@commands.on('error')
def log_error(exc):
    log.error(str(exc))


@commands.on("engage")  # responds to "/engage"  
async def handle_command(payload):
    ...
Owner
Niels van Huijstee
Niels van Huijstee
Reusable utilities for FastAPI

Reusable utilities for FastAPI Documentation: https://fastapi-utils.davidmontague.xyz Source Code: https://github.com/dmontagu/fastapi-utils FastAPI i

David Montague 1.3k Jan 04, 2023
Town / City geolocations with FastAPI & Mongo

geolocations-api United Kingdom Town / City geolocations with FastAPI & Mongo Build container To build a custom image or extend the api run the follow

Joe Gasewicz 3 Jan 26, 2022
Hook Slinger acts as a simple service that lets you send, retry, and manage event-triggered POST requests, aka webhooks

Hook Slinger acts as a simple service that lets you send, retry, and manage event-triggered POST requests, aka webhooks. It provides a fully self-contained docker image that is easy to orchestrate, m

Redowan Delowar 96 Jan 02, 2023
Docker image with Uvicorn managed by Gunicorn for high-performance FastAPI web applications in Python 3.6 and above with performance auto-tuning. Optionally with Alpine Linux.

Supported tags and respective Dockerfile links python3.8, latest (Dockerfile) python3.7, (Dockerfile) python3.6 (Dockerfile) python3.8-slim (Dockerfil

Sebastián Ramírez 2.1k Dec 31, 2022
🐞 A debug toolbar for FastAPI based on the original django-debug-toolbar. 🐞

Debug Toolbar 🐞 A debug toolbar for FastAPI based on the original django-debug-toolbar. 🐞 Swagger UI & GraphQL are supported. Documentation: https:/

Dani 74 Dec 30, 2022
SQLAlchemy Admin for Starlette/FastAPI

SQLAlchemy Admin for Starlette/FastAPI SQLAdmin is a flexible Admin interface for SQLAlchemy models. Main features include: SQLAlchemy sync/async engi

Amin Alaee 683 Jan 03, 2023
FastAPI CRUD template using Deta Base

Deta Base FastAPI CRUD FastAPI CRUD template using Deta Base Setup Install the requirements for the CRUD: pip3 install -r requirements.txt Add your D

Sebastian Ponce 2 Dec 15, 2021
Feature rich robust FastAPI template.

Flexible and Lightweight general-purpose template for FastAPI. Usage ⚠️ Git, Python and Poetry must be installed and accessible ⚠️ Poetry version must

Pavel Kirilin 588 Jan 04, 2023
Simple notes app backend using Python's FastAPI framework.

my-notes-app Simple notes app backend using Python's FastAPI framework. Route "/": User login (GET): return 200, list of all of their notes; User sign

José Gabriel Mourão Bezerra 2 Sep 17, 2022
A request rate limiter for fastapi

fastapi-limiter Introduction FastAPI-Limiter is a rate limiting tool for fastapi routes. Requirements redis Install Just install from pypi pip insta

long2ice 200 Jan 08, 2023
Fastapi-ml-template - Fastapi ml template with python

FastAPI ML Template Run Web API Local $ sh run.sh # poetry run uvicorn app.mai

Yuki Okuda 29 Nov 20, 2022
FastAPI-PostgreSQL-Celery-RabbitMQ-Redis bakcend with Docker containerization

FastAPI - PostgreSQL - Celery - Rabbitmq backend This source code implements the following architecture: All the required database endpoints are imple

Juan Esteban Aristizabal 54 Nov 26, 2022
Instrument your FastAPI app

Prometheus FastAPI Instrumentator A configurable and modular Prometheus Instrumentator for your FastAPI. Install prometheus-fastapi-instrumentator fro

Tim Schwenke 441 Jan 05, 2023
API written using Fast API to manage events and implement a leaderboard / badge system.

Open Food Facts Events API written using Fast API to manage events and implement a leaderboard / badge system. Installation To run the API locally, ru

Open Food Facts 5 Jan 07, 2023
fastapi-cache is a tool to cache fastapi response and function result, with backends support redis and memcached.

fastapi-cache Introduction fastapi-cache is a tool to cache fastapi response and function result, with backends support redis, memcache, and dynamodb.

long2ice 551 Jan 08, 2023
This is an API developed in python with the FastApi framework and putting into practice the recommendations of the book Clean Architecture in Python by Leonardo Giordani,

This is an API developed in python with the FastApi framework and putting into practice the recommendations of the book Clean Architecture in Python by Leonardo Giordani,

0 Sep 24, 2022
✨️🐍 SPARQL endpoint built with RDFLib to serve machine learning models, or any other logic implemented in Python

✨ SPARQL endpoint for RDFLib rdflib-endpoint is a SPARQL endpoint based on a RDFLib Graph to easily serve machine learning models, or any other logic

Vincent Emonet 27 Dec 19, 2022
A FastAPI WebSocket application that makes use of ncellapp package by @hemantapkh

ncellFastAPI author: @awebisam Used FastAPI to create WS application. Ncellapp module by @hemantapkh NOTE: Not following best practices and, needs ref

Aashish Bhandari 7 Oct 01, 2021
Hyperlinks for pydantic models

Hyperlinks for pydantic models In a typical web application relationships between resources are modeled by primary and foreign keys in a database (int

Jaakko Moisio 10 Apr 18, 2022
🔀⏳ Easy throttling with asyncio support

Throttler Zero-dependency Python package for easy throttling with asyncio support. 📝 Table of Contents 🎒 Install 🛠 Usage Examples Throttler and Thr

Ramzan Bekbulatov 80 Dec 07, 2022