Python IRC Bot: Initial Experimentation

The #archlinux IRC bot has gone on his summer holidays, and his absence got me thinking that I should have an attempt at making a botty-like-thing.

The code needs a rewrite and a tidy into OO, but here it is so far:

#!/usr/bin/env python

import sys
import socket
import string
import time
import re

HOST="irc.freenode.net"
PORT=6667
NICK="BavBot"
IDENT="bavbot"
REALNAME="Bavardage's bot"
readbuffer=""

def reply(socket, channel, nick, message):
	socket.send("PRIVMSG %s %s: %s\r\n" % (channel, nick, message))

def handle_command(channel, nick, command, arguments, socket):
	command = command[1:]
	if command == 'WHOAREYOU':
		reply(socket, channel, nick, "I am the bot")
	elif command == 'BYE':
		socket.send ( 'QUIT\r\n' )
		exit()
	else:
		print "command was", command

def handle_message(channel, nick, message, socket):
	print "%s on %s: %s" % (nick, channel, message)
	if(message[0] == '!'):
		print "is a command"
		dat = message.split()
		handle_command(channel, nick, dat[0], dat[1:], socket)
	else:
		print "not a command", message


s=socket.socket( )
s.connect((HOST, PORT))
time.sleep(0.2)
s.send("NICK %s\r\n" % NICK)
time.sleep(0.2)
s.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME))
print s.recv(4096)
time.sleep(0.2)
s.send("JOIN ##bavardage\r\n")
print s.recv(4096)
print "entering while now"
try:
	while 1:
	    data = s.recv(1024)
	    if data:
		print "data: " + str(data)
	    readbuffer=readbuffer+data
	    temp=string.split(readbuffer, "\n")
	    readbuffer=temp.pop( )

	    for line in temp:
		line=string.rstrip(line)
		line=string.split(line)

		if(line[0]=="PING"):
		    s.send("PONG %s\r\n" % line[1])
		else:
		    if(line[1]=='PRIVMSG'):
			print "PRIVATE MESSAGE"
			channel = line[2]
			nick = line[0].split('!')[0]
			message = ' '.join(line[3:])[1:]
			print "message '%s'" % message
			print "%s spoke on %s: %s" % (nick, channel, message)
			handle_message(channel, nick, message, s)
	    '''if data.find ( 'PRIVMSG' ) != -1:
		nick = data.split ( '!' ) [ 0 ].replace ( ':', '' )
		message = ':'.join ( data.split ( ':' ) [ 2: ] )
		print nick + ':', message'''
except:
	print "interrupt"
	print sys.exc_info()[0]
	s.send ( 'QUIT\r\n' )
	print s.recv(1024)
 
Advertisements
Python IRC Bot: Initial Experimentation

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s