chaloBEST/smsBEST/mumbai/app.py

50 lines
1.9 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]")
STYLE = {
2012-02-28 20:15:32 +00:00
"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(" ", ""))
detail = ChaloBest.route[routes[0]]
2012-02-28 18:10:22 +00:00
stops = detail['stops']['features']
2012-02-28 20:15:32 +00:00
if not stops:
msg.respond("Sorry, we found no route marked '%s'." % msg.text)
return
2012-02-28 18:10:22 +00:00
origin, destination = stops[0]['properties'], stops[-1]['properties']
msg.respond("%s: %s (%s) to %s (%s)" % (routes[0],
origin['display_name'], origin['area'],
destination['display_name'], destination['area']))
else:
2012-02-28 20:03:35 +00:00
stops = ChaloBest.stops(q=msg.text)['features']
2012-02-28 20:15:32 +00:00
if not stops:
msg.respond("Sorry, we found no stops like '%s'." % msg.text)
return
2012-02-28 20:03:35 +00:00
response = STYLE["start"]
for feature in stops:
stop = feature['properties']
2012-02-28 20:03:35 +00:00
area = PUNCT.sub('', stop['area'])
match = "%s (%s): %s" % (stop['official_name'], area, stop['routes'])
if len(response) + len(match) + len(STYLE["repeat"]) < MAX_MSG_LEN:
2012-02-28 20:15:32 +00:00
if len(response) > len(STYLE["repeat"]): response += STYLE["repeat"]
response += match
2012-02-28 20:15:32 +00:00
elif len(response) < len(STYLE["repeat"]):
response += match[:MAX_MSG_LEN-len(STYLE["start"])-len(STYLE["end"])+4]
response += " ..."
else:
break
2012-02-28 20:03:35 +00:00
response += STYLE["end"]
msg.respond(response)