douben6670 2016-03-09 22:55
浏览 61
已采纳

电报机器人sendPhoto无法正常工作

What I'm trying to do is retrieving profile photos from a user and sned them for another, all by PHP.

The problem is when I send photos using file_id string, all of the photos sent to user are the same single picture!

I've not really run that but I'm sending my own photos to myself for testing the functionality and the result is my current telegram profile picture, every time.

My code:

<?php
define('my_id', '12345678');

$userPhotos = apiRequestJson("getUserProfilePhotos", array('user_id' => my_id, 'offset' => 0, 'limit' => 1));

apiRequestJson("sendPhoto", array('chat_id' => my_id, 'photo' => $userPhotos['photos'][0][0]['file_id']));
apiRequestJson("sendPhoto", array('chat_id' => my_id, 'photo' => $userPhotos['photos'][0][1]['file_id']));
?>

Link to the telegram bot api: https://core.telegram.org/bots/api

I'd be thankfull for any help.

  • 写回答

1条回答 默认 最新

  • dongzhui9936 2016-03-09 23:41
    关注

    There are two problems in your code.

    First of all, when in the request you set the limit parameter to 1, you request for only one photo. Simply remove the optional offset and limit parameters to retrieve first 100 photos:

    $userPhotos = apiRequestJson( 'getUserProfilePhotos', array( 'user_id' => my_id ) );
    

    Second problem: the returned response is an “Array of Array of PhotoSize”, that means an array of photos that are arrays of different photo sizes:

    $userPhotos['photos'][0][0]['file_id']
                          │  │
                  photos ─┘  └─ photo sizes
    

    You iterate second index (the size of same photo); you have instead to iterate first index:

    apiRequestJson( 'sendPhoto', array( 'chat_id' => my_id, 'photo' => $userPhotos['photos'][0][0]['file_id'] ) );
    apiRequestJson( 'sendPhoto', array( 'chat_id' => my_id, 'photo' => $userPhotos['photos'][1][0]['file_id'] ) );
    

    Since you don't know in advance the total photo number of each user, the best way is to iterate through a foreach loop:

    foreach( $userPhotos['photos'] as $photo )
    {
        apiRequestJson( 'sendPhoto', array( 'chat_id' => my_id, 'photo' => $photo[0]['file_id'] ) );
    }
    

    Last but not least, please note that with this request you retrieve the user profile photos, so in most cases you will obtain anyway only one photo.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?