我正在尝试将用户发送给我的机器人的文件上传到Google驱动器中。
这是我的python代码
#!/usr/bin/env python
import os
import telegram
import logging
from telegram.ext import Updater
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler ,MessageHandler
from telegram.ext import MessageHandler, Filters
from __future__ import print_function
from apiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',level=logging.INFO)
logger = logging.getLogger(__name__)
SCOPES = 'https://www.googleapis.com/auth/drive'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secrets.json', SCOPES)
creds = tools.run_flow(flow, store)
DRIVE = discovery.build('drive', 'v2', http=creds.authorize(Http()))
def file_handler(bot, update):
file = bot.getFile(update.message.document.file_id)
file.download(update.message.document.file_name)
FILES = ((update.message.file_name, False),(update.message.file_name, True),)
for filename, convert in FILES:
metadata = {'title': filename}
res = DRIVE.files().insert(convert=convert, body=metadata,
media_body=filename ).execute()
if res:
print('Uploaded "%s" (%s)' % (filename, res['mimeType']))
def error(bot, update, error):
logger.warning('Update "%s" caused error "%s"', update, error)
def main():
updater = Updater(token='xxxxxxxxxx')
dispatcher = updater.dispatcher
dispatcher.add_handler(MessageHandler(Filters.document,file_handler))
updater.start_polling()
if __name__ == '__main__':
main()
通过此代码,我可以将用户上传的文件下载到bot(没有google-api部分)。
但是如何将这些文件上传到Google驱动器...
谢谢!
答案 0 :(得分:0)
通过组合google-drive-api
和telegram-bot-api
将文件从电报上传到Google驱动器非常简单。
这是描述代码工作原理的流程图。
bot.py
def file_handler(bot, update):
file = bot.getFile(update.message.document.file_id)
file.download(update.message.document.file_name)
FILES = ((update.message.document.file_name, False),(update.message.document.file_name, True),)
for filename, convert in FILES:
metadata = {'title': filename}
res = DRIVE.files().insert(convert=convert, body=metadata,
media_body=filename, fields='mimeType,exportLinks').execute()
if res:
print('Uploaded "%s" (%s)' % (filename, res['mimeType']))
# silentremove(filename) #if u want to remove upladed file from local
update.message.reply_text("Uploaded!")