Skip to main content
 首页 » 编程设计

python之如何从 Telegram Bot 发送文件

2024年12月31日7bluestorm

我正在编写一个 Telegram 机器人,我需要向用户发送文件。我想获取要发送的文件的 file_id。我正在关注 this answer .

要获取 file_id,我应该将文件发送到我的 Telegram 机器人。问题是如何通过我的机器人将文件发送给自己? (也许使用 API?)

请您参考如下方法:

You can send files没有file_id:

There are three ways to send files (photos, stickers, audio, media, etc.):

  • If the file is already stored somewhere on the Telegram servers, you don't need to reupload it: each file object has a file_id field, simply pass this file_id as a parameter instead of uploading. There are no limits for files sent this way.
  • Provide Telegram with an HTTP URL for the file to be sent. Telegram will download and send the file. 5 MB max size for photos and 20 MB max for other types of content.
  • Post the file using multipart/form-data in the usual way that files are uploaded via the browser. 10 MB max size for photos, 50 MB for other files

仅当您之前已经将其发送给某人(使用 URL 或 multipart/form-data)时,您才可以使用 file_id。


因此,如果您要发送的文件列表是预定义的“静态”,您可以一次上传所有文件,获取它们的 file_id(使用 getUpdates方法),存储文件与其各自的 file_id 之间的关联,最终您的机器人可以仅使用 file_id 与用户通信。

另一方面,如果可能的文件列表不同,您只能通过 URL 或 multipart/form-data 发送文件。