How to implement Telegram Bot's sendPhoto method in pure Perl?

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
};

Any help would be great. Thanks!

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.

hey, for sendin photos u gotta use multipart/form-data instead of json. try somethin like this:

my $req = POST ‘https://api.telegram.org/bot$token/sendPhoto’,
Content_Type => ‘form-data’,
Content => [
chat_id => $chat_id,
caption => $caption,
photo => [$image_path]
];

$result = $bot->request($req);

hope that helps!

I’ve dealt with this exact issue before. The key is using multipart/form-data encoding instead of JSON for photo uploads. Here’s what worked for me:

use LWP::UserAgent;
use HTTP::Request::Common;

my $ua = LWP::UserAgent->new;

my $request = POST ‘https://api.telegram.org/bot’ . $token . ‘/sendPhoto’,
Content_Type => ‘form-data’,
Content => [
chat_id => $chat_id,
caption => $caption,
photo => [ $image_path, ‘image.jpg’, Content_Type => ‘image/jpeg’ ]
];

my $response = $ua->request($request);

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!