Skip to content

Commit

Permalink
Add link shortener to urls plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
johnmaguire committed Mar 8, 2024
1 parent a344715 commit b8fd76c
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 5 deletions.
10 changes: 6 additions & 4 deletions plugins/urls/config.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
{
"timeout": 5,
"read_bytes": 524288,
"lookup_cooloff": 10,
"handle_generic_urls": true
"timeout": 5,
"read_bytes": 524288,
"lookup_cooloff": 10,
"handle_generic_urls": true,
"shorten_links": true,
"crdnlxyz_api_key": "jmlHgK+wF1hd55XqksG3uI3H92b/jGjPEOoZnwiZ26c="
}
32 changes: 31 additions & 1 deletion plugins/urls/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import re
import html
import logging
import requests
import unicodedata
from datetime import datetime
from urllib import request
Expand Down Expand Up @@ -66,6 +67,8 @@ def __init__(self, cardinal, config):
self.timeout = config.get('timeout', self.TIMEOUT)
self.read_bytes = config.get('read_bytes', self.READ_BYTES)
self.lookup_cooloff = config.get('lookup_cooloff', self.LOOKUP_COOLOFF)
self.shorten_links = config.get('shorten_links', False)
self.api_key = config.get('crdnlxyz_api_key', None)
# Whether to attempt to grab a title if no other plugin handles it
self.generic_handler_enabled = config.get(
'handle_generic_urls', True)
Expand Down Expand Up @@ -130,7 +133,34 @@ def get_title(self, cardinal, user, channel, msg):
# Truncate long titles to the first 200 characters.
title_to_send = title[:200] if len(title) >= 200 else title

cardinal.sendMsg(channel, "URL Found: %s" % title_to_send)
message = "URL Found: %s" % title_to_send

if self.shorten_links:
try:
url = self.shorten_url(url)
except Exception as e:
self.logger.exception(
"Unable to shorten URL: %s" % url)
else:
message = "^ %s: %s" % (
title_to_send, url)

cardinal.sendMsg(channel, message)

def shorten_url(self, url):
if not self.api_key:
raise Exception("No API key provided for URL shortening")

data = {
'url': url,
'token': self.api_key,
}

response = requests.post('https://crdnl.xyz/add', json=data)
response.raise_for_status()
response = response.json()

return response['url']

def close(self, cardinal):
cardinal.event_manager.remove('urls.detection')
Expand Down

0 comments on commit b8fd76c

Please sign in to comment.