thinkphp 对接 discord中midjourney的详细步骤包括引入代码发送请求
-
首先需要在 Discord 开发者门户中创建一个新的应用程序。在这个应用程序中,选择 Bot 标签页,并创建一个新的 Bot 用户。记录下来 Bot 的 Token,它将在后面用到。
-
安装 GuzzleHttp 依赖:
composer require guzzlehttp/guzzle -
在 ThinkPHP 项目中创建一个新的控制器,例如 DiscordController.php。
-
在 DiscordController.php 中引入 GuzzleHttp 库:
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\RequestException;
- 在 DiscordController.php 中创建一个新的方法,例如 sendMessage(),并传入要发送的消息:
public function sendMessage($message)
{
$url = 'https://discord.com/api/v8/channels/CHANNEL_ID/messages';
$data = array('content' => $message);
$headers = array('Authorization' => 'Bot BOT_TOKEN', 'Content-Type' => 'application/json');
$client = new Client();
$request = new Request('POST', $url, $headers, json_encode($data));
try {
$response = $client->send($request);
$code = $response->getStatusCode(); // 获取状态码
$body = $response->getBody(); // 获取响应内容
return $body;
} catch (RequestException $e) {
$response = $e->getResponse();
$code = $response->getStatusCode();
$body = $response->getBody();
return $body;
}
}
-
将 CHANNEL_ID 替换为 Discord 频道的 ID,将 BOT_TOKEN 替换为在 Discord 开发者门户中创建的 Bot 的 Token。
-
现在可以在需要发送消息的地方调用 sendMessage() 方法,例如:
$message = 'Hello, world!';
$this->sendMessage($message);
- 如果一切正常,Discord 频道中应该会出现一条新的消息
原文地址: https://www.cveoy.top/t/topic/dGCN 著作权归作者所有。请勿转载和采集!