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
Fastapi performans monitoring

Fastapi-performans-monitoring This project is a simple performance monitoring for FastAPI. License This project is licensed under the terms of the MIT

bilal alpaslan 11 Dec 31, 2022
Simple FastAPI Example : Blog API using FastAPI : Beginner Friendly

fastapi_blog FastAPI : Simple Blog API with CRUD operation Steps to run the project: git clone https://github.com/mrAvi07/fastapi_blog.git cd fastapi-

Avinash Alanjkar 1 Oct 08, 2022
Repository for the Demo of using DVC with PyCaret & MLOps (DVC Office Hours - 20th Jan, 2022)

Using DVC with PyCaret & FastAPI (Demo) This repo contains all the resources for my demo explaining how to use DVC along with other interesting tools

Tezan Sahu 6 Jul 22, 2022
FastAPI backend for Repost

Repost FastAPI This is the FastAPI implementation of the Repost API. Installation Python 3 must be installed and accessible through the use of a termi

PC 7 Jun 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
FastAPI-Amis-Admin is a high-performance, efficient and easily extensible FastAPI admin framework. Inspired by django-admin, and has as many powerful functions as django-admin.

简体中文 | English 项目介绍 FastAPI-Amis-Admin fastapi-amis-admin是一个拥有高性能,高效率,易拓展的fastapi管理后台框架. 启发自Django-Admin,并且拥有不逊色于Django-Admin的强大功能. 源码 · 在线演示 · 文档 · 文

AmisAdmin 318 Dec 31, 2022
🍃 A comprehensive monitoring and alerting solution for the status of your Chia farmer and harvesters.

chia-monitor A monitoring tool to collect all important metrics from your Chia farming node and connected harvesters. It can send you push notificatio

Philipp Normann 153 Oct 21, 2022
Ready-to-use and customizable users management for FastAPI

FastAPI Users Ready-to-use and customizable users management for FastAPI Documentation: https://fastapi-users.github.io/fastapi-users/ Source Code: ht

FastAPI Users 2.3k Dec 30, 2022
A RESTful API for creating and monitoring resource components of a hypothetical build system. Built with FastAPI and pydantic. Complete with testing and CI.

diskspace-monitor-CRUD Background The build system is part of a large environment with a multitude of different components. Many of the components hav

Nick Hopewell 67 Dec 14, 2022
Middleware for Starlette that allows you to store and access the context data of a request. Can be used with logging so logs automatically use request headers such as x-request-id or x-correlation-id.

starlette context Middleware for Starlette that allows you to store and access the context data of a request. Can be used with logging so logs automat

Tomasz Wójcik 300 Dec 26, 2022
FastAPI Auth Starter Project

This is a template for FastAPI that comes with authentication preconfigured.

Oluwaseyifunmi Oyefeso 6 Nov 13, 2022
Turns your Python functions into microservices with web API, interactive GUI, and more.

Instantly turn your Python functions into production-ready microservices. Deploy and access your services via HTTP API or interactive UI. Seamlessly export your services into portable, shareable, and

Machine Learning Tooling 2.8k Jan 04, 2023
FastAPI + PeeWee = <3

FastAPIwee FastAPI + PeeWee = 3 Using Python = 3.6 🐍 Installation pip install FastAPIwee 🎉 Documentation Documentation can be found here: https://

16 Aug 30, 2022
MS Graph API authentication example with Fast API

MS Graph API authentication example with Fast API What it is & does This is a simple python service/webapp, using FastAPI with server side rendering,

Andrew Hart 4 Aug 11, 2022
Stac-fastapi built on Tile38 and Redis to support caching

stac-fastapi-caching Stac-fastapi built on Tile38 to support caching. This code is built on top of stac-fastapi-elasticsearch 0.1.0 with pyle38, a Pyt

Jonathan Healy 4 Apr 11, 2022
A Python framework to build Slack apps in a flash with the latest platform features.

Bolt for Python A Python framework to build Slack apps in a flash with the latest platform features. Read the getting started guide and look at our co

SlackAPI 684 Jan 09, 2023
REST API with FastAPI and PostgreSQL

REST API with FastAPI and PostgreSQL To have the same data in db: create table CLIENT_DATA (id SERIAL PRIMARY KEY, fullname VARCHAR(50) NOT NULL,email

Luis Quiñones Requelme 1 Nov 11, 2021
Sample-fastapi - A sample app using Fastapi that you can deploy on App Platform

Getting Started We provide a sample app using Fastapi that you can deploy on App

Erhan BÜTE 2 Jan 17, 2022
Local Telegram Bot With FastAPI & Ngrok

An easy local telegram bot server with python, fastapi and ngrok.

Ömer Faruk Özdemir 7 Dec 25, 2022
Deploy/View images to database sqlite with fastapi

Deploy/View images to database sqlite with fastapi cd realistic Dependencies dat

Fredh Macau 1 Jan 04, 2022