def announcement_list(url, data, tracker): try: text = "" res = api_reader(url, httpmethod="post", data=data, tracker=tracker) logger.success(f"api call on url {url} done sucessfully") if not res["content"]: return res["content"] for i, p in enumerate(res["content"]): title = str(p["title"]) message = str(p["message"]) epochtime = p["publishedDate"] published_date = time.localtime(epochtime / 1000) published_date = datetime.fromtimestamp(mktime(published_date)) published_date = published_date + timedelta(hours=5, minutes=45) published_date = published_date.strftime("%m/%d/%Y, %H:%M") text = text + announcement_template.format( title=title, message=message, published_date=published_date ) if i == 4: break return "**Your recent announcements are:** \n\n" + text except Exception as e: logger.exception(f"Parsing of API resuts failed") return None
async def _get_recommendation(self, query, courses): data = {"query": query, "courses": courses} # auth = ("fuseclassroom-dev", "M!jDwkTEa3KZ") auth = ( "{}".format(env["actions"]["action_search_resource"]["user_name"]), "{}".format(env["actions"]["action_search_resource"]["password"]), ) headers = {"Content-Type": "application/json"} url = ("{}".format(env["actions"]["action_search_resource"]["url"]) + "api/search/query") try: recommendations = requests.post(url, auth=auth, headers=headers, json=data) recommendation = recommendations.json() if not recommendation: return [] res = [] for _, p in enumerate(recommendation): a, b = p.get("title"), p.get("url") res.append((a, b)) logger.success(f"api call on url {url} done sucessfully") return res except Exception as e: logger.exception( f"Api call on url {url} Failed ErrorMessage: {e}") return None
async def run( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> List[Dict[Text, Any]]: logger.success("on search resources through nlu action") if (len(tracker.events) >= 4 and tracker.events[-4].get("name") == "action_ask_affirmation"): query = tracker.events[-5].get("text") else: query = tracker.latest_message["text"].split(" ", 1)[1] dispatcher.utter_message( text="Searching resources, please wait...😊!") courses = object_list("courseId", tracker) res = await self._get_recommendation(query, courses) if not res: dispatcher.utter_message( "I couldn't find any resources that maybe helpful to you.") return [ SlotSet("data", None), FollowupAction("action_bottom_top_menu"), ] if res is None: dispatcher.utter_message( "I couldn't find any resources.Something must be wrong.🤔 Check again later, sorry." ) return [ SlotSet("data", None), FollowupAction("action_bottom_top_menu"), ] dispatcher.utter_message( "You might find the following link helpful: \n") for i, (title, url) in enumerate(res): buttons_list = [] if url and title: payload = f"{url}" payload = json.dumps(payload) buttons_list.append({ "title": title, "payload": f"{payload}/link" }) if i == 3: break dispatcher.utter_message(text="", buttons=buttons_list) return [ SlotSet("data", None), FollowupAction("action_bottom_top_menu"), ] return [ SlotSet("data", None), FollowupAction("action_bottom_top_menu"), ]
def teacher_info(url, params, attribute, tracker): if attribute is None: return None try: res = api_reader(url, params=params, tracker=tracker) logger.success(f"api call on url {url} done sucessfully") for p in res: return p.get(attribute) except Exception as e: logger.exception(f"Api call on url {url} Failed") return None
def school_info(url, attribute, tracker): if attribute is None: return None try: res = api_reader(url, tracker=tracker) logger.success( f"api call on url {url} done sucessfully for school info" ) return res.get(attribute) except Exception as e: logger.exception(f"Api call on url {url} Failed") return None
async def run( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> List[Dict[Text, Any]]: logger.success("on search resources action") data = tracker.get_slot("data") query = data dispatcher.utter_message( text="Searching resources, please wait...😊!") courses = [tracker.get_slot("course_id")] res = await self._get_recommendation(query, courses) if not res: dispatcher.utter_message( "I couldn't find any resources that maybe helpful to you.") return [ SlotSet("data", None), FollowupAction("action_bottom_top_menu"), ] if res is None: dispatcher.utter_message( "I couldn't find any resources.Something must be wrong.🤔 Check again later, sorry." ) return [ SlotSet("data", None), FollowupAction("action_bottom_top_menu"), ] dispatcher.utter_message( "You might find the following link helpful: \n") for i, (title, url) in enumerate(res): buttons_list = [] if url and title: payload = f"{url}" payload = json.dumps(payload) buttons_list.append({ "title": title, "payload": f"{payload}/link" }) if i == 3: break dispatcher.utter_message(text="", buttons=buttons_list) return [ SlotSet("data", None), FollowupAction("action_bottom_top_menu"), ]
def api_reader(url, params=None, httpmethod="get", data=None, tracker=None): headers = extract_headers_from_tracker(tracker) fullurl = extract_url_from_tracker(tracker) + "/" + url try: if httpmethod == "get": response = requests.get(fullurl, params=params, headers=headers) else: response = requests.post(fullurl, headers=headers, json=data) logger.success( f"api call on fullurl {response.request.url} done sucessfully" ) return response.json() except Exception as e: logger.error(f"Api call on url {fullurl} Failed")
def grade_list(url, tracker): text = "" try: res = api_reader(url, tracker=tracker) logger.success(f"api call on url {url} done sucessfully") if not res: return res for p in res[0]["academicCourses"]: course = str(p["courseName"]) gpa = str(p["courseGpa"]) text = text + grade_template.format(course=course, gpa=gpa) return "**These are your grades:** \n\n" + text except Exception as e: logger.exception(f"Parsing of API resuts failed") return None
def quiz_list(url, params, tracker, context): text = "" try: res = api_reader(url, params, tracker=tracker) logger.success(f"api call on url {url} done sucessfully") if not res["content"]: return res["content"] for i, p in enumerate(res["content"]): title = str(p["quizTitle"]) description = str(p["quizDescription"]) score = str(p["fullScore"]) if p["obtainedScore"] and str(p["obtainedScore"]) != "null": obtained_score = str(format(p["obtainedScore"], ".2f")) else: obtained_score = "Not Available" text = text + quiz_template.format( obtained_score=obtained_score, title=title, description=description, score=score, ) if i == 4: break if context == "help_not_attempted_quiz": text = "**Not attempted quizzes are: ** \n\n " + text elif context == "help_passed_quiz": text = "**Passed quizzes are: ** \n\n " + text else: text = "**Failed quizzes are: ** \n\n " + text return text except Exception as e: logger.exception(f"Parsing of API resuts failed") return None