Home > Web Front-end > JS Tutorial > How to Receive Messages on Discord with Cloudflare Functions

How to Receive Messages on Discord with Cloudflare Functions

WBOY
Release: 2024-07-19 16:26:32
Original
1090 people have browsed it

Como Receber Mensagens no Discord com Cloudflare Functions

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.

Creating an HTML Form

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>
Copy after login

This form sends a POST request to the /api/submit endpoint when the user clicks "Submit".

Configuring Discord Webhook

To receive messages on Discord, you need to set up a webhook. Follow the steps below:

  1. Create a Discord Channel: If you don't already have a dedicated channel, create one on your Discord server.
  2. Configure the Webhook: Go to "Channel Settings" > "Integrations" > "Webhooks" and click "Create Webhook".
  3. Name the Webhook: Give your webhook a name and copy the generated URL.

Configuring Cloudflare Pages and Workers

Now that you have the form and webhook configured, it's time to configure Cloudflare Worker to process requests and send messages to Discord.

1: Create a Project on GitHub

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
Copy after login

2: Project Structure

Organize your project as follows:

meu-projeto
├── functions
│   └── api
│       └── submit.js
└── public
    └── index.html
Copy after login

3: Configure the Worker

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 + "

```",
                    }
                ]
            }]
        }),
    });
}
Copy after login

Deploy

With everything configured, let's deploy the project:

  1. Commit and push the code to GitHub:

    git add .
    git commit -m "Projeto configurado"
    git push origin main
    
    Copy after login
  2. In Cloudflare Pages, connect the GitHub repository, select the main branch, and set the build output to public.

  3. 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:

    • DISCORD_WEBHOOK_URL with the Discord webhook URL.
    • HCAPTCHA_SECRET with the hCaptcha secret.
    • HCAPTCHA_SITE_KEY with the hCaptcha website key.

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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template