Skip to content

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

feat: add discord bot example.

thorwebdev26c6e28c787d
diff --git a/examples/edge-functions/supabase/functions/discord-bot/README.md b/examples/edge-functions/supabase/functions/discord-bot/README.md
new file mode 100644
index 00000000000..daa4d4bdd3d
--- /dev/null
+++ b/examples/edge-functions/supabase/functions/discord-bot/README.md
@@ -0,0 +1,123 @@
+# Discord Bot for Hackathon submissions
+
+## Helpful tutorials
+
+- https://deno.com/deploy/docs/tutorial-discord-slash
+
+## Create an application on Discord Developer Portal
+
+1. Go to [https://discord.com/developers/applications](https://discord.com/developers/applications) (login using your discord account if required).
+2. Click on **New Application** button available at left side of your profile picture.
+3. Name your application and click on **Create**.
+4. Go to **Bot** section, click on **Add Bot**, and finally on **Yes, do it!** to confirm.
+
+That's it. A new application is created which will hold our Slash Command. Don't close the tab as we need information from this application page throughout our development.
+
+Before we can write some code, we need to curl a discord endpoint to register a Slash Command in our app.
+
+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'
+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}]}]}' \
+"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
+```
+
+Navigate to your Function details in the Supabase Dashboard to get your Endpoint URL.
+
+### Configure Discord application to use our URL as interactions endpoint URL
+
+1. Go back to your application (Greeter) page on Discord Developer Portal
+2. Fill **INTERACTIONS ENDPOINT URL** field with the URL and click on **Save Changes**.
+
+The application is now ready. Let's proceed to the next section to install it.
+
+## Install the Slash Command on your Discord server
+
+So to use the `hello` Slash Command, we need to install our Greeter application on our Discord server. Here are the steps:
+
+1. Go to **OAuth2** section of the Discord application page on Discord Developer Portal
+2. Select `applications.commands` scope and click on the **Copy** button below.
+3. Now paste and visit the URL on your browser. Select your server and click on **Authorize**.
+
+Open Discord, type `/Promise` and press **Enter**.
+
+## Run locally
+
+```bash
+supabase functions serve discord-bot --no-verify-jwt --env-file ./supabase/functions/discord-bot/.env
+```
diff --git a/examples/edge-functions/supabase/functions/discord-bot/index.ts b/examples/edge-functions/supabase/functions/discord-bot/index.ts
new file mode 100644
index 00000000000..f5bb2391d70
--- /dev/null
+++ b/examples/edge-functions/supabase/functions/discord-bot/index.ts
@@ -0,0 +1,150 @@
+// 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.
+import { json, serve, validateRequest } from 'https://deno.land/x/[email protected]/mod.ts'
+// TweetNaCl is a cryptography library that we use to verify requests
+// 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') ?? ''
+)
+
+// For all requests to "/" endpoint, we want to invoke bot() handler.
+serve({
+ '/discord-bot': bot,
+})
+
+// The main logic of the Discord Slash Command is defined in this function.
+async function bot(request: Request) {
+ // validateRequest() ensures that a request is of POST method and
+ // has the following headers.
+ const { error } = await validateRequest(request, {
+ POST: {
+ headers: ['X-Signature-Ed25519', 'X-Signature-Timestamp'],
+ },
+ })
+ if (error) {
+ return json({ error: error.message }, { status: error.status })
+ }
+
+ // verifySignature() verifies if the request is coming from Discord.
+ // When the request's signature is not valid, we return a 401 and this is
+ // important as Discord sends invalid requests to test our verification.
+ const { valid, body } = await verifySignature(request)
+ if (!valid) {
+ return json(
+ { error: 'Invalid request' },
+ {
+ status: 401,
+ }
+ )
+ }
+ console.log(body)
+ const {
+ channel_id = '',
+ type = 0,
+ data = { options: [] },
+ member: { user } = {},
+ } = JSON.parse(body) as DiscordWebhookEvent
+ // Discord performs Ping interactions to test our application.
+ // Type 1 in a request implies a Ping interaction.
+ if (type === 1) {
+ return json({
+ type: 1, // Type 1 in a response is a Pong interaction response type.
+ })
+ }
+
+ // 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 })
+ .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/`
+ }
+
+ return json({
+ // Type 4 responds with the below message retaining the user's
+ // input at the top.
+ type: 4,
+ data: {
+ content: resMsg,
+ },
+ })
+ }
+
+ // We will return a bad request error as a valid Discord request
+ // shouldn't reach here.
+ return json({ error: 'bad request' }, { status: 400 })
+}
+
+/** Verify whether the request is coming from Discord. */
+async function verifySignature(request: Request): Promise<{ valid: boolean; body: string }> {
+ const PUBLIC_KEY = Deno.env.get('DISCORD_PUBLIC_KEY')!
+ // Discord sends these headers with every request.
+ const signature = request.headers.get('X-Signature-Ed25519')!
+ const timestamp = request.headers.get('X-Signature-Timestamp')!
+ const body = await request.text()
+ const valid = nacl.sign.detached.verify(
+ new TextEncoder().encode(timestamp + body),
+ hexToUint8Array(signature),
+ hexToUint8Array(PUBLIC_KEY)
+ )
+
+ return { valid, body }
+}
+
+/** Converts a hexadecimal string to Uint8Array. */
+function hexToUint8Array(hex: string) {
+ return new Uint8Array(hex.match(/.{1,2}/g)!.map((val) => parseInt(val, 16)))
+}
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
new file mode 100644
index 00000000000..ca1f37b13c3
--- /dev/null
+++ b/examples/edge-functions/supabase/functions/discord-bot/types/database.types.ts
@@ -0,0 +1,76 @@
+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
new file mode 100644
index 00000000000..0fd70aa998e
--- /dev/null
+++ b/examples/edge-functions/supabase/functions/discord-bot/types/discord.ts
@@ -0,0 +1,49 @@
+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
+}
diff --git a/examples/edge-functions/supabase/migrations/20221208080410_discord-bot.sql b/examples/edge-functions/supabase/migrations/20221208080410_discord-bot.sql
new file mode 100644
index 00000000000..fb842a23883
--- /dev/null
+++ b/examples/edge-functions/supabase/migrations/20221208080410_discord-bot.sql
@@ -0,0 +1,12 @@
+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;
\ No newline at end of file