Skip to content

Instantly share code, notes, and snippets.

@jgsogo
Last active February 9, 2019 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgsogo/0256203d7929142ec8eb2d853430f032 to your computer and use it in GitHub Desktop.
Save jgsogo/0256203d7929142ec8eb2d853430f032 to your computer and use it in GitHub Desktop.
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from datetime import datetime
import random
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = "1_ickKJa7tkJeA6uDfi8kIdOoUYHq6s-cJCiws_pp8W4"
SAMPLE_RANGE_NAME = 'Respuestas de formulario 1!D2:D'
def main():
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server()
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('sheets', 'v4', credentials=creds)
# Call the Sheets API
sheet = service.spreadsheets().get(spreadsheetId=SAMPLE_SPREADSHEET_ID).execute()
print(sheet['properties']['title'])
result = service.spreadsheets().values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
range=SAMPLE_RANGE_NAME).execute()
values = result.get('values', [])
if not values:
print('No data found :/')
else:
print("\tIt looks like there is people interested, great!")
print("\tChoose one random (use twitter handle)")
print("\tDatetime: {}".format(datetime.now().isoformat()))
print("\tThe winner is...\n")
tw_handles = [r[0].strip('@') for r in values]
winner = random.choice(tw_handles)
print("\tπŸŽ‰πŸŽ‰πŸŽ‰πŸŽ‰πŸŽ‰πŸŽ‰πŸŽ‰")
print("\tπŸŽ‰πŸŽ‰ @{}".format(winner))
print("\tπŸŽ‰πŸŽ‰πŸŽ‰πŸŽ‰πŸŽ‰πŸŽ‰πŸŽ‰")
print("Congratulations!")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment