-
Notifications
You must be signed in to change notification settings - Fork 1
/
connect.py
executable file
·98 lines (79 loc) · 3 KB
/
connect.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
from socket import socket, AF_INET, SOCK_STREAM
class ConnectionClosed(Exception):
"""Raised when we receive an empty string from the IRC server, indicating
that the connection with the server has been closed.
"""
pass
class IRCConn:
"""
This class handles the connection with the IRC server.
It connects and sends and receives messages.
"""
MAX_MSG_LEN = 10000 # maximum length of any message received from IRC server
# (TODO: find a non-arbitrary value for this)
def __init__(self, bot):
self._bot = bot
self._id = bot.ident
self._port = 6667
def connect(self):
self._sock = socket(AF_INET, SOCK_STREAM)
self._sock.connect((self._id.host, self._port))
self._send('USER {} {} {} :{}'.format(self._id.ident, self._id.host, self._id.serv, self._id.name))
self.nick(self._id.nick)
# wait until we have received the MOTD in full before proceeding
def join(self, chan):
self._send('JOIN {}'.format(chan))
def part(self, chan):
self._send('PART {}'.format(chan))
def topic(self, chan, new=None):
self._send('TOPIC {} {}'.format(chan, new or ''))
def _send(self, msg):
"""Send something (anything) to the IRC server."""
print('sending: {}\r\n'.format(msg))
self._sock.send('{}\r\n'.format(msg).encode())
def say(self, msg, chan, to=None):
"""say(msg, chan): Say msg on chan."""
prefix = '' if to is None else '{}: '.format(to)
for line in msg.splitlines():
self._send('{} {} :{}{}'.format('PRIVMSG', chan, prefix, line))
def pong(self, trail):
self._send('{} {}'.format('PONG', trail))
def nick(self, new):
self._send('NICK {}'.format(new))
self._nick = new
def receive(self):
"""
Read from the socket until we reach the end of an IRC message.
Attempt to decode the message and return it.
Call handle_encoing_error() if unsuccessful.
"""
buf = []
while buf[-2:] != [b'\r', b'\n']:
c = self._sock.recv(1)
if not c:
raise ConnectionClosed
buf.append(c)
try:
line = b''.join(buf).decode()
except (UnicodeError):
self.handle_encoding_error()
return ''
print('received:', line)
return line
def mainloop(self):
while True:
line = None
while line is None:
try:
line = self.receive()
except ConnectionClosed:
self.handle_connection_closed()
self._bot.parse(line)
def handle_connection_closed(self):
print('connection closed; reconnecting')
self.connect()
def handle_encoding_error(self):
print('encoding error encountered.')
def handle_error(self, tokens):
print('error. tokens:', tokens)
self.connect()