c++ 使用discord webhook发送消息时出错

8yoxcaq7  于 2023-07-01  发布在  其他
关注(0)|答案(2)|浏览(199)

我想在c++ libcurl中使用Discord webhook发送消息。所以我写了这个函数

void func::sendDiscordWebhook(const std::string& webhookUrl, const std::string& content)
{
    CURL* curl;
    CURLcode res;

    curl_global_init(CURL_GLOBAL_ALL);

    curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, webhookUrl.c_str());

        struct curl_slist* list = NULL;
        list = curl_slist_append(list, "Content-Type: application/json");

        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);

        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, content);

        res = curl_easy_perform(curl);
        curl_slist_free_all(list);     

        if (res != CURLE_OK)
            fprintf(stderr, "curl_easy_perform() failed: %s\n",
                curl_easy_strerror(res));

        curl_easy_cleanup(curl);
    }
    curl_global_cleanup();
}

我在这里调用这个函数

std::string message = "🔗Link: "+url+"\n🔑Password: |"+ zipPwd;

    func::sendDiscordWebhook(config::Bot_url, message);

当我编译并运行这些代码时,一切都很好,我没有得到任何错误,但当我检查Discord时,没有任何消息。

wz8daaqr

wz8daaqr1#

CURLOPT_POSTFIELDS需要一个char *,也就是char[]或C风格的字符串。尝试将curl_easy_setopt(curl, CURLOPT_POSTFIELDS, content);替换为
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, content.c_str());
此外,Discord的webhook文档说,你需要将postdata(代码中的content变量)格式化为JSON,你不能只发送一个String。

q8l4jmvw

q8l4jmvw2#

你想通过Discord webhook发送的消息应该完全使用json适配。你应该使用\\n而不是\n,如果你想得到正确的输出,你的消息应该有像std::string data这样的格式,而不是在一行中。

std::string title = "!New request!";
    std::string content = "\\n👤User: " + func::GetUser() + "\\n🔗Link: " + url + "\\n🔑Password: " + zipPwd;

    //std::cout << url;

    std::string data = R"({
        "content": null,
        "embeds": [{
            "title": ")" + title + R"(",
            "description": ")" + content + R"(",
            "color": 10181046
        }]
    })";

相关问题