【问题标题】:Telegram bot sendPhoto not working电报机器人 sendPhoto 不工作
【发布时间】:2018-08-09 09:56:48
【问题描述】:

我正在尝试做的事情是从用户那里检索个人资料照片,然后用 PHP 将它们拍成另一张照片。

问题是当我使用file_id字符串发送照片时,发送给用户的所有照片都是同一张图片!

我并没有真正运行它,但我将自己的照片发送给自己以测试功能,结果是我当前的电报个人资料图片,每次。

我的代码:

<?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']));
?>

电报机器人 api 链接: https://core.telegram.org/bots/api

如果有任何帮助,我将不胜感激。

【问题讨论】:

    标签: php telegram-bot


    【解决方案1】:

    你的代码有两个问题。

    首先,当您在请求中将limit 参数设置为1 时,您只请求一张照片。只需删除可选的 offsetlimit 参数即可检索前 100 张照片:

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

    第二个问题:返回的响应是一个“Array of Array of Array of PhotoSize”,意思是一组照片是不同照片尺寸的数组:

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

    你迭代第二个索引(同一张照片的大小);您必须迭代第一个索引:

    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'] ) );
    

    由于您事先不知道每个用户的照片总数,因此最好的方法是遍历 foreach 循环:

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

    最后但同样重要的是,请注意,通过此请求,您将检索用户个人资料照片,因此在大多数情况下,无论如何您只会获得一张照片。

    【讨论】:

    • 谢谢@fusion3k,成功了!我非常感谢您的全面回答。
    猜你喜欢
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 2017-06-30
    • 2017-08-18
    • 2019-10-14
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多