Skip to content

Commit

Permalink
Creating a simple Bot using slack bolt package
Browse files Browse the repository at this point in the history
  • Loading branch information
marcieltorres committed Feb 11, 2024
1 parent 23dc966 commit f4d0853
Show file tree
Hide file tree
Showing 10 changed files with 70 additions and 31 deletions.
3 changes: 2 additions & 1 deletion .dockerignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
.github
.docs
.vscode
.pytest_cache
.ruff_cache
*.md
*.md
Binary file added .docs/print_bot_working.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 3 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ endif
APP_NAME="slack-bot-no-cpf"
IMAGE_NAME="slack-bot-no-cpf"
VERSION="latest"
MAIN_ENTRYPOINT="src/bot.py"

################################
# COMMANDS TO RUN LOCALLY
Expand All @@ -25,7 +26,7 @@ local/lint/fix:
poetry run ruff . --fix --exit-non-zero-on-fix

local/run:
poetry run python src/main.py
poetry run python ${MAIN_ENTRYPOINT}

############################################
# COMMANDS TO RUN USING DOCKER (RECOMMENDED)
Expand All @@ -50,7 +51,7 @@ docker/lint/fix:
docker-compose run ${APP_NAME} poetry run ruff . --fix --exit-non-zero-on-fix

docker/run:
docker-compose run ${APP_NAME} poetry run python src/main.py
docker-compose run ${APP_NAME} poetry run python ${MAIN_ENTRYPOINT}

####################################
# DOCKER IMAGE COMMANDS
Expand Down
25 changes: 23 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,40 @@ A simple slack bot that analyzes messages sent on channels and warns about possi
- [Docker Compose](https://docs.docker.com/compose/) - **pre-requisite**
- [Poetry](https://python-poetry.org/) - **pre-requisite**
- [Ruff](https://github.com/astral-sh/ruff)
- [Slack Bolt](https://pypi.org/project/slack-bolt/)

*Please pay attention on **pre-requisites** resources that you must install/configure.*

## How to create and configure a new Slack Bot

You can find the official docs [here](https://api.slack.com/start/building/bolt-python).

This bot needs to have the following User Token Scopes added:
```
app_mentions:read
channels:history
channels:read
chat:write
im:history
im:read
```

Follow this [guide](https://api.slack.com/tutorials/tracks/getting-a-token) to generate the tokens.

## How bot works on slack workspace

![Bot working](.docs/print_bot_working.png)

## How to install, run and test

### Environment variables

*Use this section to explain each env variable available on your application*

Variable | Description | Available Values | Default Value | Required
--- | --- | --- | --- | ---
ENV | The application enviroment | `dev / test / qa / prod` | `dev` | Yes
PYTHONPATH | Provides guidance to the Python interpreter about where to find libraries and applications | [ref](https://docs.python.org/3/using/cmdline.html#envvar-PYTHONPATH) | `.` | Yes
SLACK_BOT_TOKEN | The slack bot token | `a valid token` | `-` | Yes
SLACK_APP_TOKEN | The slack app token | `a valid token` | `-` | Yes

*Note: When you run the install command (using docker or locally), a .env file will be created automatically based on [env.template](env.template)*

Expand Down
4 changes: 3 additions & 1 deletion env.template
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
ENV=dev
PYTHONPATH=.
PYTHONPATH=.
SLACK_BOT_TOKEN=
SLACK_APP_TOKEN=
4 changes: 3 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ license = "MIT"

[tool.poetry.dependencies]
python = "^3.11"
slack-bolt = "1.18.1"
aiohttp = "3.9.3"

[tool.poetry.dev-dependencies]
pytest = "^8.0.0"
Expand All @@ -19,7 +21,7 @@ pythonpath = ["src",]

[tool.coverage.run]
branch = true
omit = ["*/tests/*"]
omit = ["*/tests/*", "src/bot.py"]

[tool.coverage.report]
show_missing = true
Expand Down
33 changes: 33 additions & 0 deletions src/bot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from asyncio import run as async_run
from logging import getLogger
from logging.config import fileConfig as logConfig
from os import getenv

from slack_bolt.adapter.socket_mode.async_handler import AsyncSocketModeHandler
from slack_bolt.async_app import AsyncApp

from src.messages.constants import DEFAULT_WARNING_MESSAGE
from src.rules.pattern import pattern

logConfig("./logging.conf", disable_existing_loggers=False)
logger = getLogger(__name__)

SLACK_BOT_TOKEN = getenv("SLACK_BOT_TOKEN", "").strip()
SLACK_APP_TOKEN = getenv("SLACK_APP_TOKEN", "").strip()

app = AsyncApp(token=SLACK_BOT_TOKEN)

@app.message(pattern.compiled_pattern)
async def say_hello_regex(say, message, client):
user = message['user']
await say(text=DEFAULT_WARNING_MESSAGE.format(name=f'<@{user}>'), thread_ts=message.get('ts'))

async def main():
try:
handler = AsyncSocketModeHandler(app, SLACK_APP_TOKEN)
await handler.start_async()
except Exception as ex:
logger.error("Error when starting the bot", ex)

if __name__ == "__main__": # pragma: no cover
async_run(main())
16 changes: 0 additions & 16 deletions src/main.py

This file was deleted.

3 changes: 3 additions & 0 deletions src/messages/constants.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# todo: we will use locale (gnu gettext) to improve the messages
# ruff: noqa: E501
DEFAULT_WARNING_MESSAGE='Olá {name}, por favor não envie CPF, email, telefone (ou qualquer outro dado sensível) em canais públicos aqui pelo slack'
8 changes: 0 additions & 8 deletions tests/test_main.py

This file was deleted.

0 comments on commit f4d0853

Please sign in to comment.