如何在Rust中向Discord webhook发送文件?

9nvpjoqh  于 2023-05-23  发布在  其他
关注(0)|答案(2)|浏览(161)

我试图发送一个文件到Discord webhook我已经阅读了Webhook Resource和上传文件,但我仍然无法让它工作。以下是基于API文档编写的内容:

use anyhow::Result;
use reqwest::multipart;

#[tokio::main]
async fn main() -> Result<()> {
    let client = reqwest::Client::new();

    let part = multipart::Part::bytes(image.as_slice())
        .file_name("text.png")
        .mime_str("image/png")?;
    let form = multipart::Form::new()
        .text("Content-Disposition", "form-data")
        .part("files[0]", part);

    let res = client
        .post("https://discord.com/api/webhooks/6969696969/XD_XD_XD_XD_XD_XD_XD_XD")
        .header("Content-Type", "multipart/form-data")
        .query(&[("wait", "true")])
        .multipart(form)
        .send()
        .await?;

    println!("Response: {:#?}", res);
    Ok(())
}

响应状态是400,我发现它意味着“Bad Request”。如何发送文件?

ibps3vxo

ibps3vxo1#

我用一个叫宁静的板条箱就能做到

use anyhow::Result; // You don't really need to use anyhow Result you can just use Result<(), Box<dyn Error>>
use serenity::{http::Http, model::webhook::Webhook};

#[tokio::main]
async fn main() -> Result<()> {
    let http = Http::new("token");

    let url = "https://discord.com/api/webhooks/{id}/{token}";
    let webhook = Webhook::from_url(&http, url).await?;

    webhook
        .execute(&http, true, |w| {
            w.content("Test")
                .username("Test")
                .add_file("/path/to/file")
        })
        .await?;
    Ok(())
}
9lowa7mx

9lowa7mx2#

你不应该设置.header("Content-Type", "multipart/form-data"),因为.multipart()函数为你做了,和.text("Content-Disposition", "form-data")一样

相关问题