You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python 3将Telegram Bot对接Google Drive实现文件权限共享

对接Google Drive的Telegram Bot开发记录

我正在学习Python,想要开发一款可对接Google Drive的Telegram Bot,Bot的运行逻辑如下:

  • 步骤1:Telegram用户在聊天窗口点击按钮(或链接),选择想要获取读取权限的文件
  • 步骤2:Bot向用户索要Google邮箱地址,并校验Gmail地址的合法性
  • 步骤3:Bot连接我的Google Drive,为用户提供的Gmail地址授予所选文件的读取权限
  • 步骤4:最终Bot在聊天窗口向用户返回对应的文件访问链接

初始问题

我查阅了相关开发指南,但代码仍无法正常运行,出现如Authorization Error 400: redirect_uri_mismatch这类报错,或是凭据相关报错,我根据此前的报错提示已经正确填写了凭据,希望得到可运行的示例和需要阅读的相关文档参考。

更新1(2021-10-19)

我已经通过以下代码实现了步骤1的功能:

from telegram import (
    Update,
    InlineKeyboardMarkup,
    InlineKeyboardButton,
)
from telegram.ext import (
    Updater,
    CallbackContext,
    CommandHandler,
    CallbackQueryHandler,
)


def startCommand(update: Update, context: CallbackContext) -> None:
    bot_reply = f'Howdy, {update.effective_user.first_name}.\nThis is the main menu.'
    update.message.bot.send_message(
        chat_id=update.effective_chat.id,
        text=bot_reply,
        reply_markup=menuMarkup01()
    )


def menuMarkup01():
    keyboardMarkup = [
        [InlineKeyboardButton('Share File 1', callback_data='gdriveTestButton')],
    ]
    return InlineKeyboardMarkup(keyboardMarkup)


def startCallbackHandler(update: Update, context: CallbackContext) -> None:
    query = update.callback_query

    if query.data == 'gdriveTestButton':
        query.edit_message_text(text='Sharing the File 1 with you.', reply_markup=InlineKeyboardMarkup([]))
        # Here the next function should be called that accepts
        # the user input if it's a valid gmail address or not,
        # and if it's not then the bot asks the user for a valid
        # gmail address again.

bot_token = '1234abcd'
updater = Updater(bot_token, use_context=True)

disp = updater.dispatcher
disp.add_handler(CommandHandler(command='start', callback=startCommand))
disp.add_handler(CallbackQueryHandler(startCallbackHandler))

updater.start_polling(drop_pending_updates=True)
updater.idle()

更新2(2021-10-19)

步骤3已经通过以下代码实现(需和步骤1的代码合并使用):

from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials


def gdriveShare(update: Update, context: CallbackContext) -> None:
    if context.args:
        # I took the json file from my Google Cloud Platform (GCP) → IAM & Admin → Service Accounts:
        service_key_file = 'service_key.json'
        scope = 'https://www.googleapis.com/auth/drive'
        credentials = ServiceAccountCredentials.from_json_keyfile_name(service_key_file, scopes=scope)

        driveV3 = build('drive', 'v3', credentials=credentials)
        fileId = '1ZP1xZ0WaH8w2yaQTSx99gafNZWawQabcdVW5DSngavQ'  # My xlsx-file.
        permDict = driveV3.permissions().list(fileId=fileId, fields='permissions').execute()

        newGmailUser = context.args[0]
        permList = permDict['permissions']
        usersList = []
        # Creating a list of the current gmail addresses that already has access to the file:
        for i in range(len(permList)):
            usersList.append(permList[i].get('emailAddress'))
        if newGmailUser not in usersList:
            permNewBody = {
                'role': 'reader',
                'type': 'user',
                'emailAddress': newGmailUser,
            }
            driveV3.permissions().create(fileId=fileId, body=permNewBody).execute()
            bot_reply = f"""The file is now shared with this user:
{newGmailUser}\n
See the file here:
https://docs.google.com/spreadsheets/d/1ZP1xZ0WaH8w2yaQTSx99gafNZWawQabcdVW5DSngavQ
"""
            update.message.bot.send_message(chat_id=update.effective_chat.id, text=bot_reply)
        else:
            bot_reply = f'The user {newGmailUser} already has access to the file.'
            update.message.bot.send_message(chat_id=update.effective_chat.id, text=bot_reply)
    else:
        bot_reply = f"""Please, provide a gmail address after the command.
Example:
/share testtest@gmail.com"""
        update.message.bot.send_message(chat_id=update.effective_chat.id, text=bot_reply)

# Here the bot takes the gmail address as the "context" argument after
# the command "/share". Example:
# /share testtest@gmail.com
disp.add_handler(CommandHandler("share", gdriveShare))

更新3(2021-10-20)

步骤2和步骤4的实现可参考Telegram Bot会话处理器触发相关开发内容,目前我的Bot逻辑已经全部开发完成。


内容的提问来源于stack exchange,提问作者Serge-M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 16:54:02