Python IRC Bot

The bot doesn’t do much but tell fortunes, give a pong response to a ping, and log the chatroom. Will probably add to is as I get bored. The fortunes text file can be found here if interested.

import socket
import random
from config import *

def processChat(sock, buff):
	buff = buff.strip() # strip for processing
	buff = buff.split(':') # split on colon delimitation
	e = buff[1]
	msg = buff[2]
	if(msg == 'ping'):
		sock.send('PRIVMSG ' + channel + ' :pong\n')
	if(msg == 'fortune'):
		readFortune(sock)

def pingRespond(sock, buff):
	buff = buff.strip()
	buff = buff.split(':')
	sock.send('PONG :' + buff[1] + "\n")

def openConnection():
	sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	sock.connect((server, port))
	sock.send('PASS ' + password + '\n')
	sock.send('NICK ' + nick + '\n')
	sock.send('USER ' + nick + ' ' + ident + ' ' + server + ' :' + realname + '\n')
	return sock

def readFortune(sock):
		f = random.choice(fortunes)
		sock.send('PRIVMSG ' + channel + ' :' + f + '\n')

def main():
	sock = openConnection()
	sock.send('JOIN ' +  channel + '\n')
	if(log):
		logFile = open((channel + "log.txt"), "w")
		while True:
			buff = sock.recv(512)
			logFile.write(buff + '\n')
			if(buff.find('PRIVMSG') != -1):
				processChat(sock, buff)
			if(buff.find('PING') != -1):
				pingRespond(sock, buff)
	else:
		while True:
			buff = sock.recv(512)
			if(buff.find('PRIVMSG') != -1):
				processChat(sock, buff)
			if(buff.find('PING') != -1):
				pingRespond(sock, buff)

if __name__ == "__main__":
	main()

#The bots nick
nick = 'defaultNick';
#The bots identifier
ident = 'defaultID';
#The server the bot is connecting to
server = 'irc.freenode.net';
#The TCP port used
port = 6667;
#Channel to connect to
channel = '#botwar'
#"Realname" for the bot
realname = 'Frank'
#The password sent to IRC client
password = '' 
#The fortunes used
fortunes = open('fortune.txt').read().splitlines()
#Logging status
log = True

Leave a Reply

Your email address will not be published. Required fields are marked *