From 40417383f0f517727044fb4aab55c91927422e30 Mon Sep 17 00:00:00 2001 From: daJu Date: Fri, 19 Jun 2020 01:32:13 +0200 Subject: [PATCH] [somebot] /raumsuche --- somebot/modules/CommandRaumsuche.py | 167 ++++++++++++++++++++++++++++ 1 file changed, 167 insertions(+) create mode 100644 somebot/modules/CommandRaumsuche.py diff --git a/somebot/modules/CommandRaumsuche.py b/somebot/modules/CommandRaumsuche.py new file mode 100644 index 0000000..8d9909d --- /dev/null +++ b/somebot/modules/CommandRaumsuche.py @@ -0,0 +1,167 @@ +# Mattermost APIv4 Bot. +# written 2019 by Ju + +import mwclient +import pprint +import sys +import re + + +from AbstractCommand import * +class CommandRaumsuche(AbstractCommand): + TRIGGER = "raumsuche" + CONFIG = {"display_name": "somebot-command", "auto_complete": True, + "auto_complete_hint": "Name", + } + USEINFO = CONFIG["auto_complete_desc"] = CONFIG["description"] = "Tries to find the room with given name." + + # maximum results/rooms listed + MAX_RESULTS = 10 + # path to wiki + WIKI_URL = "wiki.fsinf.at" + # link to page with all rooms + WIKI_URL_ROOMS = "https://wiki.fsinf.at/wiki/Kategorie:Raumcode" + # wiki-login (optional) + #MWS_USER = "USER" + #MWS_PASS = "PASSWORD" + # osm - experimental - uncomment to deactivate + OSM_URL = "https://www.openstreetmap.org/search?query=" + # OSWM link with coordinates - uncomment to deactivate + OSM_COORDINATES = "https://www.openstreetmap.org/?" + # feedback to: + FEEDBACK = "\n\nFeedback zu diesem Feature bitte an **[@​ju](https://mattermost.fsinf.at/fsinf-intern/messages/@ju)** =^.^=" + # Help-Text + HELP_TEXT = "Folgende Tipps können dir bei der Suche helfen:\n" + HELP_TEXT += "\n" + HELP_TEXT += "+ die Suche ist nicht case sensitiv\n" + HELP_TEXT += "+ Verwende 'EI 7' statt 'EI7'\n" + HELP_TEXT += "+ sollte ein Raum nicht eingetragen sein, oder der Suchbegriff nicht passen, schau auf [diese Seite](https://wiki.fsinf.at/wiki/Raum:Hauptseite) und trage ihn nach. Das Wiki lebt von eurer Hilfe." + HELP_TEXT += FEEDBACK + + + def __init__(self, team_id, mw_user=None, mw_user_pw=None): + super().__init__(team_id) + self.mw_user = mw_user + self.mw_user_pw = mw_user_pw + + + def on_POST(self, request, data): + msg = "" + + if data["text"].strip() != "" and data["text"].replace("--chan ", "").strip() != "": + if data["text"].startswith("--chan "): + msg = self.roomSearch(data["text"].replace("--chan ", "")) + request.cmd_respond_text_chan(msg) + return True + else: + msg = self.roomSearch(data["text"]) + request.cmd_respond_text_temp(msg) + return True + else: + request.cmd_respond_text_temp("Du hast vergessen einen Raumnamen anzugeben.\n\n" + self.HELP_TEXT) + return True + + + def roomSearch(self, searchTerm): + searchTerm = searchTerm.strip() + if searchTerm == "help" or searchTerm == "?": + return self.HELP_TEXT + + # a try to prevent injections + searchTerm = re.sub("[^\w]+", " ", searchTerm) + searchTerm = searchTerm.replace(" ", " ").strip() + + # space to * for matching "HS 11" to "HS 11" and "HS11" + searchTerm = searchTerm.replace(" ", "*") + query="[[Category:Raumcode]]|[[RoomName::~*" + searchTerm + "*]] OR [[SearchValue::~*" + searchTerm + "*]] OR [[RoomCode::~*" + searchTerm + "*]]|?RoomName|?Address|?RoomCode|?Longitude|?Latitude" + result = "Du hast nach **`" + searchTerm + "`** gesucht." + + # check if service is available, if so execute query + try: + mws = mwclient.Site(self.WIKI_URL, path="/", retry_timeout=120) + except Exception: + return "Der Service ist gerade nicht verfügbar (zB keine Verbindung zum wiki)." + + #use user + pass for wiki connection if it is set + if self.mw_user and self.mw_user_pw: + mws.login(self.mw_user, self.mw_user_pw) + # TODO: wrong credentials behandeln + + + query_result = mws.ask(query) + + # no results + # https://stackoverflow.com/a/21525143 + _exhausted = object() + if next(query_result, _exhausted) == _exhausted: + return result + " Leider konnten keine Ergebnisse gefunden werden.\n\n" + self.HELP_TEXT + + result += " Folgende Räume wurden gefunden:\n" + # get items again, because they get consumed in the isEmpty + query_result = mws.ask(query) + # results present + counter = 0 + for p in query_result: + if counter < self.MAX_RESULTS: +# pprint.pprint(p) + # check if values are present + if len(next(iter(p.values()))["printouts"]["RoomCode"]) > 0: + roomCode = next(iter(p.values()))["printouts"]["RoomCode"][0] + else: + roomCode = "" + if len(next(iter(p.values()))["printouts"]["RoomName"]) > 0: + roomName = next(iter(p.values()))["printouts"]["RoomName"][0] + else: + roomName = "" + if len(next(iter(p.values()))["printouts"]["Address"]) > 0: + address = next(iter(p.values()))["printouts"]["Address"][0] + else: + address = "" + if len(next(iter(p.values()))["printouts"]["Longitude"]) > 0: + longitude = next(iter(p.values()))["printouts"]["Longitude"][0]["fulltext"] + else: + longitude = "" + if len(next(iter(p.values()))["printouts"]["Latitude"]) > 0: + latitude = next(iter(p.values()))["printouts"]["Latitude"][0]["fulltext"] + else: + latitude = "" + + url = next(iter(p.values()))["fullurl"] + + result += "\n+ [" + roomCode + "](" + url + "), **" + roomName + "** findest du hier: " + + # Address - Part + # priority over "OSM_URL": + if "OSM_COORDINATES" in dir(self) and len(latitude) > 0 and len(longitude) > 0: + # mlat={{{latitude}}}&mlon={{{longitude}}}#map=19/{{{latitude}}}/{{{longitude}}} + osm_query = "mlat=" + latitude + "&mlon=" + longitude + "#map=19/" + latitude + "/" + longitude + result += "[" + address + "](" + self.OSM_COORDINATES + osm_query + " \"link to open street maps\")" + # link without coordinates: + elif "OSM_URL" in dir(self): + # case format "1040 Wien, Favoritenstraße 9; durch Gittertor und Hof zu Stiege II; ins 2. OG; vom Lift aus rechts;" + if "wien" in address.split(",")[0].lower(): + osm_query = "wien%20" + address.split(";")[0].split(",")[1] + # case format "Floragasse 7, 2. Stock" + else: + osm_query = "wien%20" + address.split(",")[0] + # transforms space to %20 + osm_query = osm_query.replace(" ", "%20") + # transforms street number "22-25" to "22" + osm_query = re.sub(r"-\d+", r"", osm_query) + + result += "[" + address + "](" + self.OSM_URL + osm_query + ")" + # else print plain address + else: + result += address + counter += 1 + else: + break + + result += "\n\nSollte der Raum nicht dabei sein, kannst du ihn unter [Wiki-Räume](" + self.WIKI_URL_ROOMS + ") nachtragen bzw. einen Suchbegriff hinzufügen." + self.FEEDBACK + return result + + + +if __name__ == "__main__": + a = CommandRaumsuche("asdf") + print(a.roomSearch(sys.argv[1])) -- 2.43.0