|
| 1 | +import dotenv from 'dotenv'; |
| 2 | +import path from 'path'; |
| 3 | + |
| 4 | +// Load environment variables from the parent folder |
| 5 | +const __dirname = path.dirname(new URL(import.meta.url).pathname); |
| 6 | +dotenv.config({ path: path.resolve(__dirname, '../.env') }); |
| 7 | + |
| 8 | +import express from 'express'; |
| 9 | +import { |
| 10 | + InteractionResponseFlags, |
| 11 | + InteractionResponseType, |
| 12 | + InteractionType, |
| 13 | + verifyKeyMiddleware, |
| 14 | +} from 'discord-interactions'; |
| 15 | +import { getRandomEmoji } from './utils.js'; |
| 16 | + |
| 17 | +// Create an express app |
| 18 | +const app = express(); |
| 19 | +// Get port, or default to 3000 |
| 20 | +const PORT = process.env.PORT || 3000; |
| 21 | + |
| 22 | +// Add health check endpoint |
| 23 | +app.get('/', (req, res) => { |
| 24 | + res.status(200).send('OK'); |
| 25 | +}); |
| 26 | + |
| 27 | +// Helper functions below |
| 28 | +async function sendPlaceholderResponse(res, placeholderResponse) { |
| 29 | + await res.send({ |
| 30 | + type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE, |
| 31 | + data: { |
| 32 | + content: placeholderResponse, |
| 33 | + flags: InteractionResponseFlags.EPHEMERAL, |
| 34 | + components: [], |
| 35 | + }, |
| 36 | + }); |
| 37 | +} |
| 38 | + |
| 39 | +async function fetchAnswer(question) { |
| 40 | + const response = await fetch('https://ask.defang.io/v1/ask', { |
| 41 | + method: 'POST', |
| 42 | + headers: { |
| 43 | + 'Authorization': `Bearer ${process.env.ASK_TOKEN}`, |
| 44 | + 'Content-Type': 'application/json', |
| 45 | + }, |
| 46 | + body: JSON.stringify({ query: question }), |
| 47 | + }); |
| 48 | + |
| 49 | + const rawResponse = await response.text(); |
| 50 | + console.log('Raw API response:', rawResponse); |
| 51 | + |
| 52 | + if (!response.ok) { |
| 53 | + throw new Error(`API error! Status: ${response.status}`); |
| 54 | + } |
| 55 | + |
| 56 | + return rawResponse || 'No answer provided.'; |
| 57 | +} |
| 58 | + |
| 59 | +async function sendFollowUpResponse(endpoint, content) { |
| 60 | + await fetch(`https://discord.com/api/v10/${endpoint}`, { |
| 61 | + method: 'PATCH', |
| 62 | + headers: { |
| 63 | + 'Authorization': `Bot ${process.env.DISCORD_TOKEN}`, |
| 64 | + 'Content-Type': 'application/json', |
| 65 | + }, |
| 66 | + body: JSON.stringify({ |
| 67 | + content, |
| 68 | + flags: InteractionResponseFlags.EPHEMERAL, |
| 69 | + components: [], |
| 70 | + }), |
| 71 | + }); |
| 72 | +} |
| 73 | + |
| 74 | +/** |
| 75 | + * Interactions endpoint URL where Discord will send HTTP requests |
| 76 | + * Parse request body and verifies incoming requests using discord-interactions package |
| 77 | + */ |
| 78 | +app.post('/interactions', verifyKeyMiddleware(process.env.DISCORD_PUBLIC_KEY), async function (req, res) { |
| 79 | + // Interaction id, type and data |
| 80 | + const { id, type, data } = req.body; |
| 81 | + |
| 82 | + /** |
| 83 | + * Handle verification requests |
| 84 | + */ |
| 85 | + if (type === InteractionType.PING) { |
| 86 | + return res.send({ type: InteractionResponseType.PONG }); |
| 87 | + } |
| 88 | + |
| 89 | + /** |
| 90 | + * Handle slash command requests |
| 91 | + * See https://discord.com/developers/docs/interactions/application-commands#slash-commands |
| 92 | + */ |
| 93 | + if (type === InteractionType.APPLICATION_COMMAND) { |
| 94 | + const { name } = data; |
| 95 | + |
| 96 | + // "ask command" |
| 97 | + if (name === 'ask') { |
| 98 | + const context = req.body.context; |
| 99 | + const userId = context === 0 ? req.body.member.user.id : req.body.user.id |
| 100 | + |
| 101 | + const question = data.options[0]?.value || 'No question provided'; |
| 102 | + const endpoint = `webhooks/${process.env.DISCORD_APP_ID}/${req.body.token}/messages/@original`; |
| 103 | + const initialMessage = `\n> ${question}\n\nLet me find the answer for you. This might take a moment` |
| 104 | + |
| 105 | + // Send a placeholder response |
| 106 | + await sendPlaceholderResponse(res, initialMessage); |
| 107 | + |
| 108 | + // Show animated dots in the message while waiting |
| 109 | + let dotCount = 0; |
| 110 | + const maxDots = 4; |
| 111 | + let isFetching = true; |
| 112 | + |
| 113 | + const interval = setInterval(() => { |
| 114 | + if (isFetching) { |
| 115 | + dotCount = (dotCount % maxDots) + 1; |
| 116 | + sendFollowUpResponse(endpoint, `${initialMessage}${'.'.repeat(dotCount)}`); |
| 117 | + } |
| 118 | + }, 500); |
| 119 | + |
| 120 | + // Create the follow-up response |
| 121 | + let followUpMessage; |
| 122 | + try { |
| 123 | + // Call an external API to fetch the answer |
| 124 | + const answer = await fetchAnswer(question); |
| 125 | + followUpMessage = `\n> ${question}\n\nHere's what I found, <@${userId}>:\n\n${answer}`; |
| 126 | + } catch (error) { |
| 127 | + console.error('Error fetching answer:', error); |
| 128 | + followUpMessage = `\n> ${question}\n\nSorry <@${userId}>, I couldn't fetch an answer to your question. Please try again later.`; |
| 129 | + } finally { |
| 130 | + // Ensure cleanup and state updates |
| 131 | + isFetching = false; // Mark fetching as complete |
| 132 | + clearInterval(interval); // Stop the dot interval |
| 133 | + } |
| 134 | + |
| 135 | + return sendFollowUpResponse(endpoint, followUpMessage); |
| 136 | + } |
| 137 | + |
| 138 | + // "test" command |
| 139 | + if (name === 'test') { |
| 140 | + // Send a message into the channel where command was triggered from |
| 141 | + return res.send({ |
| 142 | + type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE, |
| 143 | + data: { |
| 144 | + // Fetches a random emoji to send from a helper function |
| 145 | + content: `Develop Anything, Deploy Anywhere ${getRandomEmoji()}`, |
| 146 | + }, |
| 147 | + }); |
| 148 | + } |
| 149 | + |
| 150 | + console.error(`unknown command: ${name}`); |
| 151 | + return res.status(400).json({ error: 'unknown command' }); |
| 152 | + } |
| 153 | + |
| 154 | + console.error('unknown interaction type', type); |
| 155 | + return res.status(400).json({ error: 'unknown interaction type' }); |
| 156 | +}); |
| 157 | + |
| 158 | +app.listen(PORT, () => { |
| 159 | + console.log('Listening on port', PORT); |
| 160 | +}); |
0 commit comments