libcpr / cpr

C++ Requests: Curl for People, a spiritual port of Python Requests.
https://docs.libcpr.org/
Other
6.49k stars 922 forks source link

trying to use discord webhook api: St12length_error - basic_string::_M_create #1011

Closed testmina77 closed 8 months ago

testmina77 commented 8 months ago

Description

While running my program it was giving me error like this:

terminate called after throwing an instance of 'std::length_error'
  what():  basic_string::_M_create
zsh: IOT instruction  ./main2

More info with exception.what St12length_error - basic_string::_M_create

Example/How to Reproduce

Code:

void sendwebhookmessage(const std::vector<std::string>& webhooks) {
        for (const auto webhook : webhooks) {
        std::string error;
            for (int i = 0; i < 10; i++) {
                try {
                    std::cout << "webhook: " << webhook;

                    cpr::Header headers{
                    {"Content-Type", "application/json"},
                    {"Authorization", "Bot " + bottoken}
                    };

                    cpr::Body body{{"content", "Hello World"}};
                    std::stringstream urlStream;
urlStream << "http://discord.com/api/v7/webhooks/" << webhook;
cpr::Url url(urlStream.str());
            auto response = cpr::Post(cpr::Url{urlStream.str()}, headers, body);

                    if (response.status_code != 200) {
                        std::cout << "[!] Failed to send webhook. Status code: " << response.status_code << "\n";
                    }
                } catch (const std::exception& e) {
    std::cout << "Exception during webhook request: " << typeid(e).name() << " - " << e.what() << "\n";
    std::cout << "API response text: " << error << "\n";

                }

            }

        }

}

webhooks vector equals for example this:

id/token

1193248954217930854/vqZ9krEbImBmyoXWDxBelwiECdK9CkblwuVmz7U9flcylTbc1lbqPTmnxQQYIFnqX2EB

Possible Fix

No response

Where did you get it from?

vcpkg

Additional Context/Your Environment

COM8 commented 8 months ago

Try replacing cpr::Body with cpr::Payload if you want so send a basic JSON message. "Hello World" is being interpreted as the string length of "content". This is caused by us forwarding everything to the std::string ctr you pass to cpr::Body.