如何使用电报 API 接收图像?

2022-08-31 00:55:33

是否可以接收由任何用户发送到机器人的图像(并将其存储在服务器上)?

如果发送了图像,我会收到此 JSON 帖子。这是指向 Telegram Bot-API 描述的链接。我不知道是否有可能接收整个图像:https://core.telegram.org/bots/api#available-types

{"update_id":XXXXX,
"message":{"message_id":2222,"from":{"id":XXXXX,"first_name":"Christoph","last_name":"XXXXX"},"chat":{"id":XXXXX,"first_name":"Christoph","last_name":"XXXXX"},"date":1435704055,"forward_from":{"id":XXXXX,"first_name":"Christoph","last_name":"XXXXX"},"forward_date":1435703471,"photo":[{"file_id":"AgADAgADmaoxG9KknwF4O978o3EMqb_EWSoABI5s-WWq46dqiR0AAgI","file_size":998,"width":51,"height":90},{"file_id":"AgADAgADmaoxG9KknwF4O978o3EMqb_EWSoABHax4HvxYqktiB0AAgI","file_size":9912,"width":180,"height":320},{"file_id":"AgADAgADmaoxG9KknwF4O978o3EMqb_EWSoABNzzDwp3sT2whx0AAgI","file_size":41020,"width":450,"height":800},{"file_id":"AgADAgADmaoxG9KknwF4O978o3EMqb_EWSoABE0Gg-AefJ7Yhh0AAgI","file_size":66058,"width":720,"height":1280}]}}

答案 1

电报支持下载文件现在与:getFile

您可以在 api 文档中看到它:https://core.telegram.org/bots/api#getfile


答案 2

可以从电报服务器下载图像。执行此操作:
1. 使用 api 获取文件getFile

//Telegram link
$telegram_link = 'https://api.telegram.org/bot' . $this->tg_configs['api_key'] . '/getFile?file_id=' . $photo['file_id'];

2. 获取文件路径 //创建 guzzle 客户端 $guzzle_client = new GuzzleClient();

//Call telegram
$request = $guzzle_client->get($telegram_link);
//Decode json
$json_response = json_decode($request->getBody(), true);
if ($json_response['ok'] == 'true') {

    //Telegram file link
    $telegram_file_link = 'https://api.telegram.org/file/bot' . $this->tg_configs['api_key'] . '/' . $json_response['result']['file_path'];

3. 如果使用 PHP,请使用 下载图像并将其保存在您的服务器上。Intervention/Image

//Build upload path
$upload_path = public_path() . \Config::get('media::media.uploadPath');
//Get image
$image = $thumbnail = InterventionImage::make($telegram_file_link);

//Get mime
$mime = $image->mime();

if ($mime == 'image/jpeg') {
    $extension = '.jpg';
} elseif ($mime == 'image/png') {
    $extension = '.png';
} elseif ($mime == 'image/gif') {
    $extension = '.gif';
} else {
    $extension = '';
}//E# if else statement
//Resize images
$image->resize(\Config::get('media::media.mainWidth'), \Config::get('media::media.mainHeight'));
$thumbnail->resize(\Config::get('media::media.thumbnailWidth'), \Config::get('media::media.thumbnailHeight'));

//Build media name
$media_name = \Str::random(\Config::get('media::media.mediaNameLength')) . $extension;

//Save images
$image->save($upload_path . '/' . $media_name);
$thumbnail->save($upload_path . '/thumbnails/' . $media_name);

推荐