代码之家  ›  专栏  ›  技术社区  ›  Antonizz

我无法使用cURL错误发送带有不一致webhook的消息:“无法发送空消息

  •  1
  • Antonizz  · 技术社区  · 2 年前

    因此,我试图使用以下代码向discord webhook发送消息:

    #include <iostream>
    #include <curl/curl.h>
    
    int main(void)
    {
        CURL* curl;
        CURLcode res;
    
        const char* WEBHOOK = "webhookLink";
        const char* content = "test";
    
        curl_global_init(CURL_GLOBAL_ALL);
    
        curl = curl_easy_init();
        if (curl) {
            curl_easy_setopt(curl, CURLOPT_URL, WEBHOOK);
    
            curl_easy_setopt(curl, CURLOPT_POSTFIELDS, content);
    
            res = curl_easy_perform(curl);
    
            if (res != CURLE_OK)
                fprintf(stderr, "curl_easy_perform() failed: %s\n",
                    curl_easy_strerror(res));
    
            curl_easy_cleanup(curl);
        }
        curl_global_cleanup();
    }
    

    我从cURL文档中获得了这段代码。每次我运行它都会输出 {“message”:“无法发送空消息”,“代码”:50006} 在控制台中。

    有什么想法吗?

    编辑:它与命令行一起工作

    curl -i -H "Accept: application/json" -H "Content-Type:application/json" -X POST --data "{\"content\": \"Posted Via Command line\"}" $WEBHOOK_URL
    
    1 回复  |  直到 2 年前
        1
  •  0
  •   Ted Lyngmo    2 年前

    您需要添加 Content-Type 标题到您的请求。

    示例(我没有discord webhook,因此无法测试):

    #include <curl/curl.h>
    
    #include <iostream>
    
    int main(void) {
        CURL* curl;
        CURLcode res;
    
        const char* WEBHOOK = "webhookLink";
        const char* content = R"aw({"content": "Posted Via libcurl"})aw";
    
        curl_global_init(CURL_GLOBAL_ALL);
    
        curl = curl_easy_init();
        if(curl) {
            curl_easy_setopt(curl, CURLOPT_URL, WEBHOOK);
    
            // create a curl list of header rows:
            struct curl_slist* list = NULL;
    
            // add Content-Type to the list:
            list = curl_slist_append(list, "Content-Type: application/json");
    
            // set this list as HTTP headers:
            curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);
    
            curl_easy_setopt(curl, CURLOPT_POSTFIELDS, content);
    
            res = curl_easy_perform(curl);
            curl_slist_free_all(list);     // and finally free the list
    
            if(res != CURLE_OK)
                fprintf(stderr, "curl_easy_perform() failed: %s\n",
                        curl_easy_strerror(res));
    
            curl_easy_cleanup(curl);
        }
        curl_global_cleanup();
    }
    

    (还应添加额外的错误检查)