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