I’m trying to figure out how to use the sendPhoto method from Telegram’s Bot API using only Perl. I don’t want to use any external libraries like WWW::Telegram::BotAPI.
I’ve got sending text messages working fine with this code:
use LWP::UserAgent;
use HTTP::Request::Common;
use JSON::MaybeXS;
my $bot = LWP::UserAgent->new;
my $text_message = {
chat_id => $chat_id,
parse_mode => 'HTML',
text => $message_content
};
my $result = $bot->request(
POST 'https://api.telegram.org/bot' . $token . '/sendMessage',
Content_Type => 'application/json',
Content => encode_json($text_message)
);
But I’m stuck on how to send photos. What’s the right way to structure the JSON for uploading a new image? Should it look something like this?
my $photo_message = {
chat_id => $chat_id,
caption => $photo_caption,
photo => $image_data # Not sure how to handle this part
};
To implement the sendPhoto method in pure Perl, you’ll need to use multipart/form-data encoding instead of JSON. Here’s a rough outline of how to structure your request:
use LWP::UserAgent;
use HTTP::Request::Common;
my $bot = LWP::UserAgent->new;
my $req = POST 'https://api.telegram.org/bot' . $token . '/sendPhoto',
Content_Type => 'form-data',
Content => [
chat_id => $chat_id,
caption => $photo_caption,
photo => [ $image_path ]
];
my $result = $bot->request($req);
This approach uses the file path for the image. The LWP::UserAgent will handle the file reading and proper encoding. Make sure to replace $image_path with the actual path to your image file. This method should work for most image formats supported by Telegram.
Make sure to replace $image_path with the actual file path. This approach handles the file reading and encoding automatically and has been reliable for various image types. Let me know if you run into any issues!