diff options
author | 2021-03-16 16:09:47 +0300 | |
---|---|---|
committer | 2021-03-16 16:09:47 +0300 | |
commit | 094d125ec6e9719937f1be5fabe3ebaefbdc0e73 (patch) | |
tree | 5ec67192e191ccc5fb10ad56b182b026320ff4b8 /backend/discord.py | |
parent | Adds Discord Request Helper (diff) |
Moves Webhook & Role Helper To Discord File
Moves the webhook helper and the role assignment helper to the discord
file to gather all discord helpers in one location.
Signed-off-by: Hassan Abouelela <[email protected]>
Diffstat (limited to 'backend/discord.py')
-rw-r--r-- | backend/discord.py | 76 |
1 files changed, 75 insertions, 1 deletions
diff --git a/backend/discord.py b/backend/discord.py index 08b8e07..560ab69 100644 --- a/backend/discord.py +++ b/backend/discord.py @@ -1,6 +1,5 @@ """Various utilities for working with the Discord API.""" import asyncio -import typing from urllib import parse import httpx @@ -72,3 +71,78 @@ async def fetch_user_details(bearer_token: str) -> dict: r = await make_request("GET", "users/@me", headers={"Authorization": f"Bearer {bearer_token}"}) r.raise_for_status() return r.json() + + +async def send_submission_webhook( + form: Form, + response: FormResponse, + request_user: Request.user +) -> None: + """Helper to send a submission message to a discord webhook.""" + # Stop if webhook is not available + if form.webhook is None: + raise ValueError("Got empty webhook.") + + try: + mention = request_user.discord_mention + except AttributeError: + mention = "User" + + user = response.user + + # Build Embed + embed = { + "title": "New Form Response", + "description": f"{mention} submitted a response to `{form.name}`.", + "url": f"{constants.FRONTEND_URL}/path_to_view_form/{response.id}", # noqa: E501 # TODO: Enter Form View URL + "timestamp": response.timestamp, + "color": 7506394, + } + + # Add author to embed + if request_user.is_authenticated: + embed["author"] = {"name": request_user.display_name} + + if user and user.avatar: + url = f"https://cdn.discordapp.com/avatars/{user.id}/{user.avatar}.png" + embed["author"]["icon_url"] = url + + # Build Hook + hook = { + "embeds": [embed], + "allowed_mentions": {"parse": ["users", "roles"]}, + "username": form.name or "Python Discord Forms" + } + + # Set hook message + message = form.webhook.message + if message: + # Available variables, see SCHEMA.md + ctx = { + "user": mention, + "response_id": response.id, + "form": form.name, + "form_id": form.id, + "time": response.timestamp, + } + + for key in ctx: + message = message.replace(f"{{{key}}}", str(ctx[key])) + + hook["content"] = message.replace("_USER_MENTION_", mention) + + # Post hook + await make_request("POST", form.webhook.url, hook) + + +async def assign_role(form: Form, request_user: User) -> None: + """Assigns Discord role to user when user submitted response.""" + if not form.discord_role: + raise ValueError("Got empty Discord role ID.") + + url = ( + f"guilds/{constants.DISCORD_GUILD}" + f"/members/{request_user.payload['id']}/roles/{form.discord_role}" + ) + + await make_request("PUT", url) |