Как загрузить файл на диск Google с помощью Python Telegram Bot API - PullRequest
0 голосов
/ 23 декабря 2018

Я пытаюсь загрузить файл, отправленный пользователем на мой бот, на диск 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()

По этому коду я могу загружать файлы, загруженныепользователи для бота (без части google-api).
Но как я могу загрузить эти файлы на google drive ...

Заранее спасибо!

1 Ответ

0 голосов
/ 30 декабря 2018

Загрузить файлы из Telegram на Google Drive очень просто, сочетая google-drive-api и telegram-bot-api.

Вот блок-схема, показывающая, как работает код.

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!")

Telegram bot Google Drive APIпример интеграции

...