代码之家  ›  专栏  ›  技术社区  ›  Sumithran

如何使用python电报bot api将文件上传到google drive

  •  1
  • Sumithran  · 技术社区  · 6 年前

    我正在尝试将用户发送到我的bot的文件上传到谷歌驱动器。
    这是我的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部分)。
    但我怎么能把这些文件上传到谷歌硬盘…

    事先谢谢!

    1 回复  |  直到 6 年前
        1
  •  0
  •   Sumithran    6 年前

    将两种方法结合在一起,很容易将文件从电报上传到Google Drive。 google-drive-api telegram-bot-api .

    下面是描述代码如何工作的流程图。

    Bo.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 integration example