如何修复:项目中未使用 Google Sheets API

2024-03-27

我想建立一个问卷调查线聊天机器人并将答案传输到谷歌表。 这是我的代码: ''' 导入操作系统

from flask import Flask, request, abort

from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage,
)
from oauth2client.service_account import ServiceAccountCredentials 
import gspread
from datetime import datetime, date, timedelta, time
import time


gsp_scopes = ['https://spreadsheets.google.com/feeds']

SPREAD_SHEETS_KEY = os.environ.get('SPREAD_SHEETS_KEY')
credential_file_path = 'credentials.json'
def auth_gsp_client(file_path, scopes):
    credentials = ServiceAccountCredentials.from_json_keyfile_name(file_path, scopes)
    return gspread.authorize(credentials)

def records(A, B, C, D, E):
    gsp_client = auth_gsp_client(credential_file_path, gsp_scopes)
    worksheet = gsp_client.open_by_key(SPREAD_SHEETS_KEY).sheet1
    worksheet.insert_row([A, B, C, D, E], 2)
    return True

app = Flask(__name__)

LINE_CHANNEL_ACCESS_TOKEN = os.environ.get('LINE_CHANNEL_ACCESS_TOKEN')
LINE_CHANNEL_SECRET = os.environ.get('LINE_CHANNEL_SECRET')
line_bot_api = LineBotApi(LINE_CHANNEL_ACCESS_TOKEN)
handler = WebhookHandler(LINE_CHANNEL_SECRET)

@app.route("/", methods=['GET'])
def hello():
    return 'hello heroku'

@app.route("/callback", methods=['POST'])
def callback():
    signature = request.headers['X-Line-Signature']

    body = request.get_data(as_text=True)

    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        print("Invalid signature. Please check your channel access token/channel secret.")
        abort(400)

    return 'OK'

user_command_dict = {}

@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    user_message = event.message.text
    user_id = event.source.user_id

    user_command = user_command_dict.get(user_id)

    if user_message == '@問卷' and user_command == None:
        print(user_message)
        reply_message = [
            TextSendMessage(text='這是問卷'),
            TextSendMessage(text='B'),
            TextSendMessage(text='開始')
            ]
        user_command_dict[user_id] = '@問卷1'
    if user_command == '@問卷1':
        answer = user_message
        if answer=='yes':
            time.sleep(3)
            reply_message=TextSendMessage(text='問題一')
            user_command_dict[user_id] = '@問卷2'
    if user_command == '@問卷2':
        global answer1
        answer1 = user_message
        time.sleep(3)
        reply_message=TextSendMessage(text='問題二')
        user_command_dict[user_id] = '@問卷3'
    if user_command == '@問卷3':
        global answer2
        answer2 = user_message
        time.sleep(3)
        reply_message=TextSendMessage(text='問題三')
        user_command_dict[user_id] = '@問卷4'
    if user_command == '@問卷4':
        global answer3
        answer3 = user_message
        Date = date.today()
        today=Date.strftime("%Y/%b/%d")
        time.sleep(3)
        
        print(today, answer1, answer2, answer3)
        reply_message=TextSendMessage(text='問題結束')
        records(today, user_id, answer1, answer2, answer3)
        user_command_dict[user_id] = None
    #else:
        #print(user_message)
        #reply_message=TextSendMessage(text=event.message.text)

    line_bot_api.reply_message(
        event.reply_token,
        reply_message)

if __name__ == "__main__":
    app.run()

''' 我把它推入heroku,但我得到了

2021-08-10T06:00:56.303548+00:00 app[web.1]: gspread.exceptions.APIError: {'code': 403, 'message': 'Google Sheets API 之前尚未在项目 10137149515 中使用过它已被禁用。通过访问启用它https://console.developers.google.com/apis/api/sheets.googleapis.com/overview?project=10137149515 https://console.developers.google.com/apis/api/sheets.googleapis.com/overview?project=10137149515然后重试。如果您最近启用了此 API,请等待几分钟,以便该操作传播到我们的系统,然后重试。', 'status': 'PERMISSION_DENIED', 'details': [{'@type': 'type.googleapis.com/ google.rpc.Help', 'links': [{'description': 'Google 开发者控制台 API 激活', 'url': 'https://console.developers.google.com/apis/api/sheets.googleapis. com/overview?project=10137149515'}]}, {'@type': 'type.googleapis.com/google.rpc.ErrorInfo', '原因': 'SERVICE_DISABLED', '域': 'googleapis.com', '元数据':{'消费者':'projects/10137149515','服务':'sheets.googleapis.com'}}]} 2021-08-10T06:00:56.304235 + 00:00应用程序[web.1]:10.1.7.41 - - [10/8月/2021:14:00:56 +0800]“POST /回调HTTP/1.1”500 290 “-”“LineBotWebhook/2.0”

请帮助并告诉我出了什么问题。谢谢


Google Sheets API 之前未曾在项目 10137149515 中使用或被禁用。通过访问启用它

如果您按照链接访问您的 Google 云控制台帐户,则这是您的 Google 云控制台帐户中的设置问题project https://console.developers.google.com/apis/api/sheets.googleapis.com/overview?project=10137149515当您设置项目时,您需要告诉 Google 您打算使用哪些 API,但您忘记添加您将使用 Google Sheets API。

启用谷歌表格API

去左边的图书馆

在搜索栏中搜索 Google Sheets api 并选择它,然后单击启用

再次运行代码应该只需要几分钟。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何修复:项目中未使用 Google Sheets API 的相关文章

随机推荐