-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrollbot.py
71 lines (59 loc) · 2.32 KB
/
rollbot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import sys
import re
import urllib
import BeautifulSoup
from HTMLParser import HTMLParseError
from twisted.words.protocols import irc
from twisted.internet import protocol, reactor
class MyBot(irc.IRCClient):
def _get_nickname(self):
return self.factory.nickname
nickname = property(_get_nickname)
def signedOn(self):
self.join(self.factory.channel, self.factory.password)
print "Signed on as {}".format(self.nickname)
def joined(self, channel):
print "Joined %s." % channel
def privmsg(self, user, channel, msg):
# get title of urls
matches = re.findall(
r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|'
r'(?:%[0-9a-fA-F][0-9a-fA-F]))+', msg)
if matches:
for url in matches:
u = urllib.urlopen(url)
urltype = u.headers.gettype()
print urltype
try:
soup = BeautifulSoup.BeautifulSoup(u)
title = re.sub("\s+", ' ', soup.title.string).strip()
title = title.encode('ascii', 'ignore')
self.msg(self.factory.channel, "Title: %s" % str(title))
except (AttributeError, HTMLParseError):
urllib.urlopen(url)
self.msg(self.factory.channel,
"NO TITLE FOUND (%s)" % urltype)
class MyBotFactory(protocol.ClientFactory):
protocol = MyBot
def __init__(self, channel, nickname="Rollbot", password=None):
self.channel = '#{}'.format(channel)
self.nickname = nickname
self.password = password
def clientConnectionLost(self, connector, reason):
print "Lost connection (%s), reconnecting." % reason
connector.connect()
def clientConnectionFailed(self, connector, reason):
print "Could not connect: %s" % reason
if __name__ == "__main__":
try:
channel = sys.argv[1]
password = None
if len(sys.argv) == 3:
password = sys.argv[2]
reactor.connectTCP('irc.freenode.net', 6667, MyBotFactory(
channel=channel, password=password))
reactor.run()
except IndexError:
print "Please specify a channel name."
print "Example:"
print " python %s somechannel [channel_password]" % sys.argv[0]