tdlib / td

Cross-platform library for building Telegram clients
https://core.telegram.org/tdlib
Boost Software License 1.0
7.11k stars 1.44k forks source link

Use of deleted function when casting update_new_message to messagePhoto(trying to get caption) #2915

Closed sierret closed 4 months ago

sierret commented 4 months ago

I am largely following the example C++ code. I have:

void TdExample::process_update(td_api::object_ptr<td_api::Object> update) {
    td_api::downcast_call(
        *update, overloaded(
                     ...
                     [this](td_api::updateNewMessage &update_new_message) {
                       ...
                       if (update_new_message.message_->content_->get_id() == td_api::messageText::ID) {
                        // text = static_cast<td_api::messageText &>(*update_new_message.message_->content_).text_->text_;
                         auto messPhoto = static_cast<td_api::messagePhoto &>(*update_new_message.message_->content_);

                       }
...

However, trying to cast the update_new_message to a messagePhoto I receive the error message use of deleted function. Meanwhile casting update_new_message to a messageText works fine. I'm unsure how to preceed. The only way to receive a photo caption seems to be through a messagePhoto object, the casting of which fails.

levlam commented 4 months ago
                       if (update_new_message.message_->content_->get_id() == td_api::messageText::ID) {
                        // text = static_cast<td_api::messageText &>(*update_new_message.message_->content_).text_->text_;
                         auto messPhoto = static_cast<td_api::messagePhoto &>(*update_new_message.message_->content_);

This code has undefined behavior accroding to C++ standard, because you cast the object reference to a wrong type. The code will crash at the best, but anything else can happen.

It would be simpler to use TDLib from an interpreted language. See https://github.com/tdlib/td/tree/master/example#tdlib-usage-and-build-examples for examples of such usages.

sierret commented 4 months ago

Thank you for the reply. I understand but my stack is built on C++. Could you direct me in a way to get the caption from a message using C++? Actually just how to get the messagePhoto object from a message.

I'd be oh so appreciative.

sierret commented 4 months ago

i figured it out.

 if (update_new_message.message_->content_->get_id() == td_api::messagePhoto::ID) {
                         caption = static_cast<td_api::messagePhoto &>(*update_new_message.message_->content_).caption_->text_;
                       }

I also learning something new about C++. I thought the issue was with the casting itself, meanwhile I had to also have the actual field of the object be correct as well.