This repository has been archived on 2023-04-13. You can view files and clone it, but cannot push or open issues or pull requests.
CloudBot/plugins/urltools.py

66 lines
2 KiB
Python
Raw Normal View History

2011-11-20 10:23:31 +01:00
from util import hook, http, urlnorm
import urllib
from urllib2 import urlopen, Request, HTTPError
2011-11-20 10:23:31 +01:00
import re
import BeautifulSoup
2012-02-02 14:05:11 +01:00
ignored_urls = ["http://google.com","http://youtube.com","http://pastebin.com","http://mibpaste.com","http://fpaste.com","beastnode.com"]
wordDic = {
'"': '"',
''': '\'',
'&': '&',
'&#60;': '<',
'&#62;': '>',
'&#171;': '«',
'&quot;': '"',
'&apos;': '\'',
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
'&laquo;': '«',
2011-11-30 16:56:46 +01:00
'&#33;': '!',
'&#036;': '$',
' ': ' '}
2011-11-20 10:23:31 +01:00
def parse(match):
url = urlnorm.normalize(match.encode('utf-8'))
if url not in ignored_urls:
url = url.decode('utf-8')
try:
soup = BeautifulSoup.BeautifulSoup(http.get(url))
2011-11-20 10:23:31 +01:00
return soup.title.string
except:
return "fail"
2011-11-20 10:23:31 +01:00
def multiwordReplace(text, wordDic):
rc = re.compile('|'.join(map(re.escape, wordDic)))
def translate(match):
return wordDic[match.group(0)]
return rc.sub(translate, text)
2011-11-20 10:23:31 +01:00
#@hook.regex(r'^(?#Protocol)(?:(?:ht|f)tp(?:s?)\:\/\/|~\/|\/)?(?#Username:Password)(?:\w+:\w+@)?(?#Subdomains)(?:(?:[-\w]+\.)+(?#TopLevel Domains)(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]{2}))(?#Port)(?::[\d]{1,5})?(?#Directories)(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|\/)+|\?|#)?(?#Query)(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?#Anchor)(?:#(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)?$')
2012-02-02 14:05:11 +01:00
#@hook.regex(r'([a-zA-Z]+://|www\.)[^ ]+')
2011-11-30 12:24:03 +01:00
def urlparser(match, say = None):
2011-11-30 16:56:46 +01:00
print "[debug] URL found"
url = urlnorm.normalize(match.group().encode('utf-8'))
for x in ignored_urls:
if x in url:
return
title = parse(url)
if title == "fail":
2011-11-30 16:56:46 +01:00
print "[url] No title found"
return
title = multiwordReplace(title, wordDic)
2011-11-30 13:51:43 +01:00
realurl = http.get_url(url)
if realurl == url:
say("(Link) %s" % title)
return
else:
say("(Link) %s [%s]" % (title, realurl))
return
2011-11-20 10:23:31 +01:00