Monday, April 28, 2025

IRC Bot in Python - Passive IRC Client

This Python script will connect to IRC server and lurk in background. 

 

We are doing network related programming, so first thing is to import socket module. 

We need it to prepare IPv4 connection (socket.AF_INET) with TCP (socket.SOCK_STREAM).

HOST will hold IRC server domain, PORT 6667 will almost always work, and set NICK to something you desire. 

After that we will use s.connect((HOST, PORT)) to prepare for data sending.

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = 'irc.libera.chat' #irc server
PORT = 6667 #port
NICK = 'YourNick'

s.connect((HOST, PORT))

First we will send NICK data finishing with '\r\n'. Sure, we will encode commands with .encode() method.

Same stuff with USER command. IRC is weird one, yes you need 3 "usernames" and one "real name". 

Read more about why at SO excellent link.

After that, we will JOIN #programming channel in this case. Don't forget encoding.

nick_data = ('NICK ' + NICK + '\r\n')
s.send(nick_data.encode())

usernam_data= ('USER YourNick1 YourNick2 YourNick3 :YourNick4 \r\n')
s.send(usernam_data.encode())

s.send('JOIN #programming \r\n'.encode()) #channel

With "while True" we will constantly check for incoming traffic to catch IRC server PING request. Because it's a must to respond with PONG.

Decode incoming stuff as UTF-8, and print results (chat). If PING is at the start of the stream, send same string with PONG. Encode it.

while True:
    result = s.recv(1024).decode('utf-8')
    print(result)

Just use 4 characters after PING (result[0:4) to grab what we need to return back.

 if result[0:4] == "PING":
        s.send(("PONG" + result[4:] + "\r\n").encode())

If length of the received message from IRC server is 0, than probably theres problem with connection so we will just break from script.

 if len(result) == 0:
        break        

Full script:  

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = 'irc.libera.chat' #irc server
PORT = 6667 #port
NICK = 'YourNick'

s.connect((HOST, PORT))

nick_data = ('NICK ' + NICK + '\r\n')
s.send(nick_data.encode())

usernam_data= ('USER YourNick1 YourNick2 YourNick3 :YourNick4 \r\n')
s.send(usernam_data.encode())

s.send('JOIN #programming \r\n'.encode()) #channel
while True:
    result = s.recv(1024).decode('utf-8')
    print(result)

    if result[0:4] == "PING":
        s.send(("PONG" + result[4:] + "\r\n").encode())

    if len(result) == 0:
        break        
        

Learn More:

Free Python Programming Course
Python Examples
Python How To
Python Modules 

YouTube WebDevPro Tutorials

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...