hemppa/modules/loc.py

71 lines
2.3 KiB
Python
Raw Normal View History

2019-12-10 22:00:15 +02:00
from geopy.geocoders import Nominatim
2020-02-08 23:16:19 +02:00
from nio import RoomMessageUnknown
2020-02-02 23:08:15 +02:00
from modules.common.module import BotModule
2020-02-08 23:16:19 +02:00
2020-02-02 23:08:15 +02:00
from modules.common.module import BotModule
2020-01-02 14:27:29 +02:00
2019-12-10 22:00:15 +02:00
2020-02-02 23:08:15 +02:00
class MatrixModule(BotModule):
2019-12-10 22:00:15 +02:00
bot = None
2020-01-02 14:27:29 +02:00
2019-12-10 22:00:15 +02:00
def matrix_start(self, bot):
super().matrix_start(bot)
2019-12-10 22:00:15 +02:00
self.bot = bot
bot.client.add_event_callback(self.unknown_cb, RoomMessageUnknown)
def matrix_stop(self, bot):
super().matrix_stop(bot)
bot.remove_callback(self.unknown_cb)
2019-12-10 22:00:15 +02:00
async def unknown_cb(self, room, event):
if event.msgtype != 'm.location':
return
location_text = event.content['body']
# Fallback if body is empty
if len(location_text) == 0:
location_text = 'location'
sender_response = await self.bot.client.get_displayname(event.sender)
sender = sender_response.displayname
geo_uri = event.content['geo_uri']
latlon = geo_uri.split(':')[1].split(',')
# Sanity checks to avoid url manipulation
float(latlon[0])
float(latlon[1])
2020-01-02 14:27:29 +02:00
osm_link = 'https://www.openstreetmap.org/?mlat=' + \
2020-02-02 23:08:15 +02:00
latlon[0] + "&mlon=" + latlon[1]
2020-01-02 14:27:29 +02:00
2019-12-11 00:04:24 +02:00
plain = sender + ' 🚩 ' + osm_link
html = f'{sender} 🚩 <a href={osm_link}>{location_text}</a>'
2019-12-10 22:00:15 +02:00
await self.bot.send_html(room, html, plain)
async def matrix_message(self, bot, room, event):
args = event.body.split()
args.pop(0)
if len(args) == 0:
await bot.send_text(room, 'Usage: !loc <location name>')
else:
2019-12-10 22:00:15 +02:00
query = event.body[4:]
geolocator = Nominatim(user_agent=bot.appid)
2020-02-08 23:16:19 +02:00
self.logger.info('loc: looking up %s ..', query)
2019-12-10 22:00:15 +02:00
location = geolocator.geocode(query)
2020-02-08 23:16:19 +02:00
self.logger.info('loc rx %s', location)
2019-12-10 22:00:15 +02:00
if location:
locationmsg = {
2019-12-11 00:04:24 +02:00
"body": str(location.address),
"geo_uri": 'geo:' + str(location.latitude) + ',' + str(location.longitude),
2019-12-10 22:00:15 +02:00
"msgtype": "m.location",
}
2019-12-11 00:04:24 +02:00
await bot.client.room_send(room.room_id, 'm.room.message', locationmsg)
2019-12-10 22:00:15 +02:00
else:
await bot.send_text(room, "Can't find " + query + " on map!")
def help(self):
2020-02-02 23:08:15 +02:00
return 'Search for locations and display Matrix location events as OSM links'