首页 > 解决方案 > Python电报API。我不明白如何通过 Python lib 将图像发送到电报

问题描述

我正在尝试将照片从我的硬盘上传到电报。在文档中说要使用upload_file():

telegraph.upload.upload_file(f) 将文件上传到 Telegra.ph 的服务器。返回链接列表。仅允许 .jpg、.jpeg、.png、.gif 和 .mp4 文件。参数: f (file, str or list) – 文件名或类文件对象。

但我不明白“f (file, str or list) – filename or file-like object”是什么意思。也就是说,我需要对照片做什么,以便它可以传递给这个函数

我解决问题的尝试:

upload_file(open('1.png', 'rb'))

错误:telegraph.exceptions.TelegraphException:文件类型无效

myf = io.StringIO()
        myf.write(open(f'photo/{i}.png', 'rb'))
        print(upload_file(myf))
        myf.close()

错误:TypeError:需要字符串参数,得到'_io.BufferedReader'

标签: pythonpython-3.xtelegraph

解决方案


我正在使用这种方法加载图像

  
def upload_image_telegraph(path_image):
    with open(path_image, 'rb') as f:
        result_requests = requests.post(
            'http://telegra.ph/upload',
            files={'file': ('file', f, 'image/jpg')}  # image/gif, image/jpeg,image/jpg, image/png, video/mp4
        ).json()
        return result_requests

您还可以使用 Python 库下载 html_telegraph_poster 在它的帮助下,您可以传输本地图像和指向它们的链接示例

  
from html_telegraph_poster import upload_image
res = upload_image('local path image or link image') 

推荐阅读