]> git.cworth.org Git - turbot/blob - turbot/sheets.py
Set the name of newly-created sheets to match the channel name
[turbot] / turbot / sheets.py
1 from flask import current_app
2 import pickle
3 import os.path
4 import os
5
6 from googleapiclient.discovery import build
7
8 # If modifying these scopes, delete the file token.pickle.
9 SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
10
11 turbot_deploy_dir = os.environ.get('TURBOT_DEPLOY_DIR', '.')
12 TOKEN_FILE = "{}/.gsheets-token.pickle".format(turbot_deploy_dir)
13
14 creds = None
15
16 def sheets_create(name):
17     """Create a new sheet with the given name.
18
19     Returns the URL for the spreadsheet.
20     """
21     global creds
22
23     # The file token.pickle stores token from last login/refresh
24     if not creds:
25         if os.path.exists(TOKEN_FILE):
26             with open(TOKEN_FILE, 'rb') as token:
27                 creds = pickle.load(token)
28
29     # If there are no (valid) credentials available, give up
30     if not creds or not creds.valid:
31         current_app.logger.error("No token found in {}".format(TOKEN_FILE))
32         current_app.logger.error("Try running ./gsheets-authenticate.py")
33         return None
34
35     service = build('sheets', 'v4', credentials=creds)
36
37     # Create a new sheet
38     spreadsheet_body = {
39         'properties': {
40             'title': name
41         }
42     }
43
44     request = service.spreadsheets().create(body=spreadsheet_body)
45     response = request.execute()
46
47     return response["spreadsheetUrl"]