Created
June 12, 2013 23:36
-
-
Save hacosta/5770069 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
import sys | |
import re | |
import argparse | |
import itertools | |
import logging | |
import urllib.request | |
import bs4 | |
import irc.bot | |
import random | |
def get_urls(s): | |
return re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', s) | |
class TontoBot(irc.bot.SingleServerIRCBot): | |
FETCH_MAX = 20 * 1024 | |
FAIL_MSGS = [':(', '):', '?', 'WAT', 'No pos no', 'link no worky', 'chupa limon'] | |
def __init__(self, serverspec, channel, nickname, realname): | |
irc.bot.SingleServerIRCBot.__init__(self, [serverspec], nickname, realname) | |
self.channel = channel | |
logging.info("channel= %s" % channel) | |
def on_welcome(self, connection, event): | |
logging.info("joining %s", self.channel) | |
connection.join(self.channel) | |
def on_pubmsg(self, connection, event): | |
line = event.arguments[0] | |
opener = urllib.request.build_opener() | |
opener.add_headers = [('User-agent', 'Mozilla/5.0')] | |
for u in get_urls(line): | |
try: | |
fd = opener.open(u) | |
soup = bs4.BeautifulSoup(fd.read(self.FETCH_MAX)) | |
connection.privmsg(self.channel, soup.title.string) | |
except: | |
logging.error("Failed with: %s" % line) | |
connection.privmsg(self.channel, random.choice(self.FAIL_MSGS)) | |
def get_args(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument('--server', default='irc.freenode.net') | |
parser.add_argument('--nickname', default='tontobot') | |
parser.add_argument('--channel', default='#gultec', help="a nickname or channel") | |
parser.add_argument('--realname', default='Tonto Bot', help="a nickname or channel") | |
parser.add_argument('-p', '--port', default=6667, type=int) | |
return parser.parse_args() | |
def main(): | |
logging.basicConfig(level=logging.INFO) | |
args = get_args() | |
serverspec = irc.bot.ServerSpec(args.server, args.port) | |
bot = TontoBot(serverspec, args.channel, args.nickname, args.realname) | |
try: | |
c = bot.start() | |
except irc.client.ServerConnectionError: | |
log.error((sys.exc_info()[1])) | |
raise SystemExit(1) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment