如何下载发送到我的 Telegram 机器人的文件或照片? [英] How do I download a file or photo that was sent to my Telegram bot?

查看:81
本文介绍了如何下载发送到我的 Telegram 机器人的文件或照片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用电报机器人 API,但无论如何我无法下载发送到我的机器人的文件.我得到了文件的哈希值,但不知道如何处理它.有什么办法吗?谢谢.

I am using the telegram bot API but I cant see anyway to download a filé that was sent to my bot. I get a hash of the file but dont know what to do with it. Is there any way? Thanks.

推荐答案

现已推出!

https://core.telegram.org/bots/api#getfile

万岁!它是在 9 月 18 日添加的:

Hooray! It was added on Sep 18th:

https://core.telegram.org/bots/api

用法:

在消息的 JSON 中,您将像以前一样收到 file_id.带有语音文件的消息对象示例:

In the JSON of the message you will receive a file_id as before. An example of a message object with a voice file:

{
  message_id: 2675,
  from: {
    id: 10000001,
    first_name: 'john',
    username: 'john'
  },
  chat: {
    id: 10000001,
    first_name: 'john',
    username: 'john'
  },
  date: 1442848171,
  voice: {
    duration: 2,
    mime_type: 'audio/ogg',
    file_id: 'AwADBAADYwADO1wlBuF1ogMa7HnMAg',  //  <------- file_id
    file_size: 17746
  }
}

通过 API 的 getFile,您现在可以获得文件所需的路径信息:

Via the API's getFile you can now get the required path information for the file:

https://api.telegram.org/bot<bot_token>/getFile?file_id=the_file_id

这将返回一个带有 file_idfile_sizefile_path 的对象.然后您可以使用 file_path 下载文件:

This will return an object with file_id, file_size and file_path. You can then use the file_path to download the file:

https://api.telegram.org/file/bot<token>/<file_path>

请注意,此链接仅在一个小时内可用.一个小时后,您可以请求另一个链接.这意味着,如果您想以某种方式托管文件,并且宁愿避免在每次提供文件时检查和重新检查新链接,那么最好将文件下载到您自己的托管服务.

Note that this link will only be available for an hour. After an hour you can request another link. This means that if you want to host the file somehow and you rather avoid checking and re-checking for fresh links every time you serve it you might be better off downloading the file to your own hosting service.

通过此方法获取的文件最大为20MB.错误:使用大于 20mb 的文件时获得.(如下所示)

The maximum size of a file obtained through this method is 20MB. Error: Obtained when a file large than 20mb is used.(Shown below)

{"ok":false,"error_code":400,"description":"Bad Request: file is too big[size:1556925644]"}

来自电报的文档:

成功后,返回一个 File 对象.然后可以通过链接下载该文件 https://api.telegram.org/file/bot/,从响应中获取的位置.保证链接的有效期至少为 1 小时.当链接过期时,可以通过再次调用 getFile 来请求新的链接.目前,机器人可以下载最大 20MB 的文件.

On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot/, where is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again.For the moment, bots can download files of up to 20MB in size.

这篇关于如何下载发送到我的 Telegram 机器人的文件或照片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆