Last active
January 29, 2018 15:52
-
-
Save williamjacksn/e8509ee834e05b632466e33499692fa9 to your computer and use it in GitHub Desktop.
An IRC bot that is as simple as possible, but not simpler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
# change these | |
HOST = 'irc.undernet.org' | |
PORT = 6667 | |
NICK = 'rex' | |
CHAN = '#dashin' | |
# this is the function I will use when I want to send a message to the IRC server | |
def send_line(irc: socket.socket, line: str): | |
print(f'=> {line}') | |
# add \r\n to the end of the line and convert it from string to bytes, then send | |
irc.send(f'{line}\r\n'.encode()) | |
# this is the function I will use when I want to process a message I received from the IRC server | |
def handle_line(irc: socket.socket, line: bytes): | |
# convert line from bytes to string, and remove leading and trailing whitespace | |
line = line.decode().strip() | |
print(f'<= {line}') | |
# split the line on whitespace into a list of tokens | |
tokens = line.split() | |
if tokens[0] == 'PING': | |
# when the server sends PING, I automatically reply with PONG | |
send_line(irc, f'PONG {tokens[1]}') | |
elif tokens[1] in ('376', '422'): | |
# 376 means the server has finished sending the message of the day | |
# 422 means there is no message of the day to send | |
# in any case, now I can join my channel | |
send_line(irc, f'JOIN {CHAN}') | |
# this is where I start my work | |
def main(): | |
irc = socket.socket() | |
irc.connect((HOST, PORT)) | |
print(f'** connected to {HOST}') | |
# identify myself to the IRC server | |
send_line(irc, f'NICK {NICK}') | |
send_line(irc, f'USER {NICK} {HOST} x :{NICK}') | |
# set up a buffer that I can use to receive messages from the server | |
buffer = b'' | |
while True: | |
# receive what the server has sent me | |
buffer = buffer + irc.recv(4096) | |
# split it into lines | |
lines = buffer.split(b'\n') | |
# the last line might be incomplete, put it back in the buffer | |
buffer = lines.pop() | |
# handle each of the lines that the server sent me | |
for line in lines: | |
handle_line(irc, line) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment