Close Menu
TechBeamersTechBeamers
    TechBeamersTechBeamers
    • Python
    • Java
    • C
    • SQL
    • MySQL
    • Selenium
    • Testing
    • Agile
    • Linux
    • WebDev
    • Technology
    TechBeamersTechBeamers
    Python Examples

    Learn to Build an IRC Bot in Python

    By Meenakshi AgarwalUpdated:Nov 05, 2023No Comments4 Mins Read
    Share
    Facebook Twitter LinkedIn Pinterest Email

    In this tutorial, you’ll learn to use Python 3 for creating an IRC bot. IRC is an acronym for Internet Relay Chat which is a popular form of communication to send text messages over the network.

    How to Use Python to Build an IRC Bot?

    • What is an IRC Bot?
    • What can a Bot do?
    • How to Implement IRC Bot in Python?
    • Bot Source Code
    Python IRC Bot Client

    What is an IRC Bot?

    A bot is a virtual assistant that emulates a real user to provide instant responses. IRC bot is a type of network client that could be a script or a program that can relay messages using the IRC protocol.

    When any active user receives a text from the IRC bot, it appears to him as another real user. Many programming languages like Python and Java aid in developing IRC bots.

    What can a Bot do?

    The bots mimic a real user and communicate with other active clients. However, they can perform a variety of tasks:

    • Archive chat messages
    • Can parse Twitter feeds
    • Crawl the web for a keyword
    • Run any command if needed.

    How to Implement IRC Bot in Python?

    For this, we’ll need a Python program that creates a client socket to connect to the IRC server. The IRC server performs a simple verification and connects without much hassle.

    The script uses the Python socket library to allow network communication. Check the below sample code.

    import socket
    
    ircbot = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    The IRC protocol is just a layer above the IP protocol and works over the TCP/IP stack.

    We’ll need our program to exchange the following set of commands.

    ** Authetication **** USER botname botname botname: text
                          NICK botname
                          NICKSERV IDENTIFY botnickpass botpass
    ** Join Channel  **** JOIN

    Bot Source Code

    Find the Python code of the IRC bot in the below section.

    See also  Python Sorting a Dictionary

    Class File:

    First, you need to create an IRC bot class. Copy the below code paste it into a file and save it as the irc_class.py.

    import socket
    import sys
    import time
    
    class IRC:
     
        irc = socket.socket()
      
        def __init__(self):
            # Define the socket
            self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     
        def send(self, channel, msg):
            # Transfer data
            self.irc.send(bytes("PRIVMSG " + channel + " " + msg + "\n", "UTF-8"))
     
        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\n", "UTF-8"))
            self.irc.send(bytes("NICK " + botnick + "\n", "UTF-8"))
            self.irc.send(bytes("NICKSERV IDENTIFY " + botnickpass + " " + botpass + "\n", "UTF-8"))
            time.sleep(5)
    
            # join the channel
            self.irc.send(bytes("JOIN " + channel + "\n", "UTF-8"))
     
        def get_response(self):
            time.sleep(1)
            # Get the response
            resp = self.irc.recv(2040).decode("UTF-8")
     
            if resp.find('PING') != -1:                      
                self.irc.send(bytes('PONG ' + resp.split().decode("UTF-8") [1] + '\r\n', "UTF-8")) 
     
            return resp

    After creating the network communication class, we’ll import it into our client and use its instance. We are designing a demo client so that you can understand it easily.

    Our bot will send the "Hello!" message while responding to a "Hello" message on the channel.

    Also Read: A simple IRC bot built in Java

    Client Script:

    Below is the Python IRC Bot program to start the client communication. Create a new file, copy the code, paste it, and save it as irc_bot.py.

    IRC server usually runs on ports like 6667 or 6697 (IRC with SSL). So, we’ll be using “6667” in our sample. Also, you will need to provide a valid IRC Server IP address or hostname to make this program run correctly.

    from irc_class import *
    import os
    import random
    
    ## IRC Config
    server = "10.x.x.10" # Provide a valid server IP/Hostname
    port = 6697
    channel = "#python"
    botnick = "techbeamers"
    botnickpass = "guido"
    botpass = "<%= @guido_password %>"
    irc = IRC()
    irc.connect(server, port, channel, botnick, botpass, botnickpass)
    
    while True:
        text = irc.get_response()
        print(text)
     
        if "PRIVMSG" in text and channel in text and "hello" in text:
            irc.send(channel, "Hello!")

    Please note that you can run the above program using the following command:

    python irc_bot.py

    Hope, the above tutorial could help you build a more complex IRC bot with more features and usage.

    See also  How to Check Python Version Using Code

    If you wish to learn Python programming from scratch, then read this Python tutorial.

    Previous ArticleDecorators in Python
    Next Article Python String Formatting Methods
    Meenakshi Agarwal

    I'm Meenakshi Agarwal, founder of TechBeamers.com, with 10+ years of experience in Software development, testing, and automation. Proficient in Python, Java, Selenium, SQL, & C-Sharp, I create tutorials, quizzes, exercises and interview questions on diverse tech topics. Follow my tutorials for valuable insights!

    Add A Comment

    Leave A Reply Cancel Reply

    Python Coding Exercises for Beginners
    • 40 Python Exercises for Beginners
    • 6 Python Data Class Exercises
    • 100+ Python Interview Questions for 2024
    • 20 Python Programs to Print Patterns
    Python Basic Tutorials
    • Python Keyword
    • Python Statement
    • Python Comment
    • Python Data Types
    • Python String Methods
    • Python Multiline Strings
    • Python Split Strings
    • Python Slice Strings
    • Iterate Strings in Python
    • Python String Format
    • Python String Concatenation
    • Python Permutations of a String
    • Python Numbers
    • Python List
    • Python List Reverse
    • Python List Slice
    • Python Nested List
    • Python Set
    • Python Tuple
    • Python Dictionary
    • Python Dict to JSON
    • Python Dictionary Examples
    • Python OrderedDict
    • Python Arrays
    • Python Generate SubArrays
    • Python Heapq (Heap queue)
    • Python Operators
    • Python XOR Operator
    • Operator Precedence
    • Python Namespace
    • Python For Loop
    • Python While Loop
    • Python If Else
    • Python Switch Case
    • Python Function
    • Higher Order Functions in Python
    • Python Class
    • Python Class Definition
    • Python Data Class
    • Python Inheritance
    • Python Multiple Inheritance
    • Python Static Method
    • File Handling in Python
    • Python Copy File
    • Python Exception Handling
    • Python Try Except
    • Python Lambda
    • Python Generator
    • Python Module
    Python Pandas in Action
    • Rename Columns using Pandas
    • Python Pandas to Read CSV Files
    • Python Pandas to Merge CSV Files
    • Python Dictionary to DataFrame
    • Python Find Length of List
    Python Important Functions
    • Python Glob()
    • Python Range()
    • Python Float Range()
    • Python Map()
    • Python Filter()
    • Python Enumerate()
    • Python Zip()
    • Python Join()
    • Python Ord()
    Python Advanced Tutorials
    • Python Multithreading
    • Python Socket Programming
    • Selenium Python
    • Python Unittest
    • Python Time Module
    • Python Datetime
    • Python IRC
    • PyLint in Python
    • Python Random Number
    • Python MongoDB
    • Python Pickle
    Python Code Examples
    • Python List Contains Elements
    • Python Search Dictionary by Value
    • Python Check Type of Variable
    • Python Check Version Using Code
    • Python Loop Through Files
    • Compare Strings in Python
    • Replace Strings in Python
    • Size of Integer in Python
    • Simple Socket in Python
    • Threaded Socket in Python
    Python Tips & Tricks
    • 30 Essential Python Tips
    • 10 Python Coding Tips
    • 12 Python Code Optimization Tips
    • 10 Python Programming Mistakes
    Python General Topics
    • Top 10 Python IDEs
    • Top 7 Python Interpreters
    • Top 7 Websites for Python
    • Top 5 Chrome Plugin for Python
    Python Quizzes - General
    • Python Quiz-1
    • Python Quiz-2
    • Python Quiz-3
    • Python Quiz-4
    Python Quizzes - Advanced
    • Python Quiz - Data Structures
    • Python Quiz - Threads
    • Python Quiz - DA
    Python MCQ - Strings
    • Python MCQ Strings-1
    • Python MCQ Strings-2
    Python MCQ - Classes `
    • Python MCQ Classes-1
    • Python MCQ Classes-2
    Python MCQ - Functions
    • Python MCQ Functions-1
    • Python MCQ Functions-2
    Python MCQ - File I/O
    • Python MCQ File I/O-1
    • Python MCQ File I/O-2
    Latest Posts
    • 30 Python Programming Questions On List, Tuple, and Dictionary
    • 4 Different Ways to Rename Columns in Pandas
    • 4 Unique Ways to Reverse a String in Python
    • 40 Google Interview Questions You Need to Join Google in 2023
    • 40 Python Exercises for Beginners
    • 44 Python Data Analyst Interview Questions
    • 7 Websites to Learn Python Programming

    Subscribe to Updates

    Get the latest tutorials from TechBeamers.

    Loading
    • About
    • Contact
    • Disclaimer
    • Privacy Policy
    • Terms of Use
    © 2023 TechBeamers. All Rights Reserved.

    Type above and press Enter to search. Press Esc to cancel.