【问题标题】:Is there a way to get profile picture updates using python Telegram-Bot?有没有办法使用 python Telegram-Bot 获取个人资料图片更新?
【发布时间】:2018-08-20 00:10:26
【问题描述】:

所以我使用python-telegram-bot 将电报集成到另一个应用程序中。我的目标是在我的应用程序中的电报上有用户的个人资料图片。 (用户和群聊)

获取用户或群组的头像很容易,在我的应用中下载和使用它也是如此。但是,如果用户更改了他们的个人资料图片怎么办?我在允许机器人检索图片更改的文档中找不到任何更新消息或处理程序,甚至对于组也不行。

我的第一个想法是首先检索所有图片并将file_id存储在数据库中,然后定期检查用户/组的图片并返回他们的图片,直到file_id与数据库中最后保存的file_id匹配.

这与JobQueue 相结合是我能想到的最好的东西,所以我会用它来自我回答,但我认为它仍然不是一个完美的解决方案,所以如果有人有更好的想法,我会很感激一个答案。

我正在专门为群组寻找更好的解决方案,因为我认为除了最近的群组图片外,没有其他方法可以检索任何图片,我的应用程序应该检索所有他们。我的自我回答的另一个缺陷是,如果用户在这六个小时内两次更改个人资料图片,我只会得到最新的。对于机器人调用中具有offset 属性的用户,可以修复此问题,但用于获取群组头像的method 似乎没有。

tl;博士:

当用户更改他们的或组个人资料图片时,如何以最有效和最可靠的方式使用 python-telegram-bot 和 python 3.5 检索更新? p>

【问题讨论】:

    标签: python python-3.x telegram telegram-bot python-telegram-bot


    【解决方案1】:

    这是使用telegram.ext.JobQueue 每 6 小时检查一次个人资料图片更新。

    # define job queue
    j = updater.job_queue
    
    def dl_pfps(bot, job):
        # this assumes that we have a textfile with the following
        # layout: "user_id:last_pfp_file_id" - One per line
        # later we'll write a list back into it with the newest IDs
        user_pfp_list = []
        with open("user_pfps.txt") as f:
            for line in f:
                user_id = line.split(':')[0]
                last_file_id = line.split(':')[1]
                most_recent_pfp = bot.get_user_profile_photos(user_id, limit=1).photos[0]
                if last_file_id == most_recent_pfp[-1].file_id:
                    print("No change")
                    user_pfp_list.append(user_id + ":" + last_file_id)
                else:
                    print("User updated profile picture. Geting full size picture...")
                    # download and process the picture
                    file_id = most_recent_pfp[-1].file_id
                    newFile = bot.getFile(file_id)
                    newFile.download('my/filename.jpg')
                    user_pfp_list.append(user_id + ":" + file_id)
    
        # write new list back to file (overwrite current list)
        with open("user_pfps.txt", "w") as f:
            f.write("\n".join(user_pfp_list))
    
    # check for new profile pictures every 6 hours
    job_dlpfps = j.run_repeating(dl_pfps, interval=21600, first=0)
    

    这是我能想到的最好的。如果您想在代码中使用它,您必须将 'my/filename.jpg' 调整为正确的文件名,并且您需要在 user_pfps.txt 中生成一个初始列表,每个用户一行如下:user_id:0

    【讨论】:

      猜你喜欢
      • 2017-04-08
      • 2020-04-26
      • 2021-12-15
      • 1970-01-01
      • 2013-07-08
      • 2019-06-04
      • 1970-01-01
      • 2013-02-05
      • 1970-01-01
      相关资源
      最近更新 更多