2016-03-29 11:56:58 +00:00
|
|
|
import re
|
2019-02-09 10:57:05 +00:00
|
|
|
from src import EventManager, ModuleManager, utils
|
2016-03-29 11:56:58 +00:00
|
|
|
|
|
|
|
REGEX_URL = re.compile("https?://\S+", re.I)
|
|
|
|
|
2019-02-09 10:35:37 +00:00
|
|
|
@utils.export("channelset", {"setting": "auto-title",
|
|
|
|
"help": "Disable/Enable automatically getting info titles from URLs",
|
|
|
|
"validate": utils.bool_or_none})
|
2018-09-26 17:27:17 +00:00
|
|
|
class Module(ModuleManager.BaseModule):
|
2019-02-09 10:35:37 +00:00
|
|
|
def _get_title(self, url):
|
|
|
|
try:
|
|
|
|
page = utils.http.request(url, soup=True)
|
|
|
|
except Exception as e:
|
2019-02-09 13:37:21 +00:00
|
|
|
self.log.error("failed to get URL title", [], exc_info=True)
|
2019-02-09 10:35:37 +00:00
|
|
|
return None
|
2019-02-28 23:30:09 +00:00
|
|
|
except utils.http.HTTPWrongContentTypeException:
|
|
|
|
return None
|
2019-02-09 10:38:44 +00:00
|
|
|
if page.data.title:
|
|
|
|
return page.data.title.text.replace("\n", " ").replace(
|
|
|
|
"\r", "").replace(" ", " ").strip()
|
|
|
|
else:
|
|
|
|
return None
|
2019-02-09 10:35:37 +00:00
|
|
|
|
2019-02-09 10:56:06 +00:00
|
|
|
@utils.hook("received.message.channel",
|
|
|
|
priority=EventManager.PRIORITY_MONITOR)
|
2019-02-09 10:35:37 +00:00
|
|
|
def channel_message(self, event):
|
|
|
|
match = re.search(REGEX_URL, event["message"])
|
|
|
|
if match and event["channel"].get_setting("auto-title", False):
|
|
|
|
title = self._get_title(match.group(0))
|
|
|
|
if title:
|
|
|
|
self.events.on("send.stdout").call(target=event["channel"],
|
|
|
|
message=title, module_name="Title",
|
|
|
|
server=event["server"])
|
|
|
|
|
2018-10-10 09:42:41 +00:00
|
|
|
@utils.hook("received.command.t", alias_of="title")
|
|
|
|
@utils.hook("received.command.title", usage="[URL]")
|
2018-08-31 11:55:52 +00:00
|
|
|
def title(self, event):
|
2018-09-26 17:27:17 +00:00
|
|
|
"""
|
2018-09-30 16:29:09 +00:00
|
|
|
:help: Get the title of a URL
|
|
|
|
:usage: [URL]
|
2018-09-26 17:27:17 +00:00
|
|
|
"""
|
2018-08-31 11:55:52 +00:00
|
|
|
url = None
|
|
|
|
if len(event["args"]) > 0:
|
|
|
|
url = event["args_split"][0]
|
|
|
|
else:
|
2018-09-30 10:43:34 +00:00
|
|
|
url = event["target"].buffer.find(REGEX_URL)
|
2018-08-31 11:55:52 +00:00
|
|
|
if url:
|
|
|
|
url = re.search(REGEX_URL, url.message).group(0)
|
|
|
|
if not url:
|
2018-10-16 14:09:58 +00:00
|
|
|
raise utils.EventError("No URL provided/found.")
|
2018-10-19 09:31:45 +00:00
|
|
|
|
2019-02-09 10:35:37 +00:00
|
|
|
title = self._get_title(url)
|
2018-10-19 09:31:45 +00:00
|
|
|
|
2018-08-31 11:55:52 +00:00
|
|
|
if title:
|
|
|
|
event["stdout"].write(title)
|
|
|
|
else:
|
2019-02-09 10:35:37 +00:00
|
|
|
event["stderr"].write("Failed to get title")
|