gcal.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. from __future__ import print_function
  2. import httplib2
  3. import os
  4. from apiclient import discovery
  5. import oauth2client
  6. from oauth2client import client
  7. from oauth2client import tools
  8. import datetime
  9. try:
  10. import argparse
  11. flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
  12. except ImportError:
  13. flags = None
  14. # If modifying these scopes, delete your previously saved credentials
  15. # at ~/.credentials/calendar-python-quickstart.json
  16. SCOPES = 'https://www.googleapis.com/auth/calendar.readonly'
  17. CLIENT_SECRET_FILE = 'client_secret.json'
  18. APPLICATION_NAME = 'Google Calendar API Python Quickstart'
  19. def get_credentials():
  20. """Gets valid user credentials from storage.
  21. If nothing has been stored, or if the stored credentials are invalid,
  22. the OAuth2 flow is completed to obtain the new credentials.
  23. Returns:
  24. Credentials, the obtained credential.
  25. """
  26. home_dir = os.path.expanduser('~')
  27. credential_dir = os.path.join(home_dir, '.credentials')
  28. if not os.path.exists(credential_dir):
  29. os.makedirs(credential_dir)
  30. credential_path = os.path.join(credential_dir,
  31. 'calendar-python-quickstart.json')
  32. store = oauth2client.file.Storage(credential_path)
  33. credentials = store.get()
  34. if not credentials or credentials.invalid:
  35. flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
  36. flow.user_agent = APPLICATION_NAME
  37. if flags:
  38. credentials = tools.run_flow(flow, store, flags)
  39. else: # Needed only for compatibility with Python 2.6
  40. credentials = tools.run(flow, store)
  41. print('Storing credentials to ' + credential_path)
  42. return credentials
  43. def main():
  44. """Shows basic usage of the Google Calendar API.
  45. Creates a Google Calendar API service object and outputs a list of the next
  46. 10 events on the user's calendar.
  47. """
  48. credentials = get_credentials()
  49. http = credentials.authorize(httplib2.Http())
  50. service = discovery.build('calendar', 'v3', http=http)
  51. now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
  52. print('Getting the upcoming 10 events')
  53. eventsResult = service.events().list(
  54. calendarId='primary', timeMin=now, maxResults=10, singleEvents=True,
  55. orderBy='startTime').execute()
  56. events = eventsResult.get('items', [])
  57. if not events:
  58. print('No upcoming events found.')
  59. i=0
  60. for event in events:
  61. i = i + 1
  62. print('The event #', i,'------------------------')
  63. start = event['start'].get('dateTime', event['start'].get('date'))
  64. #status : confirmed or not
  65. print(' Status:', event['status'])
  66. #htmlLink: the url of the event
  67. print(' HtmlLink:', event['htmlLink'])
  68. #created: the created time of the event
  69. print(' Created time:', event['created'])
  70. #updateed: the updated time of the event
  71. print(' Updatedtime:', event['updated'])
  72. #summary: the description of the event
  73. if ('description' in event):
  74. print(' Description:', event['description'])
  75. if ('location' in event):
  76. print(' Location:', event['location'])
  77. print(" Organizer's name:", event['organizer'].get('displayName', 'unknown'))
  78. print(" Organizer's email:", event['organizer']['email'])
  79. print(" Start time:", event['start']['dateTime'])
  80. #print(start, event['summary']);
  81. if __name__ == '__main__':
  82. main()