How to receive messages from an HTML form directly on your Discord using Cloudflare Pages and Cloudflare Functions.
We will divide the process into four main parts: creating the HTML form, configuring the webhook on Discord, configuring the Worker on Cloudflare and Deploying the project.
First, you need an HTML form to collect user data. The basic form might look like this:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Formulário de Contato</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <form method="POST" action="/api/submit"> <label for="name">Nome:</label> <input id="name" name="name" type="text" required> <label for="email">Email:</label> <input id="email" name="email" type="email" required> <label for="subject">Assunto:</label> <input id="subject" name="subject" type="text" required> <label for="message">Mensagem:</label> <textarea id="message" name="message" required></textarea> <button type="submit">Enviar</button> </form> </body> </html>
This form sends a POST request to the /api/submit endpoint when the user clicks "Submit".
To receive messages on Discord, you need to set up a webhook. Follow the steps below:
Now that you have the form and webhook configured, it's time to configure Cloudflare Worker to process requests and send messages to Discord.
Create a repository on GitHub for your project. In your terminal, clone the repository and configure the project structure:
mkdir meu-projeto cd meu-projeto git init git remote add origin git@github.com:<seu-usuario>/<seu-repositorio>.git
Organize your project as follows:
meu-projeto ├── functions │ └── api │ └── submit.js └── public └── index.html
In the functions/api/submit.js file, add the following code to process the form and send the message to Discord:
export async function onRequestPost(ctx) { try { return await handleRequest(ctx); } catch(e) { return new Response(`${e.message}\n${e.stack}`, { status: 500 }); } } async function handleRequest({ request, env }) { const data = await request.formData(); const name = data.get('name'); const email = data.get('email'); const subject = data.get('subject'); const message = data.get('message'); const captcha = data.get('h-captcha-response'); if (!name || !email || !subject || !message || !captcha) { return new Response('Verifique se os campos estão preenchidos!', { status: 400 }); } const captchaVerified = await verifyHcaptcha( captcha, request.headers.get('cf-connecting-ip'), env.HCAPTCHA_SECRET, env.HCAPTCHA_SITE_KEY ); if (!captchaVerified) { return new Response('Captcha inválido!', { status: 400 }); } await sendDiscordMessage(name, email, subject, message, env.DISCORD_WEBHOOK_URL); return new Response('OK'); } async function verifyHcaptcha(response, ip, secret, siteKey) { const res = await fetch('https://hcaptcha.com/siteverify', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `response=${response}&remoteip=${ip}&secret=${secret}&sitekey=${siteKey}` }); const json = await res.json(); return json.success; } async function sendDiscordMessage(name, email, subject, message, webhookUrl) { await fetch(webhookUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ username: 'Formulário de Contato', embeds: [{ color: 0x0099ff, title: 'Nova Mensagem', fields: [ { name: 'Nome', value: name, inline: true, }, { name: 'Email', value: email, inline: true, }, { name: 'Assunto', value: subject, }, { name: 'Mensagem', value: "``` " + message + " ```", } ] }] }), }); }
With everything configured, let's deploy the project:
Commit and push the code to GitHub:
git add . git commit -m "Projeto configurado" git push origin main
In Cloudflare Pages, connect the GitHub repository, select the main branch, and set the build output to public.
To avoid exposing your sensitive keys and settings, configure environment variables in Cloudflare Pages. Access your Cloudflare Pages dashboard. Select the project and go to Settings > Environment Variables. Add the following variables:
After setup, your website will be accessible via a *.pages.dev subdomain and ready to use. When a user submits the form, a message will be sent directly to your Discord channel.
Congratulations! You have successfully configured an HTML form that sends messages to Discord using Cloudflare Functions.
The above is the detailed content of How to Receive Messages on Discord with Cloudflare Functions. For more information, please follow other related articles on the PHP Chinese website!