Gave the bot plastic surgery, it no longer looks the same from most angles

This commit is contained in:
Chris Oliver 2010-02-06 21:12:50 -06:00
parent 8f1de01c45
commit 34101ad0f9

240
logbot.py
View file

@ -29,160 +29,138 @@ __date__ = "08/11/2009"
__copyright__ = "Copyright (c) Chris Oliver" __copyright__ = "Copyright (c) Chris Oliver"
__license__ = "GPL2" __license__ = "GPL2"
# Imports
import os import os
import os.path import os.path
import irclib import irclib
from ftplib import FTP from ftplib import FTP
from time import strftime from time import strftime
# Customizable Variables # Customizable Variables
######################## ########################
# Log format
extensions = {'text':'log',
'html':'html'}
# Valid formats: text, html
FORMAT = 'text'
# Connection information
network = 'irc.freenode.net' network = 'irc.freenode.net'
port = 6667 port = 6667
channels = ['#keryx'] channels = ['#excid3', '#keryx']
nick = 'Excid3LogBot' nick = 'Timber'
name = 'Excid3LogBot' owner = ['excid3|asus', 'mac9416']
logs_folder = 'logs'
# FTP information
USE_FTP = False # Allow FTP uploads
host = '' # Server Ex. deathlok.dreamhost.com
username = ''
password = ''
# Folder on the server where the logs will be stored
# ALWAYS terminate with a /
# NOTE: This directory should already exist
# Ex: chdir = 'excid3.com/logs/'
chdir = ''
counter = 0 html_header = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
lines = 50 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>%s</title>
<link href="/static/css/stylesheet.css" rel="stylesheet" type="text/css" />
</head>
<body onload="init()">
</body>
</html>
"""
def write(channel, message):
""" Write to the log file and console """ class LogBot(object):
# Format the message def __init__(self, network, port, channels, owner, nick, folder):
string = '%s %s' % (strftime('[%H:%M]'), message) self.network = network
if FORMAT == 'html': self.port = port
string += '<br />' self.channels = channels
string += '\n' self.owner = owner
self.nick = nick
# Make sure the local folder exists for logging this channel self.folder = folder
if not os.path.exists(channel):
os.mkdir(channel)
# Append the message to the file locally def start(self):
path = os.path.join(channel, '%s_%s.%s' % (channel, strftime('%m-%d-%Y'), \ # Write logs locally, so we need the folder to exist
extensions[FORMAT])) if not os.path.exists(self.folder):
f = open(path, 'a') os.mkdir(self.folder)
f.write(string) os.chdir(self.folder)
f.close()
print '%s> %s' % (channel, message)
def handleJoin(connection, event): # Create an IRC object
""" User joins channel """ self.irc = irclib.IRC()
nick = event.source().split("!")
# Setup the IRC functionality we want to log
handlers = {'join': self.handleJoin,
'pubmsg': self.handlePubMessage,
'privmsg': self.handlePrivMessage,
'part': self.handlePart,
'invite': self.handleInvite,
'kick': self.handleKick,
'mode': self.handleMode,
'pubnotice': self.handlePubNotice,
'quit': self.handleQuit}
for key, val in handlers.items():
self.irc.add_global_handler(key, val)
# Create a server object, connect and join the channel
self.server = self.irc.server()
self.server.connect(self.network, self.port, self.nick, ircname=self.nick)
for channel in self.channels:
self.server.join(channel)
# Jump into an infinte loop
self.irc.process_forever()
try: #eventtype -- A string describing the event.
nickmask = nick[1] #source -- The originator of the event (a nick mask or a server).
#target -- The target of the event (a nick or a channel).
#arguments
def handleKick(self, connection, event):
# kicker, channel, [person, reason]
print event.source(), event.target(), event.arguments()
def handleMode(self, connection, event):
# person giving ops, #channel, [modes, person]
print event.source(), event.target(), event.arguments()
def handlePubNotice(self, connection, event):
# user, channel, [msg]
print event.source(), event.target(), event.arguments()
def handleQuit(self, connection, event):
# user, channel?, [reason]
print event.source(), event.target(), event.arguments()
def handlePrivMessage(self, connection, event):
# sender, receiver (me), [msg]
print event.source(), event.target(), event.arguments()
def handleJoin(self, connection, event):
nick = event.source().split("!")
try:
nickmask = nick[1]
except:
nickmask = "unknown"
nick = nick[0] nick = nick[0]
except:
nick = "unknown"
nickmask = "unknown"
write(event.target(), '%s (%s) has joined %s' % print "%s (%s) has joined %s" % \
(nick, nickmask, event.target())) (nick,
nickmask,
def handleInvite(connection, event): event.target())
""" User invites bot to join channel """
connection.join(event.arguments()[0])
def handlePubMessage(connection, event): # Any public message
""" Public message is sent """
global counter, lines
write(event.target(), '%s: %s' % \
(event.source().split ('!')[0], event.arguments()[0]))
# Update the counter and check it to see if its time to upload
counter += 1
if counter == lines and USE_FTP:
upload()
counter = 0
def handlePart(connection, event):
""" User parts channel """
write(event.target(), '%s has parted %s' % \
(event.source().split('!')[0], event.target()))
def upload():
""" Upload files via FTP """
try:
print 'Uploading logs to %s ...' % host
# Create the FTP connection def handlePubMessage(self, connection, event):
ftp = FTP(host, username, password) nick = event.source().split("!")[0]
print "%s: %s" % \
(nick,
event.arguments()[0])
# Attempt to create the directory if it does not already exist def handlePart(self, connection, event):
try: ftp.mkd(chdir) nick = event.source().split("!")[0]
except: pass print '%s has parted %s' % \
(nick,
for channel in channels: event.target())
# Attempt to create subdirectory for channel
try: ftp.mkd('%s%s' % (chdir, channel)) def handleInvite(self, connection, event):
except: pass nick = event.source().split("!")[0]
# Move to the directory
ftp.cwd('%s%s' % (chdir, channel))
# Get the path for the filename
path = os.path.join(channel, '%s_%s' % \
(channel, strftime('%m-%d-%Y')))
# Open the file and store it via FTP
f = open(path, 'rb')
ftp.storbinary('STOR %s_%s.%s' % \
(channel, strftime('%m-%d-%Y'), extensions[FORMAT]), f)
f.close()
# Close the FTP connection
ftp.quit()
print 'Finished uploading logs to %s' % chdir
except Exception, e: # Only allow invites from owner(s)
print e if not nick in self.owner:
print 'Make sure your FTP information is correct.' print "Invite from %s denied" % nick
return
for channel in event.arguments():
self.server.join(channel)
def main(): def main():
""" Join the IRC server """ bot = LogBot(network, port, channels, owner, nick, logs_folder)
bot.start()
# Write logs locally to logs/
if not os.path.exists('logs'):
os.mkdir('logs')
os.chdir('logs')
# Create an IRC object
irc = irclib.IRC()
# Setup the IRC functionality we want to log
irc.add_global_handler('join', handleJoin)
irc.add_global_handler('pubmsg', handlePubMessage)
irc.add_global_handler('part', handlePart)
irc.add_global_handler('invite', handleInvite)
# Create a server object, connect and join the channel
server = irc.server()
server.connect(network, port, nick, ircname=name)
for channel in channels:
server.join(channel)
# Jump into an infinte loop
irc.process_forever()
if __name__ == '__main__': if __name__ == '__main__':
main() main()