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