Last active
August 31, 2021 23:05
-
-
Save wilhelmy/46bfda540fd4be13db01bf22ecb06759 to your computer and use it in GitHub Desktop.
deadsimple IRC client in 55 lines of python to show you that IRC is easy to implement - public domain - see also: http://www.faqs.org/rfcs/rfc1459.html
This file contains 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
from sys import stdin | |
import socket, select | |
channel = '#worldchat' | |
server = ('vienna.irc.at',6669) | |
ident = nick = 'herbert' | |
user = 'Herbert Herbert' | |
irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
irc.connect(server) | |
def send(msg): irc.send(bytes(msg, 'utf-8')) | |
send('NICK %s\r\n' % nick) | |
send('USER %s 0 0 :%s\r\n' % (ident, user)) | |
send('JOIN %s\r\n' % channel) | |
poll = select.poll() | |
poll.register(irc, select.POLLIN) | |
poll.register(stdin, select.POLLIN) | |
def do_irc(irc): | |
for line in str(irc.recv(2048), 'utf-8').splitlines(): # FIXME check if message ends with \r\n, buffer it otherwise | |
sp = line.split(' ') | |
if len(sp) > 1 and sp[0].upper() == 'PING': | |
send('PONG %s\r\n' % sp[1]) | |
elif len(sp) > 1 and sp[1].upper() == 'PRIVMSG': | |
msg = line.split(':',2)[-1] | |
nick = sp[0].split('!')[0].lstrip(':') | |
who = nick + (sp[2].lower() != channel.lower() and ':' + sp[2] or '') | |
if not msg.startswith('\001'): | |
print('<%s> %s' % (who ,msg)) | |
else: # CTCP | |
(ctcp, msg) = msg.strip('\001').split(' ',1) | |
if ctcp.upper() == 'ACTION': | |
print('* %s %s' % (who, msg)) | |
else: | |
print('! %s requested unknown CTCP %s %s' % (who, ctcp, msg)) | |
else: | |
print(line) | |
def do_stdin(stdin, irc): | |
line = stdin.readline().splitlines()[0] | |
if line.startswith('/'): | |
send(line[1:] + '\r\n') | |
else: | |
send('PRIVMSG %s :%s\r\n' % (channel, line)) | |
while True: | |
ready = poll.poll() | |
for (fd, events) in ready: | |
if fd == 0: # stdin | |
do_stdin(stdin, irc) | |
else: # irc fd | |
do_irc(irc) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment