1 # Mattermost APIv4 Bot.
2 # written 2019 by Ju <daju@fsinf.at>
10 from AbstractCommand import AbstractCommand
11 class CommandRaumsuche(AbstractCommand):
13 CONFIG = {"display_name": "somebot-command", "auto_complete": True,
14 "auto_complete_hint": "Name",
16 USEINFO = CONFIG["auto_complete_desc"] = CONFIG["description"] = "Tries to find the room with given name."
18 # maximum results/rooms listed
21 WIKI_URL = "wiki.fsinf.at"
22 # link to page with all rooms
23 WIKI_URL_ROOMS = "https://wiki.fsinf.at/wiki/Kategorie:Raumcode"
24 # wiki-login (optional)
26 #MWS_PASS = "PASSWORD"
27 # osm - experimental - uncomment to deactivate
28 OSM_URL = "https://www.openstreetmap.org/search?query="
29 # OSWM link with coordinates - uncomment to deactivate
30 OSM_COORDINATES = "https://www.openstreetmap.org/?"
32 FEEDBACK = "\n\nFeedback zu diesem Feature bitte an **[@ju](https://mattermost.fsinf.at/fsinf-intern/messages/@ju)** =^.^="
34 HELP_TEXT = "Folgende Tipps können dir bei der Suche helfen:\n"
36 HELP_TEXT += "+ die Suche ist nicht case sensitiv\n"
37 HELP_TEXT += "+ Verwende 'EI 7' statt 'EI7'\n"
38 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."
42 def __init__(self, team_id, mw_user=None, mw_user_pw=None):
43 super().__init__(team_id)
44 self.mw_user = mw_user
45 self.mw_user_pw = mw_user_pw
48 def on_POST(self, request, data):
51 if data["text"].strip() != "" and data["text"].replace("--chan ", "").strip() != "":
52 if data["text"].startswith("--chan "):
53 msg = self.roomSearch(data["text"].replace("--chan ", ""))
54 request.cmd_respond_text_chan(msg)
57 msg = self.roomSearch(data["text"])
58 request.cmd_respond_text_temp(msg)
61 request.cmd_respond_text_temp("Du hast vergessen einen Raumnamen anzugeben.\n\n" + self.HELP_TEXT)
65 def roomSearch(self, searchTerm):
66 searchTerm = searchTerm.strip()
67 if searchTerm == "help" or searchTerm == "?":
70 # a try to prevent injections
71 searchTerm = re.sub("[^\w]+", " ", searchTerm)
72 searchTerm = searchTerm.replace(" ", " ").strip()
74 # space to * for matching "HS 11" to "HS 11" and "HS11"
75 searchTerm = searchTerm.replace(" ", "*")
76 query="[[Category:Raumcode]]|[[RoomName::~*" + searchTerm + "*]] OR [[SearchValue::~*" + searchTerm + "*]] OR [[RoomCode::~*" + searchTerm + "*]]|?RoomName|?Address|?RoomCode|?Longitude|?Latitude"
77 result = "Du hast nach **`" + searchTerm + "`** gesucht."
79 # check if service is available, if so execute query
81 mws = mwclient.Site(self.WIKI_URL, path="/", retry_timeout=120)
83 return "Der Service ist gerade nicht verfügbar (zB keine Verbindung zum wiki)."
85 #use user + pass for wiki connection if it is set
86 if self.mw_user and self.mw_user_pw:
87 mws.login(self.mw_user, self.mw_user_pw)
88 # TODO: wrong credentials behandeln
91 query_result = mws.ask(query)
94 # https://stackoverflow.com/a/21525143
96 if next(query_result, _exhausted) == _exhausted:
97 return result + " Leider konnten keine Ergebnisse gefunden werden.\n\n" + self.HELP_TEXT
99 result += " Folgende Räume wurden gefunden:\n"
100 # get items again, because they get consumed in the isEmpty
101 query_result = mws.ask(query)
104 for p in query_result:
105 if counter < self.MAX_RESULTS:
107 # check if values are present
108 if len(next(iter(p.values()))["printouts"]["RoomCode"]) > 0:
109 roomCode = next(iter(p.values()))["printouts"]["RoomCode"][0]
112 if len(next(iter(p.values()))["printouts"]["RoomName"]) > 0:
113 roomName = next(iter(p.values()))["printouts"]["RoomName"][0]
116 if len(next(iter(p.values()))["printouts"]["Address"]) > 0:
117 address = next(iter(p.values()))["printouts"]["Address"][0]
120 if len(next(iter(p.values()))["printouts"]["Longitude"]) > 0:
121 longitude = next(iter(p.values()))["printouts"]["Longitude"][0]["fulltext"]
124 if len(next(iter(p.values()))["printouts"]["Latitude"]) > 0:
125 latitude = next(iter(p.values()))["printouts"]["Latitude"][0]["fulltext"]
129 url = next(iter(p.values()))["fullurl"]
131 result += "\n+ [" + roomCode + "](" + url + "), **" + roomName + "** findest du hier: "
134 # priority over "OSM_URL":
135 if "OSM_COORDINATES" in dir(self) and len(latitude) > 0 and len(longitude) > 0:
136 # mlat={{{latitude}}}&mlon={{{longitude}}}#map=19/{{{latitude}}}/{{{longitude}}}
137 osm_query = "mlat=" + latitude + "&mlon=" + longitude + "#map=19/" + latitude + "/" + longitude
138 result += "[" + address + "](" + self.OSM_COORDINATES + osm_query + " \"link to open street maps\")"
139 # link without coordinates:
140 elif "OSM_URL" in dir(self):
141 # case format "1040 Wien, Favoritenstraße 9; durch Gittertor und Hof zu Stiege II; ins 2. OG; vom Lift aus rechts;"
142 if "wien" in address.split(",")[0].lower():
143 osm_query = "wien%20" + address.split(";")[0].split(",")[1]
144 # case format "Floragasse 7, 2. Stock"
146 osm_query = "wien%20" + address.split(",")[0]
147 # transforms space to %20
148 osm_query = osm_query.replace(" ", "%20")
149 # transforms street number "22-25" to "22"
150 osm_query = re.sub(r"-\d+", r"", osm_query)
152 result += "[" + address + "](" + self.OSM_URL + osm_query + ")"
153 # else print plain address
160 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
165 if __name__ == "__main__":
166 a = CommandRaumsuche("asdf")
167 print(a.roomSearch(sys.argv[1]))