/
ircbot.py
214 lines (169 loc) · 6.94 KB
/
ircbot.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
#!/usr/bin/python
"""
Author: Technux
website: http://www.technux.se
mail: support@technux.se
"""
import argparse
import os
import socket
import sys
import threading
import time
import ConfigParser
try:
import redmine_interface
REDMINE_MAX_RESULTS = 15
redmine_enabled = True
except ImportError as ie:
print "Redmine support modules not loaded (reason: %s)" % ie
print "'pip install python-redmine' prerequisite to enable Redmine support"
redmine_enabled = False
SOCKET_IRC = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connected_to_irc = False
def bot_setup(config_dict):
""" bot_setup() - Setup basic stuffs like nick and what channel to join"""
global connected_to_irc
technux_bot_name = config_dict['technux_bot']
SOCKET_IRC.connect((config_dict['ircserver'], 6667))
SOCKET_IRC.send("USER " + technux_bot_name + " " + technux_bot_name +
" " + technux_bot_name + " :" +
config_dict['realname'] + "\n")
SOCKET_IRC.send("NICK %s\n" % (technux_bot_name))
# Authenticate with NICKSERV if nick is registred
if config_dict['passwd']:
SOCKET_IRC.send("PRIVMSG NICKSERV :IDENTIFY %s\n" %
(config_dict['passwd']))
SOCKET_IRC.send("JOIN %s\n" % config_dict['channel'])
connected_to_irc = True
def keep_alive(msg):
""" keep_alive() - If the ircserver pings us, make sure to respond"""
if msg.find("PING :") != -1:
SOCKET_IRC.send("PONG :alive\n")
return False
return True
def send_msg(channel, nickname, msg):
""" send_msg() - Send a PRIVMSG message to channel or channel + nick"""
if nickname == "":
SOCKET_IRC.send("PRIVMSG %s : %s\n" % (channel, msg))
else:
SOCKET_IRC.send("PRIVMSG %s :%s: %s\n" % (channel, nickname, msg))
def send_priv_msg(nickname, msg):
""" send_priv_msg() - Send PRIVMSG message to nick """
SOCKET_IRC.send("PRIVMSG %s :%s\n" % (nickname, msg))
def usage(channel, nick, usagemsg):
""" usage() - Print usage for the bot"""
send_msg(channel, nick, usagemsg)
def parse_nick(msg):
""" parse_nick() - Parse nickname from irc msg log"""
return msg.split('!')[0][1:]
def leave_irc_network():
""" leave_irc_network() - Gracefully disconnect from IRC server"""
global connected_to_irc
if connected_to_irc is True:
print "Sending quit"
SOCKET_IRC.send("QUIT")
def handle_msg(ircmsg, config_dict):
""" handle_msg() - parse and handle an irc msg"""
if ircmsg.find("Hello %s" % config_dict['technux_bot']) != -1:
nick = parse_nick(ircmsg)
send_msg(config_dict['channel'], nick, config_dict['greeting'])
elif ircmsg.find("%s: help" % (config_dict['technux_bot'])) != -1:
nick = parse_nick(ircmsg)
usage(config_dict['channel'], nick, config_dict['usagemsg'])
elif ircmsg.find("%s: info" % (config_dict['technux_bot'])) != -1:
nick = parse_nick(ircmsg)
send_msg(config_dict['channel'], nick, config_dict['info'])
elif ircmsg.find("%s: redmine" % (config_dict['technux_bot'])) != -1:
nick = parse_nick(ircmsg)
if redmine_enabled is False:
send_msg(config_dict['channel'], nick,
"Redmine commands not enabled")
else:
index = ircmsg.find("%s: redmine" % (config_dict['technux_bot']))
cmd = ircmsg[index:].split()
res = redmine_interface.parse_command(cmd[2:])
if len(res) > REDMINE_MAX_RESULTS:
tmpmsg = "More than %d results, only sending first %d" % \
(REDMINE_MAX_RESULTS, REDMINE_MAX_RESULTS)
send_priv_msg(nick, tmpmsg)
res = res[:REDMINE_MAX_RESULTS]
for r in res:
for line in r.strip().split('\n'):
send_priv_msg(nick, line)
time.sleep(0.5) # avoid flooding the IRC server
def _main():
global redmine_enabled
parser = argparse.ArgumentParser()
parser.add_argument(
'-c', '--conf', help='specify path to custom config file')
args = parser.parse_args()
if args.conf:
if os.path.isfile(args.conf):
conf_file = args.conf
else:
print "Specified config file %s not found!" % args.conf
exit(64)
if not os.access(conf_file, os.R_OK):
print "Can't read %s!" % conf_file
exit(65)
else:
conf_file = "%s/conf/bot.conf" % os.path.dirname(
os.path.abspath(__file__))
print "Using config file %s" % conf_file
config = ConfigParser.ConfigParser()
config_dict = {}
if config.read(conf_file):
config_dict['channel'] = config.get('settings', 'channel')
config_dict['technux_bot'] = config.get('settings', 'botname')
config_dict['realname'] = config.get('settings', 'realname')
config_dict['ircserver'] = config.get('settings', 'server')
logfile = config.get('settings', 'logfile')
config_dict['passwd'] = config.get('settings', 'passwd')
config_dict['greeting'] = config.get('text', 'greeting')
config_dict['usagemsg'] = config.get('text', 'usage')
config_dict['info'] = config.get('text', 'info')
redmine_url = config.get('redmine', 'url')
redmine_trackers = config.get('redmine', 'trackers')
else:
print "ERROR: %s could not be found!" % (conf_file)
sys.exit(66)
if redmine_enabled is True and redmine_url is not "":
redmine_interface.setup(redmine_url, redmine_trackers.split(','))
else:
print "Redmine url not specified. " \
"Support for redmine commands disabled"
redmine_enabled = False
try:
bot_setup(config_dict)
# If logfile is set, redirect console printouts to logfile
if logfile:
sys.stdout = open(logfile, 'w')
# variables frequently accessed below
channel = config_dict['channel']
technux_bot = config_dict['technux_bot']
while True:
ircmsg = SOCKET_IRC.recv(2048)
ircmsg = ircmsg.strip('\n\r') # Remove linebreaks
print(ircmsg) # Log irc msg to console or file
# messages from the IRC server
if keep_alive(ircmsg) is False:
continue
# don't start a thread unless the msg is directed
# to the bot by a nick
if (ircmsg.find("PRIVMSG %s :%s: " %
(channel, technux_bot)) != -1) \
or (ircmsg.find("PRIVMSG %s :Hello %s" %
(channel, technux_bot)) != -1):
t = threading.Thread(target=handle_msg,
args=(ircmsg, config_dict))
t.start()
except KeyboardInterrupt:
print "\n\n'Ctrl + C' detected"
except socket.gaierror as (err, msg):
print err
print msg
leave_irc_network()
print "Exiting"
if __name__ == "__main__":
_main()