0
# IRC
1
2
A comprehensive Python library for Internet Relay Chat (IRC) protocol implementation. The IRC package provides both synchronous and asynchronous client implementations with full event-driven architecture, enabling developers to create IRC clients, bots, and servers with support for modern IRC features including IRCv3, CTCP, DCC, and server capabilities detection.
3
4
## Package Information
5
6
- **Package Name**: irc
7
- **Language**: Python
8
- **Installation**: `pip install irc`
9
10
## Core Imports
11
12
```python
13
import irc.client
14
import irc.bot
15
```
16
17
For synchronous IRC clients:
18
19
```python
20
from irc.client import Reactor, SimpleIRCClient, ServerConnection
21
```
22
23
For asynchronous IRC clients:
24
25
```python
26
from irc.client_aio import AioReactor, AioSimpleIRCClient, AioConnection
27
```
28
29
For bot framework:
30
31
```python
32
from irc.bot import SingleServerIRCBot, ServerSpec
33
```
34
35
## Basic Usage
36
37
### Simple IRC Client
38
39
```python
40
import irc.client
41
42
def on_connect(connection, event):
43
connection.join("#test")
44
45
def on_join(connection, event):
46
connection.privmsg("#test", "Hello IRC!")
47
48
def on_pubmsg(connection, event):
49
print(f"<{event.source.nick}> {event.arguments[0]}")
50
51
client = irc.client.SimpleIRCClient()
52
client.connect("irc.libera.chat", 6667, "mybot")
53
client.connection.add_global_handler("welcome", on_connect)
54
client.connection.add_global_handler("join", on_join)
55
client.connection.add_global_handler("pubmsg", on_pubmsg)
56
client.start()
57
```
58
59
### IRC Bot
60
61
```python
62
from irc.bot import SingleServerIRCBot
63
64
class TestBot(SingleServerIRCBot):
65
def __init__(self, channels, nickname, server, port=6667):
66
spec = [{"host": server, "port": port}]
67
super().__init__(spec, nickname, nickname)
68
self.channels = channels
69
70
def on_welcome(self, connection, event):
71
for channel in self.channels:
72
connection.join(channel)
73
74
def on_pubmsg(self, connection, event):
75
message = event.arguments[0]
76
if message.startswith("!hello"):
77
connection.privmsg(event.target, f"Hello {event.source.nick}!")
78
79
bot = TestBot(["#test"], "mybot", "irc.libera.chat")
80
bot.start()
81
```
82
83
### Asyncio IRC Client
84
85
```python
86
import asyncio
87
from irc.client_aio import AioSimpleIRCClient
88
89
async def main():
90
client = AioSimpleIRCClient()
91
92
def on_connect(connection, event):
93
connection.join("#test")
94
95
def on_pubmsg(connection, event):
96
print(f"<{event.source.nick}> {event.arguments[0]}")
97
98
client.connection.add_global_handler("welcome", on_connect)
99
client.connection.add_global_handler("pubmsg", on_pubmsg)
100
101
await client.connect("irc.libera.chat", 6667, "mybot")
102
# Client runs in background, process events as needed
103
104
asyncio.run(main())
105
```
106
107
## Architecture
108
109
The IRC package follows an event-driven architecture with these core components:
110
111
- **Reactor**: Central event loop managing connections and dispatching events
112
- **ServerConnection**: Individual IRC server connection handling protocol communication
113
- **Event System**: Comprehensive event handling with prioritized handlers
114
- **Bot Framework**: High-level abstractions for building IRC bots with channel management
115
- **Protocol Support**: CTCP, DCC, IRCv3 features, and server capability detection
116
117
The library supports both traditional callback-based programming and modern asyncio/await patterns, making it suitable for both simple scripts and complex applications.
118
119
## Capabilities
120
121
### Synchronous IRC Client
122
123
Core IRC client functionality using traditional socket connections with select-based event processing. Provides ServerConnection for protocol communication and Reactor for event management.
124
125
```python { .api }
126
class Reactor:
127
def __init__(self, on_connect=None, on_disconnect=None): ...
128
def server(self) -> ServerConnection: ...
129
def process_forever(self, timeout=0.2): ...
130
def add_global_handler(self, event: str, handler, priority: int = 0): ...
131
132
class ServerConnection:
133
def connect(self, server: str, port: int, nickname: str, password: str = None,
134
username: str = None, ircname: str = None, **kwargs): ...
135
def join(self, channel: str, key: str = ""): ...
136
def privmsg(self, target: str, text: str): ...
137
def quit(self, message: str = ""): ...
138
139
class SimpleIRCClient:
140
def connect(self, server: str, port: int, nickname: str, **kwargs): ...
141
def start(self): ...
142
```
143
144
[Synchronous Client](./synchronous-client.md)
145
146
### Asynchronous IRC Client
147
148
Asyncio-based IRC client implementation providing full async/await support for modern Python applications. Uses asyncio protocols for non-blocking network communication.
149
150
```python { .api }
151
class AioReactor:
152
def __init__(self, on_connect=None, on_disconnect=None, loop=None): ...
153
def server(self) -> AioConnection: ...
154
async def process_forever(self): ...
155
156
class AioConnection:
157
async def connect(self, server: str, port: int, nickname: str, **kwargs): ...
158
def join(self, channel: str, key: str = ""): ...
159
def privmsg(self, target: str, text: str): ...
160
161
class AioSimpleIRCClient:
162
async def connect(self, server: str, port: int, nickname: str, **kwargs): ...
163
```
164
165
[Asynchronous Client](./asynchronous-client.md)
166
167
### Bot Framework
168
169
High-level IRC bot framework with automatic reconnection, channel management, and common bot functionality. Provides SingleServerIRCBot base class for easy bot development.
170
171
```python { .api }
172
class SingleServerIRCBot:
173
def __init__(self, server_list, nickname: str, realname: str, **kwargs): ...
174
def start(self): ...
175
def die(self, msg: str = "Bye, cruel world!"): ...
176
def jump_server(self, msg: str = "Changing servers"): ...
177
178
class Channel:
179
def users(self) -> list: ...
180
def is_oper(self, nick: str) -> bool: ...
181
def is_voiced(self, nick: str) -> bool: ...
182
def set_mode(self, mode: str, value=None): ...
183
184
class ServerSpec:
185
def __init__(self, host: str, port: int = 6667, password: str = None): ...
186
```
187
188
[Bot Framework](./bot-framework.md)
189
190
### Event System
191
192
Comprehensive event handling system supporting all IRC protocol events, custom handlers with priorities, and extensible event processing for advanced applications.
193
194
```python { .api }
195
class Event:
196
def __init__(self, type: str, source, target, arguments: list = None, tags: list = None): ...
197
198
def add_global_handler(event: str, handler, priority: int = 0): ...
199
def remove_global_handler(event: str, handler): ...
200
201
# Event types available
202
protocol_events = [
203
"error", "join", "kick", "mode", "part", "ping", "privmsg",
204
"privnotice", "pubmsg", "pubnotice", "quit", "invite", "pong",
205
"action", "topic", "nick"
206
]
207
```
208
209
[Event System](./event-system.md)
210
211
### Protocol Extensions
212
213
Support for IRC protocol extensions including CTCP (Client-To-Client Protocol), DCC (Direct Client-to-Client), IRCv3 message tags, and server capability detection.
214
215
```python { .api }
216
# CTCP support
217
def dequote(message: str) -> list: ...
218
219
# DCC connections
220
class DCCConnection:
221
def connect(self, address: tuple, port: int): ...
222
def listen(self, addr=None): ...
223
def send_bytes(self, bytes: bytes): ...
224
225
# Server features
226
class FeatureSet:
227
def set(self, name: str, value=True): ...
228
def load(self, arguments: list): ...
229
```
230
231
[Protocol Extensions](./protocol-extensions.md)
232
233
### Connection Management
234
235
Connection factories, SSL support, IPv6 compatibility, rate limiting, and automatic ping/pong handling for robust IRC connections.
236
237
```python { .api }
238
class Factory:
239
def __init__(self, bind_address=None, wrapper=None, ipv6: bool = False): ...
240
def connect(self, server_address: tuple): ...
241
242
def set_rate_limit(self, frequency: float): ...
243
def set_keepalive(self, interval: int): ...
244
```
245
246
[Connection Management](./connection-management.md)
247
248
### Utilities and Helpers
249
250
IRC-specific string handling, nickname parsing, channel detection, mode parsing, and scheduling utilities for IRC applications.
251
252
```python { .api }
253
class NickMask:
254
@property
255
def nick(self) -> str: ...
256
@property
257
def user(self) -> str: ...
258
@property
259
def host(self) -> str: ...
260
261
def is_channel(string: str) -> bool: ...
262
def parse_nick_modes(mode_string: str) -> list: ...
263
def parse_channel_modes(mode_string: str) -> list: ...
264
265
class IRCDict(dict):
266
# Case-insensitive dictionary using IRC rules
267
pass
268
269
class DefaultScheduler:
270
def execute_every(self, period, func): ...
271
def execute_at(self, when, func): ...
272
def execute_after(self, delay, func): ...
273
```
274
275
[Utilities](./utilities.md)
276
277
## Types
278
279
```python { .api }
280
class IRCError(Exception):
281
"""Base IRC exception class."""
282
pass
283
284
class ServerConnectionError(IRCError):
285
"""Server connection error."""
286
pass
287
288
class ServerNotConnectedError(ServerConnectionError):
289
"""Server not connected error."""
290
pass
291
292
class InvalidCharacters(ValueError):
293
"""Invalid characters in IRC message."""
294
pass
295
296
class MessageTooLong(ValueError):
297
"""IRC message exceeds length limits."""
298
pass
299
300
class DCCConnectionError(IRCError):
301
"""DCC connection error."""
302
pass
303
304
class PrioritizedHandler:
305
priority: int
306
callback: callable
307
308
class Event:
309
type: str
310
source: NickMask
311
target: str
312
arguments: list
313
tags: list
314
```