Laravel Http发送Discord Webhook报50006空消息错误排查
问题分析与修复方案
出现Cannot send an empty message(错误码50006)的核心原因是Discord无法正确解析请求内容,以下是代码中的关键问题及修复方式:
1. 手动设置Content-Type边界导致请求格式错误
你手动指定了multipart/form-data的boundary,但Laravel的asMultipart()方法会自动生成并处理正确的boundary,手动添加的边界会和框架生成的冲突,导致Discord无法识别payload_json字段。
修复:删除手动设置的Content-Type头部
// 移除手动设置Content-Type的行 Http::asMultipart() ->post($this->webhookUrl, [...]);
2. 图片内容使用Data URI格式,而非原始二进制数据
你传递的图片内容是data:image/jpeg;base64,[[encoded image]]这种Data URI字符串,但Discord期望接收的是原始的二进制文件内容,带前缀的字符串会被识别为无效文件内容,同时干扰payload解析。
修复:解码Base64字符串为二进制内容
// 替换图片的contents部分 [ 'name' => 'image1.jpg', 'contents' => base64_decode(str_replace('data:image/jpeg;base64,', '', '[[encoded image]]')), 'headers' => [ 'Content-Type' => 'image/jpeg', ] ], [ 'name' => 'image2.jpg', 'contents' => base64_decode(str_replace('data:image/jpeg;base64,', '', '[[encoded image]]')), 'headers' => [ 'Content-Type' => 'image/jpeg', ] ]
3. 可选优化:payload_json使用数组而非字符串
虽非直接错误原因,但用数组传递payload内容,Laravel会自动处理JSON编码,避免手动写JSON字符串可能出现的语法错误:
[ 'name' => 'payload_json', 'contents' => json_encode([ 'content' => 'Hello, World!', 'embeds' => [ [ 'title' => 'Hello, Embed!', 'description' => 'This is an embedded message.', 'thumbnail' => ['url' => 'attachment://image1.jpg'], 'image' => ['url' => 'attachment://image2.jpg'] ] ], 'attachments' => [ ['id' => 0, 'description' => 'Image of a cute little cat', 'filename' => 'image1.jpg'], ['id' => 1, 'description' => 'Rickroll gif', 'filename' => 'image2.jpg'] ] ]), 'headers' => ['Content-Type' => 'application/json'] ]
修复后的完整代码示例
Http::asMultipart() ->post( $this->webhookUrl, [ [ 'name' => 'payload_json', 'contents' => json_encode([ 'content' => 'Hello, World!', 'embeds' => [ [ 'title' => 'Hello, Embed!', 'description' => 'This is an embedded message.', 'thumbnail' => ['url' => 'attachment://image1.jpg'], 'image' => ['url' => 'attachment://image2.jpg'] ] ], 'attachments' => [ ['id' => 0, 'description' => 'Image of a cute little cat', 'filename' => 'image1.jpg'], ['id' => 1, 'description' => 'Rickroll gif', 'filename' => 'image2.jpg'] ] ]), 'headers' => [ 'Content-Type' => 'application/json', ] ], [ 'name' => 'image1.jpg', 'contents' => base64_decode(str_replace('data:image/jpeg;base64,', '', '[[encoded image]]')), 'headers' => [ 'Content-Type' => 'image/jpeg', ] ], [ 'name' => 'image2.jpg', 'contents' => base64_decode(str_replace('data:image/jpeg;base64,', '', '[[encoded image]]')), 'headers' => [ 'Content-Type' => 'image/jpeg', ] ] ] );
内容的提问来源于stack exchange,提问作者Bird87 ZA
相关产品推荐
相关产品推荐

