【问题标题】:Getting the user profile pictures with pyTelegramBotAPI (JSON)使用 pyTelegramBotAPI (JSON) 获取用户头像
【发布时间】:2020-11-03 22:53:09
【问题描述】:

这是我的代码(Python):

import telebot
import time
import json

bot_token = "..."
bot = telebot.TeleBot(token=bot_token)

@bot.message_handler(commands=['myphoto'])
def send_welcome(message):
    number = bot.get_user_profile_photos(message.from_user.id)
    njson = json.loads(number)
    nlist = njson['photos']
    bot.reply_to(message, nlist[0].file_size)

while True:
    try:
        bot.polling(none_stop=True)

    except Exception as e:
        logger.error(e)  # or just print(e) if you don't have logger,
        # or import traceback; traceback.print_exc() for print full info
        time.sleep(15)

这里是 JSON 的结果,其中包含一个包含我的帐户 Telegram 的个人资料图片的数组(它是我的代码中变量 "number" 的结果):

{'total_count': 2, 'photos': [[<telebot.types.PhotoSize object at
0x7fc0fd9069a0>, <telebot.types.PhotoSize object at 0x7fc0fd906970>,
<telebot.types.PhotoSize object at 0x7fc0fd906a30>],
[<telebot.types.PhotoSize object at 0x7fc0fd906550>,
<telebot.types.PhotoSize object at 0x7fc0fd906eb0>,
<telebot.types.PhotoSize object at 0x7fc0fd906790>]]}

这里涉及到来自 pyTelegramBotAPI link 的类

但是打印变量 njson 或 nlist[0] 它什么也没有显示。问题出在哪里?我想获取该数组中单个 PhotoSize 对象的 file_id(执行 photosizeName.file_id,因此我可以使用常规默认 Telegram API 下载图片)。

【问题讨论】:

    标签: python json api telegram py-telegram-bot-api


    【解决方案1】:

    如果你密切关注这一点:

    {'total_count': 2, 'photos': [[<telebot.types.PhotoSize object at
    0x7fc0fd9069a0>, <telebot.types.PhotoSize object at 0x7fc0fd906970>,
    <telebot.types.PhotoSize object at 0x7fc0fd906a30>],
    [<telebot.types.PhotoSize object at 0x7fc0fd906550>,
    <telebot.types.PhotoSize object at 0x7fc0fd906eb0>,
    <telebot.types.PhotoSize object at 0x7fc0fd906790>]]}
    

    photos 是一个数组数组。照片[0] 是一个列表,那么您必须更深入地选择其中一个文件,例如这张照片[0][0]。

    无论如何,您应该添加更多信息,您的程序是否抛出错误?

    【讨论】:

    • 谢谢,你没看错,是[0][0]。但错误是:in loads raise TypeError(f'the JSON object must be str, bytes or bytearray). TypeError: the JSON object must be str, bytes or bytearray, not UserProfilePhotos,所以它可以在 number.total_countnumber[0][0] 上运行,因为 number 是一个包含一组照片的对象 (UserProfilePhotos)。
    • 对不起,number.photos[0][0].file_id(UserProfilePhotos 有一个数组“照片”)
    猜你喜欢
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 2013-01-13
    • 2018-08-19
    • 2012-07-11
    • 1970-01-01
    相关资源
    最近更新 更多