-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmoztnbot.py
executable file
·265 lines (224 loc) · 7.26 KB
/
moztnbot.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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
#!/usr/bin/python
# -*- coding:utf-8 -*-
# Please do not use tab for indentation, use 2 spaces instead !
import sys, os.path
import socket
import string
import threading
import time
import json
import random
import time
import chardet
import codecs
import re
html_begin = '''<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>MozTn IRC log file</title>
<style type="text/css">
h3 { text-align: center }
body { background: #f0f0f0; }
body .time { color: #007020; display: inline-block; width: 75px; vertical-align: top; }
body .nick { color: #062873; font-weight: bold;display: inline-block; vertical-align: middle; width: 130px;vertical-align: top; }
body .msg { display: inline-block; width: 80%; }
</style>
</head>
<body>
'''
os.chdir(os.path.realpath(os.path.dirname(sys.argv[0]))) #using relative path
class Message:
message = ''
def __init__(self, message):
self.message = message
def GetCmd():
return
def contains(self,word, sensitive = True):
if(sensitive == False):
upperMessage = self.message.upper()
upperWord = word.upper()
return upperMessage.find(upperWord) != -1
return self.message.find(word) != -1
def GetMsg(self):
msg = self.message[self.message.find('PRIVMSG'):]
msg = msg[msg.find(':')+1:]
msg = msg[:msg.find('\r')]
return msg
def GetUname(self):
return self.message[self.message.find(':')+1:self.message.find('!')]
def GetChannel(self):
if(self.contains('INVITE')):
return self.message[self.message.find('#'):self.message.find('\r')]
elif(self.contains('PRIVMSG')):
msg = self.message[self.message.find('#'):]
return msg[:msg.find(':')-1]
def printMsg(self):
time = getTime()
uname = self.GetUname()
msg = self.GetMsg()
if(len(msg) is not 0):
print time+' @'+uname+': '+msg
def log(self):
directory='log/'+time.strftime("%Y",time.localtime())+'/'+time.strftime("%b",time.localtime())
if not os.path.isdir(directory):
os.makedirs(directory)
date = getDate()
channel = self.GetChannel().replace('#','')
fname = directory+'/'+channel+'-'+date+'.log.html'
t = getTime()
uname = self.GetUname()
msg = self.GetMsg()
if(not os.path.exists(fname)):
f = open(fname,'a')
f.write(html_begin)
f.write(' <h3>========================%s========================</h3>\n'%date)
f.close()
if(len(msg) is not 0):
f = open(fname,'a')
content = ' <p>'+'<span class="time">'+t+'</span> <span class="nick"><'+uname+'> : </span> <span class="msg">'+msg+'</span></p>\n'
f.write(content.encode('utf-8'))
f.close()
def pushLog(self):
try:
directory='log/'+time.strftime("%Y",time.localtime())+'/'+time.strftime("%b",time.localtime())
date = getDate()
channel = self.GetChannel().replace('#','')
fname = directory+'/'+channel+'-'+date+'.log.html'
return 'http://irc.mozilla-tunisia.org/'+fname
except:
return None
#Config
config = {}
configfile = 'config.json'
#Messages :
msgs = {}
msgfile = 'msgs.json'
#Server info :
linkname = ''
# Main Socket
s=socket.socket()
def init():
loadConfig()
loadMsgs()
def Connect():
s.connect((config['host'], config['port']))
s.send("NICK %s\r\n" % config['nick'])
s.send("USER %s %s bla :%s\r\n" % (config['ident'], config['host'], config['realname']))
def loadJson(fname):
try:
f = open(fname, 'r')
fcontent = f.readlines()
content = json.loads(''.join(fcontent))
f.close()
except:
f = open("/var/log/moztnbot.log", "a")
f.write('failed to open %s \n' %fname)
f.close()
return content
def loadConfig():
global config
config = loadJson(configfile)
def loadMsgs():
global msgs
msgs = loadJson(msgfile)
def joinChannel(msg):
channel = Message(msg).GetChannel()
s.send("JOIN %s\r\n" % channel)
def isRegistered(uname):
s.send("WHOIS %s\r\n" % uname)
buff = s.recv(1024)
if(buff.find('is a registered nick') != -1):
return True
return False
def RandMentionResponse():
n = random.randrange(1,len(msgs)+1)
return msgs[str(n)]
def getTime():
localtime=time.strftime("%H:%M:%S", time.localtime())
return localtime
def getDate():
lt = time.localtime()
date = '%s-%s-%s' %(lt.tm_year, lt.tm_mon, lt.tm_mday)
return date
def getBug(msg):
obj = re.search('.*?([b|B][u|U][g|G]).*?(\d+)', msg)
if(obj):
bugNumber = obj.group(2)
url = 'https://bugzilla.mozilla.org/show_bug.cgi?id=%s' %bugNumber
return url
else:
return None
def decodeMsg(msg):
charsets = ['utf-8', chardet.detect(msg)['encoding']]
decodedMsg = None
for c in charsets:
try:
decodedMsg = codecs.decode(msg, c)
except UnicodeDecodeError as e:
pass
if (decodedMsg is not None):
print "Yes ! decoded with {} @ {}.".format(c, charsets.index(c))
return decodedMsg
return codecs.decode(msg, 'utf-8', 'ignore')
def MakeAction(msg):
message = Message(msg)
message.printMsg()
if(message.contains('PRIVMSG')):
message.log()
if(message.contains('hello') or message.contains('Hello')):
s.send("PRIVMSG %s :Hello %s :) How are you ? How can I help you ?\r\n" % (message.GetChannel(),message.GetUname()))
return
if(message.contains(config['nick'])):
s.send("PRIVMSG %s :%s, %s\r\n" % (message.GetChannel(),message.GetUname(),RandMentionResponse()))
s.send("PRIVMSG %s :%s, %s\r\n" % (message.GetChannel(),message.GetUname(),"Type \x02!help\x02 to learn more."))
if(message.contains('!help')):
s.send("PRIVMSG %s :%s, Sorry, my master is too lasy to implement this :( you can maybe help on %s ?\r\n" % (message.GetChannel(),message.GetUname(), config['wiki']))
if(message.contains('!log')):
url = message.pushLog()
if(url is not None):
s.send("PRIVMSG %s :%s you can find the log here : %s\r\n" % (message.GetChannel(),message.GetUname(),url))
else:
s.send("PRIVMSG %s :%s Sorry unable to get log please contact my master\r\n" % (message.GetChannel(), message.GetUname()))
if(message.contains('INVITE')):
hostUser = message.GetUname()
if(hostUser == config['master'] and isRegistered(hostUser)):
joinChannel(msg)
else:
s.send("PRIVMSG %s :%s Sorry you are not my master.You can't invite me !\r\n" % (message.GetUname(), message.GetUname()))
if(message.contains('bug')):
url = getBug(message.GetMsg())
if(url):
s.send('PRIVMSG %s :%s\r\n' % (message.GetChannel(), url))
def getLinkname():
buff = s.recv(1024)
global linkname
linkname = buff[buff.find(':')+1:buff.find(' ')]
def main_loop():
readbuffer = ""
while 1:
readbuffer=readbuffer+s.recv(1024)
temp=string.split(readbuffer, "\n")
readbuffer=temp.pop()
print temp
if(temp[0].find(linkname) is -1):
try:
res = decodeMsg(temp[0])
if(res is not None):
MakeAction(res)
else:
raise Exception, 'Unable to decode'
except Exception as e:
f = open("/var/log/moztnbot.log", "a")
f.write('[Decoding Error]: %s\n' % e)
f.close()
for line in temp:
line=string.rstrip(line)
line=string.split(line)
if(line[0]=="PING"):
s.send("PONG %s\r\n" % line[1])
if __name__ == '__main__':
init()
Connect()
getLinkname()
main_loop()