Skip to content

Commit

Permalink
Merge pull request #42 from appwrite/feat-port-discord-command-bot
Browse files Browse the repository at this point in the history
Discord Command Bot Ports
  • Loading branch information
loks0n authored Aug 22, 2023
2 parents 0c5eb43 + f120c8c commit bea4796
Show file tree
Hide file tree
Showing 7 changed files with 333 additions and 8 deletions.
17 changes: 9 additions & 8 deletions node/discord-command-bot/src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,18 @@ export default async ({ req, res, error, log }) => {
) {
log('Matched hello command - returning message');

const interactionResponse = {
type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
content: 'Hello, World!',
return res.json(
{
type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
content: 'Hello, World!',
},
},
};

return res.json(interactionResponse);
200
);
}

log("Didn't match command - returning PONG");

return res.json({ type: InteractionResponseType.PONG });
return res.json({ type: InteractionResponseType.PONG }, 200);
};
160 changes: 160 additions & 0 deletions python/discord-command-bot/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
62 changes: 62 additions & 0 deletions python/discord-command-bot/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# 🤖 Python Discord Command Bot Function

Simple command using Discord Interactions.

## 🧰 Usage

### `POST`

Webhook to receive Discord command events. To receive events, you must register your application as a [Discord bot](https://discord.com/developers/applications).

**Parameters**

| Name | Description | Location | Type | Sample Value |
| --------------------- | -------------------------------- | -------- | ------ | --------------------------------------------------------------------------------------------- |
| x-signature-ed25519 | Signature of the request payload | Header | string | `d1efb...aec35` |
| x-signature-timestamp | Timestamp of the request payload | Header | string | `1629837700` |
| JSON Body | GitHub webhook payload | Body | Object | See [Discord docs](https://discord.com/developers/docs/interactions/receiving-and-responding) |

**Response**

Sample `200` Response:

Returns a Discord message object.

```json
{
"type": 4,
"data": {
"content": "Hello from Appwrite 👋"
}
}
```

Sample `401` Response:

```json
{
"error": "Invalid request signature"
}
```

## ⚙️ Configuration

| Setting | Value |
| ----------------- | -------------------------------------------------------- |
| Runtime | Python (3.9) |
| Entrypoint | `src/main.py` |
| Build Commands | `pip install -r requirements.txt && python src/setup.py` |
| Permissions | `any` |
| Timeout (Seconds) | 15 |

## 🔒 Environment Variables

### DISCORD_PUBLIC_KEY

Discord Public Key to verify request signature.

| Question | Answer |
| ------------- | ---------------------------------------------------------------------------------------------------------------------- |
| Required | Yes |
| Sample Value | `d1efb...aec35` |
| Documentation | [Discord Docs](https://discord.com/developers/docs/tutorials/hosting-on-cloudflare-workers#creating-an-app-on-discord) |
2 changes: 2 additions & 0 deletions python/discord-command-bot/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
requests
discord-interactions
51 changes: 51 additions & 0 deletions python/discord-command-bot/src/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import os
from utils import throw_if_missing
from discord_interactions import verify_key, InteractionResponseType, InteractionType


def main(context):
throw_if_missing(
os.environ,
[
"DISCORD_PUBLIC_KEY",
"DISCORD_APPLICATION_ID",
"DISCORD_TOKEN",
],
)

if not verify_key(
context.req.bodyRaw,
context.req.headers["x-signature-ed25519"],
context.req.headers["x-signature-timestamp"],
os.environ["DISCORD_PUBLIC_KEY"],
):
context.error("Invalid request")
return context.res.json({"error": "Invalid request signature"}, 401)

context.log("Valid request")

interaction = context.req.body

if (interaction.type == InteractionType.APPLICATION_COMMAND) and (
interaction.data.name == "hello"
):
context.log("Matched hello command - returning message")

return context.res.json(
{
"type": InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
"data": {
"content": "Hello World!",
},
},
200,
)

context.log("Didn't match command - returning PONG")

return context.res.json(
{
"type": InteractionResponseType.PONG,
},
200,
)
35 changes: 35 additions & 0 deletions python/discord-command-bot/src/setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import requests, os
from utils import throw_if_missing


def setup():
throw_if_missing(
os.environ,
[
"DISCORD_PUBLIC_KEY",
"DISCORD_APPLICATION_ID",
"DISCORD_TOKEN",
],
)

REGISTER_API = f'https://discord.com/api/v9/applications/{os.environ["DISCORD_APPLICATION_ID"]}/commands'

response = requests.post(
REGISTER_API,
data={
"name": "hello",
"description": "Hello World Command",
},
headers={
"Authorization": f'Bot {os.environ["DISCORD_TOKEN"]}',
"Content-Type": "application/json",
},
)

if not response.ok:
raise Exception(f"Failed to register command")

print("Successfully registered command")


setup()
14 changes: 14 additions & 0 deletions python/discord-command-bot/src/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
def throw_if_missing(obj: object, keys: list[str]) -> None:
"""
Throws an error if any of the keys are missing from the object
Parameters:
obj (object): Object to check
keys (list[str]): List of keys to check
Raises:
ValueError: If any keys are missing
"""
missing = [key for key in keys if key not in obj or not obj[key]]
if missing:
raise ValueError(f"Missing required fields: {', '.join(missing)}")

0 comments on commit bea4796

Please sign in to comment.