📜  php 在用户登录 discord webhook 时发送 - PHP (1)

📅  最后修改于: 2023-12-03 15:03:41.762000             🧑  作者: Mango

PHP 在用户登录 Discord Webhook 时发送

如果你想要在用户登录你的网站或应用程序时自动发送 Discord 通知,你可以使用 Discord Webhooks 和 PHP 来完成。在本文中,我们将介绍如何通过 PHP 在用户登录时发送 Discord 通知。

Discord Webhooks 简介

Discord Webhooks 是一种机制,可以让你向特定的 Discord 群组发送消息。通过向 Webhook URL 发送 POST 请求,你可以发送文本、嵌入式消息、文件甚至是自定义的内容。

代码实现

为了使用 PHP 发送 Discord Webhook 消息,你需要使用 PHP cURL 库。以下是实现的基本代码:

<?php
// Discord Webhook URL
$url = 'https://discordapp.com/api/webhooks/1234567890/ABCDEFGHijklmnopqrstuvwxyz';

// 消息内容
$message = 'User has logged in!';

// cURL 请求设置
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode(['content' => $message]));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_exec($curl);

在上面的代码中,你需要用你自己的 Webhook URL 替换 $url 变量。然后,你可以定义消息内容,并使用 curl_setopt() 函数将其作为 JSON 发送到 Webhook URL。

发送嵌入消息

如果你想发送一个更复杂的消息到 Discord,你可以使用嵌入消息。以下是实现代码:

<?php
// Discord Webhook URL
$url = 'https://discordapp.com/api/webhooks/1234567890/ABCDEFGHijklmnopqrstuvwxyz';

// 嵌入消息内容
$messageArray = [
    'username' => 'Your Bot Name',
    'avatar_url' => 'https://www.example.com/your-bot-avatar.png',
    'embeds' => [
        [
            'title' => 'User Login',
            'color' => 0xFF5733,
            'fields' => [
                [
                    'name' => 'Username',
                    'value' => 'John Doe',
                    'inline' => true
                ],
                [
                    'name' => 'IP Address',
                    'value' => '123.45.67.89',
                    'inline' => true
                ],
                [
                    'name' => 'Browser',
                    'value' => 'Chrome',
                    'inline' => false
                ]
            ]
        ]
    ]
];

// cURL 请求设置
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($messageArray));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_exec($curl);

在上面的代码中,我们使用 usernameavatar_url 声明了一个 bot,并使用嵌入消息(embeds)创建了一个标题为“User Login”的消息。嵌入消息的其他属性包括颜色、字段名称和值等。更多关于嵌入消息的内容可以在 Discord 的开发者文档中找到。

结论

在本文中,我们演示了如何使用 PHP 和 Discord Webhooks 自动发送通知。无论是简单的文本消息还是复杂的嵌入消息,PHP 与 Discord Webhooks 的结合使得发送消息变得非常简单,只需几行代码即可。使用这种方法,你可以创建强大的自动化通知,以提高你的网站或应用程序的用户体验。