I want to built a questionnaire line chatbot and transmit the answer to google sheet. Here is my code: ''' import os
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()
''' I push it in heroku, but I get
2021-08-10T06:00:56.303548+00:00 app[web.1]: gspread.exceptions.APIError: {'code': 403, 'message': 'Google Sheets API has not been used in project 10137149515 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/sheets.googleapis.com/overview?project=10137149515 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.', 'status': 'PERMISSION_DENIED', 'details': [{'@type': 'type.googleapis.com/google.rpc.Help', 'links': [{'description': 'Google developers console API activation', 'url': 'https://console.developers.google.com/apis/api/sheets.googleapis.com/overview?project=10137149515'}]}, {'@type': 'type.googleapis.com/google.rpc.ErrorInfo', 'reason': 'SERVICE_DISABLED', 'domain': 'googleapis.com', 'metadata': {'consumer': 'projects/10137149515', 'service': 'sheets.googleapis.com'}}]} 2021-08-10T06:00:56.304235+00:00 app[web.1]: 10.1.7.41 - - [10/Aug/2021:14:00:56 +0800] "POST /callback HTTP/1.1" 500 290 "-" "LineBotWebhook/2.0"
Please help and tell me what's wrong. THX
Google Sheets API has not been used in project 10137149515 before or it is disabled. Enable it by visiting
This is a settings issue in your Google cloud console account if you follow the link to your project When you set up your project you need to tell google which APIs you intend to use you have forgotten to add that you will be using the Google sheets api.
Go to library on the left
In the search bar search for Google sheets api and select it then click enable
It should only take a few minutes then run your code again.