我决定在 Telebot 上为 Telegram 编写一个简单的机器人。我遇到了一个问题:我需要下载用户发送的所有文件和文本。我这样做:
from config import TOKEN
import telebot
import os
import time
bot = telebot.TeleBot(TOKEN)
@bot.message_handler(commands=['start'])
def start(message):
bot.send_message(message.chat.id, 'Отправь своё (фото, видео, музыку, или текст)')
@bot.message_handler(content_types=['text', 'photo', 'video', 'audio'])
def download_data(message):
user_directory = f'data/{message.from_user.username}'
if not os.path.exists(user_directory):
os.makedirs(user_directory)
if message.photo:
photo = message.photo[-1]
file = bot.get_file(photo.file_id)
downloaded_file = bot.download_file(file.file_path)
filename = f'{user_directory}/photo_{int(time.time())}.jpg'
with open(filename, 'wb') as f:
f.write(downloaded_file)
elif message.video:
video = message.video
file = bot.get_file(video.file_id)
downloaded_file = bot.download_file(file.file_path)
filename = f'{user_directory}/video_{int(time.time())}.mp4'
with open(filename, 'wb') as f:
f.write(downloaded_file)
elif message.audio:
audio = message.audio
file = bot.get_file(audio.file_id)
downloaded_file = bot.download_file(file.file_path)
filename = f'{user_directory}/audio_{int(time.time())}.mp3'
with open(filename, 'wb') as f:
f.write(downloaded_file)
elif message.text:
filename = f'{user_directory}/text.txt'
with open(filename, 'w') as f:
f.write(message.text)
bot.infinity_polling()
发送大量图像、视频或音频时,会下载所发送内容的一小部分。我需要保存所有发送的文件。提前致谢!
