php - 通过 discord webhook 发送附件/文件

标签 php curl discord webhooks

我一直在尝试弄清楚如何在 webhook 中发送附件。我已经尝试了几个小时,但无法弄清楚。我一直在阅读 this但我仍然没有太多联系。我也一直在阅读 docs但很难理解。谁能帮助我?

<pre><?php 

$url = "WEBHOOK URL HERE";

$headers = [ 'Content-Type: multipart/form-data; charset=utf-8' ];
$POST = [
    // Message
    "content" => "Hello World!",
    
    // Username
    "username" => "testuser",

    // File upload
    "file" => curl_file_create("image.gif", 'image/gif', 'image')

];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($POST));
$response   = curl_exec($ch);
var_dump($response);

我遇到了错误

"{"message": "Cannot send an empty message", "code": 50006}"

最佳答案

替换

"file" => curl_file_create("image.gif", 'image/gif', 'image.gif')

"file" => curl_file_create(realpath("image.gif"), 'image/gif', 'image.gif')
<pre><?php 

$url = "WEBHOOK URL HERE";

$headers = [ 'Content-Type: multipart/form-data; charset=utf-8' ];
$POST = [
    // Message
    "content" => "Hello World!",
    
    // Username
    "username" => "testuser",

    // File upload
    "file" => curl_file_create(realpath("image.gif"), 'image/gif', 'image.gif')

];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($POST));
$response   = curl_exec($ch);
var_dump($response);

以上代码只是将你自己的服务器文件上传到discord。

如果您想从其他 URL 获取文件并上传到 Discord,那么您需要先将相同的文件上传到您自己的服务器上作为临时文件,然后在此处设置此临时文件..

"file" => curl_file_create(realpath($tempfile), 'image/gif', 'image.gif')

之后

$response   = curl_exec($ch);
unlink($tempfile); //delete temp file if you want.

关于php - 通过 discord webhook 发送附件/文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70028361/

相关文章:

curl - 来自 strip curl 的 NSUrlRequest

python - 对帖子使用react时添加角色的问题

php数组元素大小有限

php - 为图像添加透明水印

linux - 读取 bash 脚本中的命令在通过管道传输到 bash 时不等待用户输入?

c - "No symbol version section for versioned symbol"

javascript - 获取服务器 discord.js 上所有用户的列表

javascript - Discord.js user.bot 未定义?

php - 如何在没有API的情况下从网站获取数据

PHP:使用同名方法处理特征