· 4 years ago · Jun 15, 2021, 07:10 AM
1###############################################################
2# This program:
3# - Asks the user to enter an access token or use the hard coded access token.
4# - Lists the user's Webex Teams rooms.
5# - Asks the user which Webex Teams room to monitor for "/location" requests.
6# - Monitors the selected Webex Team room every second for "/location" messages.
7# - Discovers GPS coordinates for the "location" using MapQuest API.
8# - Discovers the date and time of the next ISS flyover over the "location" using the ISS API
9# - Formats and sends the results back to the Webex Team room.
10#
11# The student will:
12# 1. Import libraries for API requests, JSON formatting, and epoch time conversion.
13# 2. Complete the if statement to ask the user for the Webex access token.
14# 3. Provide the URL to the Webex Teams room API.
15# 4. Create a loop to print the type and title of each room.
16# 5. Provide the URL to the Webex Teams messages API.
17# 6. Provide your MapQuest API consumer key.
18# 7. Provide the URL to the MapQuest address API.
19# 8. Provide the MapQuest key values for latitude and longitude.
20# 9. Provide the URL to the ISS pass times API.
21# 10. Provide the ISS key values risetime and duration.
22# 11. Convert the risetime epoch value to a human readable date and time.
23# 12. Complete the code to format the response message.
24# 13. Complete the code to post the message to the Webex Teams room.
25###############################################################
26
27# 1. Import libraries for API requests, JSON formatting, and epoch time conversion.
28import json
29import requests
30import time
31
32# 2. Complete the if statement to ask the user for the Webex access token.
33choice = input("Do you wish to use the hard-coded Webex token? (y/n) ")
34
35if choice == 'y':
36 token = input("Your Webex Teams Access Token? ")
37 accessToken = "Bearer {}".format(token)
38else:
39 accessToken = "Bearer NjQxZTUxZTEtNjQ5MC00YWNmLWE0YTYtODhhMTFmMDhjODY2N2I5MWZjZDYtNDBk_P0A1_9e2858ad-dbc7-45d0-8184-304acabb5516"
40
41# 3. Provide the URL to the Webex Teams room API.
42r = requests.get("https://webexapis.com/v1/rooms",
43 headers={"Authorization": accessToken}
44 )
45
46#####################################################################################
47# DO NOT EDIT ANY BLOCKS WITH r.status_code
48if not r.status_code == 200:
49 raise Exception("Incorrect reply from Webex Teams API. Status code: {}. Text: {}".format(r.status_code, r.text))
50######################################################################################
51
52# 4. Create a loop to print the type and title of each room.
53print("List of rooms:")
54rooms = r.json()["items"]
55# print(rooms)
56
57for room in rooms:
58 print(f'Room title: {room["title"]}, room type: {room["type"]}')
59
60#######################################################################################
61# SEARCH FOR WEBEX TEAMS ROOM TO MONITOR
62# - Searches for user-supplied room name.
63# - If found, print "found" message, else prints error.
64# - Stores values for later use by bot.
65# DO NOT EDIT CODE IN THIS BLOCK
66#######################################################################################
67
68while True:
69 roomNameToSearch = input("Which room should be monitored for /location messages? ")
70 roomIdToGetMessages = None
71
72 for room in rooms:
73 if (room["title"].find(roomNameToSearch) != -1):
74 print("Found rooms with the word " + roomNameToSearch)
75 print(room["title"])
76 roomIdToGetMessages = room["id"]
77 roomTitleToGetMessages = room["title"]
78 print("Found room : " + roomTitleToGetMessages)
79 break
80
81 if (roomIdToGetMessages == None):
82 print("Sorry, I didn't find any room with " + roomNameToSearch + " in it.")
83 print("Please try again...")
84 else:
85 break
86
87######################################################################################
88# WEBEX TEAMS BOT CODE
89# Starts Webex bot to listen for and respond to /location messages.
90######################################################################################
91
92while True:
93 time.sleep(1)
94 GetParameters = {
95 "roomId": roomIdToGetMessages,
96 "max": 1
97 }
98 # 5. Provide the URL to the Webex Teams messages API.
99 r = requests.get("https://webexapis.com/v1/messages",
100 params=GetParameters,
101 headers={"Authorization": accessToken}
102 )
103
104 if not r.status_code == 200:
105 raise Exception("Incorrect reply from Webex Teams API. Status code: {}. Text: {}".format(r.status_code, r.text))
106
107 json_data = r.json()
108 if len(json_data["items"]) == 0:
109 raise Exception("There are no messages in the room.")
110
111 messages = json_data["items"]
112 message = messages[0]["text"]
113 print("Received message: " + message)
114
115 if message.find("/") == 0:
116 location = message[1:]
117 # 6. Provide your MapQuest API consumer key.
118 mapsAPIGetParameters = {
119 "location": location,
120 "key": "yQTJquGPB1KKcqVCBepg4IpPsUviF9sp"
121 }
122 # 7. Provide the URL to the MapQuest address API.
123 r = requests.get("https://www.mapquestapi.com/geocoding/v1/address",
124 params=mapsAPIGetParameters
125 )
126 json_data = r.json()
127
128 if not json_data["info"]["statuscode"] == 0:
129 raise Exception("Incorrect reply from MapQuest API. Status code: {}".format(r.statuscode))
130
131 locationResults = json_data["results"][0]["providedLocation"]["location"]
132 print("Location: " + locationResults)
133
134 # 8. Provide the MapQuest key values for latitude and longitude.
135 locationLat = json_data["results"][0]["locations"][0]["latLng"]["lat"]
136 locationLng = json_data["results"][0]["locations"][0]["latLng"]["lng"]
137 print("Location GPS coordinates: " + str(locationLat) + ", " + str(locationLng))
138
139 issAPIGetParameters = {
140 "lat": locationLat,
141 "lon": locationLng
142 }
143 # 9. Provide the URL to the ISS pass times API.
144 r = requests.get("http://api.open-notify.org/iss/v1/",
145 params=issAPIGetParameters
146 )
147
148 json_data = r.json()
149
150 if not "response" in json_data:
151 raise Exception(
152 "Incorrect reply from open-notify.org API. Status code: {}. Text: {}".format(r.status_code, r.text))
153
154 # 10. Provide the ISS key values risetime and duration.
155 risetimeInEpochSeconds = json_data["response"][0]["risetime"]
156 durationInSeconds = json_data["response"][0]["duration"]
157
158 # 11. Convert the risetime epoch value to a human readable date and time.
159 risetimeInFormattedString = time.strftime('%a %b %d %H:%M:%S %Y', time.localtime(risetimeInEpochSeconds))
160
161 # 12. Complete the code to format the response message.
162 # Example responseMessage result: In Austin, Texas the ISS will fly over on Thu Jun 18 18:42:36 2020 for 242 seconds.
163 responseMessage = "In {} the ISS will fly over on {} for {} seconds.".format(locationResults,
164 risetimeInFormattedString,
165 durationInSeconds)
166 print("Sending to Webex Teams: " + responseMessage)
167
168 # 13. Complete the code to post the message to the Webex Teams room.
169 HTTPHeaders = {
170 "Authorization": accessToken,
171 "Content-Type": "application/json"
172 }
173 PostData = {
174 "roomId": roomIdToGetMessages,
175 "text": roomTitleToGetMessages
176 }
177
178 r = requests.post("https://webexapis.com/v1/messages",
179 data=json.dumps(PostData),
180 headers=HTTPHeaders
181 )
182 if not r.status_code == 200:
183 raise Exception(
184 "Incorrect reply from Webex Teams API. Status code: {}. Text: {}".format(r.status_code, r.text))
185