iT邦幫忙

0

linebot 與 google sheet 鏈結的問題 (環境:python,heroku)

各位高手好,最近有個需求,就是將google sheet視為一個資料庫,然後製作一個問答機器人,從line發送訊息後,在google sheet資料庫裡找問題,然後回應相對應的答案,網路爬了文,找到了這篇https://medium.com/@ctosib/linebot-with-google-api-2dd720f93ded

def gettotal():

apikey={Youe API KEY}
getvalueurl='https://sheets.googleapis.com/v4/spreadsheets/{Your sheet ID}/values/sheet1!A:C?key=%s' % (apikey)
res = requests.get(getvalueurl)
data = res.content
jsondata = json.loads(data)
values = jsondata['values']

請問1
values = jsondata['values']後面的'values'是指sheet裡面的values欄位嗎?
之前有看到另外一篇教學有使用到foreach ($data['feed']['entry'] as $item)
這裡也需要做這個判斷嗎?

請問2
如何取得apikey?

感謝各位高手

黃彥儒 iT邦高手 1 級 ‧ 2018-10-10 14:33:40 檢舉
為什麼你不看看他的API文件~?
而是跑去看教學
抱歉 我是新手 正在努力學習中 只能從茫茫大海中找資訊 請問API文件是指?
陳小熊 iT邦新手 4 級 ‧ 2018-10-11 11:38:07 檢舉
https://developers.google.com/sheets/api/reference/rest/ 這個就是API文件喔(通常都很落落長...)
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
陳小熊
iT邦新手 4 級 ‧ 2018-10-10 16:11:37

問題1-[values = jsondata['values']後面的'values'是指sheet裡面的values欄位嗎?]的回答:
參考API簡介,回傳的response格式如下:

{
  "range": string(選擇的sheet range,格式類似 *Class Data!A2:E* ),
  "majorDimension": enum(Dimension)(以列ROWS為主或是以欄位COLUMNS 為主,沒設定的話預設是ROWS ),
  "values": [
    array(讀取到的資料,是sheet的values沒錯,假設您的Range設定A-E,會回傳A-E Column的資料)
  ]
}

不太清楚您說的['feed']['entry']的意思,想請問另一篇文章的連結.
但我們倒是可以針對values做以下判斷

    # 如果沒有資料的話,回傳沒資料,有資料的話印各欄位出來
    if not values:
        print('No data found.')
    else:
        print('Name, Major:')
        for row in values:
            # Print columns A and E, which correspond to indices 0 and 4.
            print('%s, %s' % (row[0], row[4]))

API Response的參考文件:https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values

問題2-[如何取得API KEY]的回答:

參考以下順序操作
https://ithelp.ithome.com.tw/upload/images/20181010/20111777kVsShFxfMG.png

https://ithelp.ithome.com.tw/upload/images/20181010/20111777CJ3eeWZ244.png

連結如下
https://developers.google.com/sheets/api/quickstart/python

補充(黑客松愛好者陳小熊)另一篇文章連結:https://superlevin.tw/%E4%BD%BF%E7%94%A8azurephpgoogle%E8%A9%A6%E7%AE%97%E8%A1%A8%E5%BB%BA%E7%BD%AEline%E5%9B%9E%E6%87%89%E6%A9%9F%E5%99%A8%E4%BA%BA/

另外想請問,如果print('%s, %s' % (row[0], row[4]))是只列出欄位的values,如果要做相對應values可以怎麼做呢?

例如:
https://i.imgur.com/oDVWfep.png

input是:甲-1,則output:a
input是:丙-2,則output:i
...以此類推

我要發表回答

立即登入回答