How to Build an IRC Bot with Python
Build a small Python IRC bot that connects to TwistedNET over verified TLS, joins one channel and responds to !hello. The example uses the Python standard library and works with Python 3.11 or later.
Before you run it
- Pick an unused nickname for your bot and a test channel you control. Ask the channel operators before adding a bot to an existing channel.
- Open TwistedNET Web Chat or connect with an IRC client so you can send the test command.
- Use
irc.twistednet.orgon port6697for TLS. See the IRC security guide for more on certificate verification and SASL.
How an IRC bot connects
IRC sends lines of text that end with a carriage return and a line feed (\r\n). TLS protects those lines in transit. A TCP read can contain part of a line or several lines, so the example reads complete lines before decoding or parsing them.
- Open a TLS connection and verify the certificate against the server hostname.
- Send
NICKandUSERto register the session. - Answer the server’s
PINGwithPONG, using the same token. The server can send a ping before registration finishes. - Wait for numeric
001, then sendJOINfor your test channel. - Watch for a
PRIVMSGaddressed to that channel. When someone types!hello, reply in the channel.
For example, :alex!user@host PRIVMSG #example :!hello contains a sender prefix, a command, a target and the message text. See the IRC commands reference and the IRC client protocol reference for more message formats and numerics.
Save the bot as bot.py
import os
import socket
import ssl
import time
SERVER = "irc.twistednet.org"
PORT = 6697
def send_line(connection, message):
line = message.encode("utf-8") + b"\r\n"
if len(line) > 512 or any(mark in message for mark in ("\r", "\n", "\0")):
raise ValueError("Invalid IRC message")
connection.sendall(line)
def parse_line(line):
prefix = ""
if line.startswith(":"):
prefix, _, line = line[1:].partition(" ")
command, _, arguments = line.partition(" ")
return prefix, command.upper(), arguments
def run_bot(irc, nick, channel):
send_line(irc, f"NICK {nick}")
send_line(irc, f"USER {nick} 0 * :TwistedNET Python example bot")
registered = False
last_reply = float("-inf")
with irc.makefile("rb") as incoming:
while raw_line := incoming.readline(513):
if len(raw_line) > 512 or not raw_line.endswith(b"\r\n"):
raise ConnectionError("Invalid line received from the IRC server")
line = raw_line[:-2].decode("utf-8", errors="replace")
prefix, command, arguments = parse_line(line)
if command == "PING":
send_line(irc, f"PONG {arguments}")
elif command == "001" and not registered:
send_line(irc, f"JOIN {channel}")
registered = True
print(f"Registered as {nick}. Requested to join {channel}.", flush=True)
elif command == "433" and not registered:
raise ConnectionError("Nickname in use. Choose a different IRC_NICK.")
elif command == "ERROR":
raise ConnectionError("The IRC server closed the connection.")
elif registered and command == "PRIVMSG":
target, _, message = arguments.partition(" :")
sender = prefix.partition("!")[0]
now = time.monotonic()
if target == channel and message.strip() == "!hello" and sender:
if now - last_reply >= 2:
send_line(irc, f"PRIVMSG {channel} :Hello, {sender}!")
last_reply = now
raise ConnectionError("The IRC connection ended.")
def main():
nick = os.environ.get("IRC_NICK", "")
channel = os.environ.get("IRC_CHANNEL", "")
if not nick or not channel.startswith("#") or len(channel) == 1:
raise SystemExit("Set IRC_NICK and IRC_CHANNEL before running the bot.")
if any(char.isspace() or char in ",:\0" for char in nick + channel):
raise SystemExit("Use a single nickname and a single channel without spaces.")
context = ssl.create_default_context()
with socket.create_connection((SERVER, PORT), timeout=15) as tcp:
with context.wrap_socket(tcp, server_hostname=SERVER) as irc:
irc.settimeout(300)
run_bot(irc, nick, channel)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
pass
except (OSError, ValueError) as error:
raise SystemExit(f"IRC bot stopped: {error}") from error
Run and test it
Replace the sample nickname and channel before running this command in your shell.
IRC_NICK=MyPythonBot IRC_CHANNEL='#your-test-channel' python3 bot.py
Once your IRC client shows the bot in the channel, type !hello. You should see a reply such as Hello, alex!. The example sends at most one reply every two seconds and prints connection status without recording chat messages. Press Ctrl+C to stop it.
Troubleshoot common failures
- Nickname in use. Numeric
433means the nickname is taken. Choose a differentIRC_NICKand restart. - Certificate verification failed. Check the server name, your system clock and your trusted CA certificates. Keep certificate verification enabled.
- Connected but missing from the channel. Check the channel name and its join requirements using your regular client. An invite-only or registered-users-only channel may reject
JOIN. This example uses guest registration. - Bot joined but did not reply. Send exactly
!helloin the configured channel. Use the same spelling for the channel in your configuration and wait two seconds between tests.
Keep the bot running on Linux
After testing, you can let systemd restart the bot when the connection drops. Use an existing unprivileged service account named ircbot, place the tested script at /opt/ircbot/bot.py with read access for that account, and adapt this unit to your paths and IRC settings.
[Unit]
Description=TwistedNET Python IRC bot
Wants=network-online.target
After=network-online.target
[Service]
User=ircbot
WorkingDirectory=/opt/ircbot
Environment="IRC_NICK=MyPythonBot"
Environment="IRC_CHANNEL=#your-test-channel"
ExecStart=/usr/bin/python3 /opt/ircbot/bot.py
Restart=on-failure
RestartSec=30
[Install]
WantedBy=multi-user.target
Save it as /etc/systemd/system/ircbot.service. Run sudo systemctl daemon-reload, then sudo systemctl enable --now ircbot. Check startup and reconnects with journalctl -u ircbot -f. The restart delay reduces repeated connection attempts during an outage.
Extend the bot
Try adding a small command such as !about. Ask the channel operators about bot etiquette, keep replies rate-limited and get consent before recording messages. If you need a registered nickname, start with the IRC services guide and use a client library that supports SASL.