chaloBEST/smsBEST/mumbai/app.py

57 lines
2.1 KiB
Python
Raw Normal View History

from rapidsms.apps.base import AppBase
2012-02-28 18:10:22 +00:00
import re
import arrest
MAX_MSG_LEN = 160
2012-02-28 18:10:22 +00:00
DIGIT = re.compile(r"\d{1,3}")
2012-02-28 20:03:35 +00:00
PUNCT = re.compile(r"[^\w\s]")
"""
2012-02-28 20:03:35 +00:00
STYLE = {
2012-02-28 20:15:32 +00:00
"start": "-* ",
"repeat": " -*- ",
"end": " *-"
2012-02-28 20:03:35 +00:00
}
"""
STYLE = {"start": "", "repeat": "; ", "end": ""}
2012-02-28 20:03:35 +00:00
ChaloBest = arrest.Client("http://chalobest.in/1.0")
class App(AppBase):
2012-02-28 18:10:22 +00:00
def handle(self, msg):
if DIGIT.search(msg.text):
2012-02-28 20:03:35 +00:00
routes = ChaloBest.routes(q=msg.text.replace(" ", ""))
2012-02-28 21:08:53 +00:00
if not routes:
msg.respond("Sorry, we found no route marked '%(text)s'.", text=msg.text)
2012-02-28 20:15:32 +00:00
return
2012-02-28 21:08:53 +00:00
detail = ChaloBest.route[routes[0]]
stops = detail['stops']['features']
origin, dest = stops[0]['properties'], stops[-1]['properties']
origin_name, dest_name = origin['display_name'], dest['display_name']
origin_area, dest_area = PUNCT.sub('', origin['area']), PUNCT.sub('', dest['area'])
msg.respond("%s: %s (%s) to %s (%s)" % (
",".join(routes), origin_name, origin_area, dest_name, dest_area))
2012-02-28 18:10:22 +00:00
else:
features = ChaloBest.stops(q=msg.text)['features']
if not features:
msg.respond("Sorry, we found no stops marked '%(text)s'.", text=msg.text)
2012-02-28 20:15:32 +00:00
return
stops = []
for feat in features:
stop = feat['properties']
if stops and stop["official_name"] == stops[-1]["official_name"]:
stops[-1]["routes"] += ", " + stop["routes"]
else:
stops.append(stop)
2012-02-28 20:03:35 +00:00
response = STYLE["start"]
for stop in stops:
match = stop["official_name"] + ": " + stop["routes"]
if len(response) > len(STYLE["repeat"]): response += STYLE["repeat"]
response += match
if len(response) > MAX_MSG_LEN: break
if len(response) > MAX_MSG_LEN:
response = response[:MAX_MSG_LEN-(len(STYLE["end"])+4)] + "..."
2012-02-28 20:03:35 +00:00
response += STYLE["end"]
msg.respond(response)