Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

chore: simplify discord example.

thorwebdev8d3d87027aee
diff --git a/examples/edge-functions/supabase/functions/discord-bot/README.md b/examples/edge-functions/supabase/functions/discord-bot/README.md
index daa4d4bdd3d..5e9ad79f29b 100644
--- a/examples/edge-functions/supabase/functions/discord-bot/README.md
+++ b/examples/edge-functions/supabase/functions/discord-bot/README.md
@@ -1,8 +1,9 @@
-# Discord Bot for Hackathon submissions
+# Discord Slash Command Bot
-## Helpful tutorials
+## Helpful docs
- https://deno.com/deploy/docs/tutorial-discord-slash
+- https://discord.com/developers/docs/interactions/application-commands#slash-commands
## Create an application on Discord Developer Portal
@@ -18,80 +19,19 @@ Before we can write some code, we need to curl a discord endpoint to register a
Fill `DISCORD_BOT_TOKEN` with the token available in the **Bot** section and `CLIENT_ID` with the ID available on the **General Information** section of the page and run the command on your terminal.
```bash
-DISCORD_BOT_TOKEN='replace_me_with_discord_bot_token'
+BOT_TOKEN='replace_me_with_bot_token'
CLIENT_ID='replace_me_with_client_id'
-
curl -X POST \
-H 'Content-Type: application/json' \
--H "Authorization: Bot $DISCORD_BOT_TOKEN" \
--d '{"name":"promise","description":"Command to manage a coding challenge.","options":[{"name":"new","description":"Set a new challenge for yourself.","type":1,"options":[{"name":"promise","description":"What would you like to achieve?","type":3,"required":true}]},{"name":"resolve","description":"Mark your challenge as completed.","type":1,"options":[{"name":"submission","description":"Provide a link to your project (Website, GitHub, etc.).","type":3,"required":true}]}]}' \
+-H "Authorization: Bot $BOT_TOKEN" \
+-d '{"name":"hello","description":"Greet a person","options":[{"name":"name","description":"The name of the person","type":3,"required":true}]}' \
"https://discord.com/api/v8/applications/$CLIENT_ID/commands"
```
-Here a more readable representation of the body payload for the Slash Command creation request:
-
-```json
-{
- "name": "promise",
- "description": "Command to manage a coding challenge.",
- "options": [
- {
- "name": "new",
- "description": "Set a new challenge for yourself.",
- "type": 1,
- "options": [
- {
- "name": "promise",
- "description": "What would you like to achieve?",
- "type": 3,
- "required": true
- }
- ]
- },
- {
- "name": "resolve",
- "description": "Mark your challenge as completed.",
- "type": 1,
- "options": [
- {
- "name": "submission",
- "description": "Provide a link to your project (Website, GitHub, etc.).",
- "type": 3,
- "required": true
- }
- ]
- }
- ]
-}
-```
-
This will register a Slash Command named `hello` that accepts a parameter named `name` of type string.
## Deploy the Slash Command Handler
-### Create a Database Table to store information
-
-1. Navigate to the [SQL Editor in your Supabase Dashboard](https://app.supabase.com/project/_/sql).
-2. Click "New Query".
-3. Paste and run the SQL below:
-
-```sql
-create table discord_promise_challenge (
- id bigint generated by default as identity primary key,
- inserted_at timestamp with time zone default timezone('utc'::text, now()) not null,
- updated_at timestamp with time zone default timezone('utc'::text, now()) not null,
- user_id text not null,
- username text not null,
- promise text not null,
- email text,
- submission text,
- resolved boolean default false
-);
-alter table discord_promise_challenge enable row level security;
-```
-
-### Deploy the Functions
-
```bash
supabase functions deploy discord-bot --no-verify-jwt
supabase secrets set DISCORD_PUBLIC_KEY=your_public_key
@@ -120,4 +60,5 @@ Open Discord, type `/Promise` and press **Enter**.
```bash
supabase functions serve discord-bot --no-verify-jwt --env-file ./supabase/functions/discord-bot/.env
+ngrok http 54321
```
diff --git a/examples/edge-functions/supabase/functions/discord-bot/discord_api.ts b/examples/edge-functions/supabase/functions/discord-bot/discord_api.ts
deleted file mode 100644
index 1b1148f6416..00000000000
--- a/examples/edge-functions/supabase/functions/discord-bot/discord_api.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-const DISCORD_API_URL = 'https://discord.com/api/v9'
-
-const headers = {
- Authorization: `Bot ${Deno.env.get('DISCORD_BOT_TOKEN')!}`,
- 'Content-Type': 'application/json',
-}
-
-export const sendDiscordDM = async ({
- user,
- message,
-}: {
- user: string
- message: string
-}): Promise<void> => {
- // Open DM channel
- const createDMChannel = await fetch(`${DISCORD_API_URL}/users/@me/channels`, {
- method: 'POST',
- headers,
- body: JSON.stringify({ recipient_id: user }),
- }).then((res) => res.json())
- console.log(createDMChannel)
- // Send DM
- const createDM = await fetch(`${DISCORD_API_URL}/channels/${createDMChannel.id}/messages`, {
- method: 'POST',
- headers,
- body: JSON.stringify({ content: message }),
- }).then((res) => res.json())
- console.log(createDM)
-}
-
-export const createPrivateThread = async ({
- channel,
- user,
- username,
- message,
-}: {
- channel: string
- user: string
- username: string
- message: string
-}): Promise<void> => {
- // Create private thread
- const createDMChannel = await fetch(`${DISCORD_API_URL}/channels/${channel}/threads`, {
- method: 'POST',
- headers,
- body: JSON.stringify({
- name: `${username}'s challenge. Complete your submission`,
- type: 12,
- invitable: false,
- }),
- }).then((res) => res.json())
- console.log(createDMChannel)
- // Add user to thread
- const addUser = await fetch(
- `${DISCORD_API_URL}/channels/${createDMChannel.id}/thread-members/${user}`,
- {
- method: 'PUT',
- headers,
- }
- )
- console.log(addUser)
- // Send message to thread
- const createDM = await fetch(`${DISCORD_API_URL}/channels/${createDMChannel.id}/messages`, {
- method: 'POST',
- headers,
- body: JSON.stringify({ content: message }),
- }).then((res) => res.json())
- console.log(createDM)
- // Add webhook
- const createWebhook = await fetch(`${DISCORD_API_URL}/channels/${createDMChannel.id}/webhooks`, {
- method: 'POST',
- headers,
- body: JSON.stringify({ name: `${username}_webhook` }),
- }).then((res) => res.json())
- console.log(createWebhook)
-}
diff --git a/examples/edge-functions/supabase/functions/discord-bot/index.ts b/examples/edge-functions/supabase/functions/discord-bot/index.ts
index 6e76bd0e76d..140bb30b767 100644
--- a/examples/edge-functions/supabase/functions/discord-bot/index.ts
+++ b/examples/edge-functions/supabase/functions/discord-bot/index.ts
@@ -1,3 +1,7 @@
+// Follow this setup guide to integrate the Deno language server with your editor:
+// https://deno.land/manual/getting_started/setup_your_environment
+// This enables autocomplete, go to definition, etc.
+
// Sift is a small routing library that abstracts away details like starting a
// listener on a port, and provides a simple function (serve) that has an API
// to invoke a function for a specific path.
@@ -6,25 +10,18 @@ import { json, serve, validateRequest } from 'https://deno.land/x/[email protected]/mod
// from Discord.
import nacl from 'https://cdn.skypack.dev/[email protected]?dts'
-import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'
-
-import { Database } from './types/database.types.ts'
-import { DiscordWebhookEvent } from './types/discord.ts'
-
-const supabaseAdminClient = createClient<Database>(
- // Supabase API URL - env var exported by default when deployed.
- Deno.env.get('SUPABASE_URL') ?? '',
- // Supabase API SERVICE ROLE KEY - env var exported by default when deployed.
- Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
-)
+enum DiscordCommandType {
+ Ping = 1,
+ ApplicationCommand = 2,
+}
-// For all requests to "/" endpoint, we want to invoke bot() handler.
+// For all requests to "/" endpoint, we want to invoke home() handler.
serve({
- '/discord-bot': bot,
+ '/discord-bot': home,
})
// The main logic of the Discord Slash Command is defined in this function.
-async function bot(request: Request) {
+async function home(request: Request) {
// validateRequest() ensures that a request is of POST method and
// has the following headers.
const { error } = await validateRequest(request, {
@@ -48,16 +45,11 @@ async function bot(request: Request) {
}
)
}
- console.log(body)
- const {
- channel_id = '',
- type = 0,
- data = { options: [] },
- member: { user } = {},
- } = JSON.parse(body) as DiscordWebhookEvent
+
+ const { type = 0, data = { options: [] } } = JSON.parse(body)
// Discord performs Ping interactions to test our application.
// Type 1 in a request implies a Ping interaction.
- if (type === 1) {
+ if (type === DiscordCommandType.Ping) {
return json({
type: 1, // Type 1 in a response is a Pong interaction response type.
})
@@ -65,60 +57,16 @@ async function bot(request: Request) {
// Type 2 in a request is an ApplicationCommand interaction.
// It implies that a user has issued a command.
- if (type === 2) {
- const { options: newOptions } = data.options.find((option) => option.name === 'new') ?? {
- value: null,
- }
- const { options: resolveOptions } = data.options.find(
- (option) => option.name === 'resolve'
- ) ?? {
- value: null,
- }
-
- let resMsg = 'An error occured.'
-
- // Handle new challenge creation.
- if (user && newOptions) {
- const { value: promise } = newOptions.find((option) => option.name === 'promise')!
-
- const { data: existingChallenge } = await supabaseAdminClient
- .from('discord_promise_challenge')
- .select('*')
- .match({ user_id: user.id, resolved: false })
- .maybeSingle()
- if (existingChallenge) {
- resMsg = `You must complete your open challenge first before creating a new one! Your ongoing challenge: "${existingChallenge.promise}".`
- } else {
- const { error: insertError } = await supabaseAdminClient
- .from('discord_promise_challenge')
- .insert({ promise, user_id: user.id, username: user.username })
- if (insertError) resMsg = insertError.message
- else
- resMsg = `New challenge "${promise}" created. Once completed come back here and submit via "/promise resolve"!`
- }
- }
-
- // Handle submission for existing challenge.
- if (user && resolveOptions) {
- const { value: submission } = resolveOptions.find((option) => option.name === 'submission')!
-
- const { data: updatedChallenge, error: updateError } = await supabaseAdminClient
- .from('discord_promise_challenge')
- .update({ submission, resolved: true, updated_at: new Date().toISOString() })
- .match({ user_id: user.id, resolved: false })
- .select('promise')
- .single()
- if (updateError) resMsg = updateError.message
- else
- resMsg = `Thanks! Your submission for challenge "${updatedChallenge.promise}" has been recorded \\o/`
- }
-
+ if (type === DiscordCommandType.ApplicationCommand) {
+ const { value } = data.options.find(
+ (option: { name: string; value: string }) => option.name === 'name'
+ )
return json({
// Type 4 responds with the below message retaining the user's
// input at the top.
type: 4,
data: {
- content: resMsg,
+ content: `Hello, ${value}!`,
},
})
}
diff --git a/examples/edge-functions/supabase/functions/discord-bot/types/database.types.ts b/examples/edge-functions/supabase/functions/discord-bot/types/database.types.ts
deleted file mode 100644
index ca1f37b13c3..00000000000
--- a/examples/edge-functions/supabase/functions/discord-bot/types/database.types.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-export type Json =
- | string
- | number
- | boolean
- | null
- | { [key: string]: Json }
- | Json[]
-
-export interface Database {
- public: {
- Tables: {
- discord_promise_challenge: {
- Row: {
- id: number
- user_id: string
- username: string
- promise: string
- email: string | null
- submission: string | null
- inserted_at: string
- updated_at: string
- resolved: boolean | null
- }
- Insert: {
- id?: number
- user_id: string
- username: string
- promise: string
- email?: string | null
- submission?: string | null
- inserted_at?: string
- updated_at?: string
- resolved?: boolean | null
- }
- Update: {
- id?: number
- user_id?: string
- username?: string
- promise?: string
- email?: string | null
- submission?: string | null
- inserted_at?: string
- updated_at?: string
- resolved?: boolean | null
- }
- }
- users: {
- Row: {
- id: string
- full_name: string | null
- avatar_url: string | null
- }
- Insert: {
- id: string
- full_name?: string | null
- avatar_url?: string | null
- }
- Update: {
- id?: string
- full_name?: string | null
- avatar_url?: string | null
- }
- }
- }
- Views: {
- [_ in never]: never
- }
- Functions: {
- [_ in never]: never
- }
- Enums: {
- [_ in never]: never
- }
- }
-}
-
diff --git a/examples/edge-functions/supabase/functions/discord-bot/types/discord.ts b/examples/edge-functions/supabase/functions/discord-bot/types/discord.ts
deleted file mode 100644
index 0fd70aa998e..00000000000
--- a/examples/edge-functions/supabase/functions/discord-bot/types/discord.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-export interface DiscordWebhookEvent {
- app_permissions: string
- application_id: string
- channel_id: string
- data: {
- id: string
- name: string
- options: Array<{
- name: string
- type: number
- options: Array<{
- name: string
- type: number
- value: string
- }>
- }>
- type: number
- }
- entitlement_sku_ids: string[]
- guild_id: string
- guild_locale: string
- id: string
- locale: string
- member: {
- avatar: string | null
- communication_disabled_until: string
- deaf: boolean
- flags: number
- is_pending: boolean
- joined_at: string
- mute: boolean
- nick: string | null
- pending: boolean
- permissions: string
- premium_since: string | null
- roles: string[]
- user: {
- avatar: string
- avatar_decoration: string | null
- discriminator: string
- id: string
- public_flags: number
- username: string
- }
- }
- token: string
- type: number
- version: number
-}