-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocketbot.py
executable file
·82 lines (71 loc) · 1.85 KB
/
socketbot.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
#!/usr/bin/python2
import irclib
import socket
import threading
import os
import os.path
import signal
import sys
import config
# Constants
socketdir = 'channels'
class ClientHandler(threading.Thread):
def __init__(self, sock, addr):
super( ClientHandler, self).__init__()
self.sock = sock
self.addr = addr
def run(self):
line = self.sock.recv(1024)
while line:
server.privmsg(os.path.basename(self.sock.getsockname()), line)
line = self.sock.recv(1024)
class SocketListener(threading.Thread):
def __init__(self, ssock):
super( SocketListener, self ).__init__()
self.daemon = True
self.ssock = ssock
def run(self):
while True:
sock, addr = self.ssock.accept()
ClientHandler(sock, addr).start()
def init_sockets(channels):
sockets = {}
try:
os.makedirs(socketdir)
except OSError:
# Maybe in the future we really need to check for writability and such
pass
for channel in channels:
path = os.path.join(socketdir, channel)
try:
os.remove(path)
except OSError:
# We really should just continue
pass
# Create a unix socket and bind to it
s = socket.socket(socket.AF_UNIX)
s.bind(path)
# Start the listeners
s.listen(1)
SocketListener(s).start()
sockets[channel] = s
return sockets
def init_server(network, port, nick, ircname, channels):
server = irc.server()
server.connect(network, port, nick, ircname)
for channel in channels:
server.join(channel)
return server
if __name__ == '__main__':
irc = irclib.IRC()
# Get channel -> unix socket dict
sockets = init_sockets(config.channels)
# Join the server
server = init_server(config.network, config.port, config.nick, config.name, config.channels)
# Before we start looping, make a signal handler
def shutdown(signal, frame):
server.disconnect()
sys.exit(0)
signal.signal(signal.SIGINT, shutdown)
# Jump into an infinite loop
irc.process_forever()