itte/irc.py

77 lines
2.8 KiB
Python

import socket
class IRC:
"""A set of methods for basic IRC communication."""
def __init__(self):
self.debug = False
self.sock = ""
def is_debug(self, boolean):
self.debug = boolean
def send(self, command, text, *args, **kwargs):
"""Send messages given the IRC command and text. Optionally specify a
message recipient with `recvr=user`."""
recvr = kwargs.get("recvr", "")
if recvr != "":
recvr += " :"
if self.debug:
print("[debug][send] " + command + " " + recvr + text)
bs = bytes(command + " " + recvr + text + "\r\n", "utf-8")
try:
if kwargs.get("sock", "") != "":
public_ss = kwargs.get("sock", "")
public_ss.sendall(bs)
else:
self.sock.sendall(bs)
except BrokenPipeError:
print("[debug][broken_pipe_err] " + command + " " + recvr + text)
pass
def connect(self, server, bot_nick):
"""Connect to the server and sends user/nick information."""
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect(server)
self.send("USER", bot_nick + " " + bot_nick + " " + \
bot_nick + " " + bot_nick)
self.send("NICK", bot_nick)
return self.sock
def disconnect(self, resp_msg, quit_msg, admin_user):
"""Notify the admin user and disconnect from the server."""
self.send("PRIVMSG", resp_msg, recvr=admin_user)
self.send("QUIT", ":" + quit_msg)
def receive(self, *args, **kwargs):
data = self.sock.recv(2040).decode("utf-8").strip("\n\r")
if self.debug:
print("[debug][recv] " + data)
return data
def keep_alive(self, line):
"""Stay connected to a server by responding to server pings."""
if "PING" in line:
self.send("PONG", ":" + line.split(":", 2)[1].split(" ", 1)[0])
def join_channels(self, channels):
"""Join channels from a list in the config."""
for c in channels:
if c.strip() != "" or c.strip() != "#":
self.send("JOIN", c)
def parse_msg(self, line, req_prefix):
"""Extract the request, the nick and username of the requester,
the channel where the request originated and returns a dictionary of
values."""
data = {"req": "", "req_chan": "", "nick": "", "user": ""}
if (":" + req_prefix) in line:
data["req"] = line.split("PRIVMSG", 1)[1].split(":" + \
req_prefix, 1)[1].strip()
data["req_chan"] = line.split("PRIVMSG ", \
1)[1].split(" :", 1)[0]
data["nick"] = line.split("!~", 1)[0][1:]
data["user"] = line.split("!~", 2)[1][0:].split("@", 1)[0]
return data