import socket import sys import time class IRCBadMessage(Exception): pass def parsemsg(s): """Breaks a message from an IRC server into its prefix, command, and arguments. """ prefix = '' trailing = [] if not s: raise IRCBadMessage("Empty line.") if s[0] == ':': prefix, s = s[1:].split(' ', 1) if s.find(' :') != -1: s, trailing = s.split(' :', 1) args = s.split() args.append(trailing) else: args = s.split() command = args.pop(0) return prefix, command, args LINEEND = '\r\n' class IRCBot: irc = None def __init__(self, sock): # Define the socket self.irc = sock def send_privmsg(self, channel, msg): # Transfer data self.irc.send(bytes("PRIVMSG " + channel + " :" + msg + LINEEND, "UTF-8")) def send_quit(self, quitmsg): msg = f'QUIT :{quitmsg}' + LINEEND print(msg) self.irc.send(msg.encode('utf-8')) def send_action(self, action_msg): pass def connect(self, server, port, channel, botnick, botpass, botnickpass): # Connect to the server print("Connecting to: " + server) self.irc.connect((server, port)) # Perform user authentication self.irc.send(bytes("USER " + botnick + " " + botnick + " " + botnick + " :python" + LINEEND, "UTF-8")) self.irc.send(bytes("NICK " + botnick + LINEEND, "UTF-8")) self.irc.send(bytes("NICKSERV IDENTIFY " + botnickpass + " " + LINEEND, "UTF-8")) time.sleep(5) # join the channel self.irc.send(bytes("JOIN " + channel + LINEEND, "UTF-8")) def get_response(self): time.sleep(1) # Get the response resp = self.irc.recv(4096).decode("UTF-8") msg = parsemsg(resp) if msg[1] == 'PING': print('Sending pong') self.irc.send( bytes('PONG ' + LINEEND, "UTF-8")) return msg