Очередной коммит. Стараюсь пофиксить баги.
[nia.git] / nia.py
blob73a42db60d2a3a177d5c376a35d765efa8e53b6b
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 '''
4 Nia - бот написаный на Python.
5 Разработчик - apkawa@gmail.com
7 Лицензия - GPLv3
8 '''
9 from jaconn import bot
11 import re
12 from random import randint
13 import urllib
14 from simplejson import loads
15 from xml.sax.saxutils import unescape
18 class Nia(bot):
19 def LOG(self, conf, nick, body):
20 if self.logging:
21 from nia_sql import sql
22 s = sql()
23 body = re.sub('\'','',body)
24 self.DEBUG(body)
25 s.write(conf, nick, body)
27 def nia_help(self,args):
28 '''Lists of possible functions'''
29 if args:
30 if self.commands.has_key(args):
31 halp = self.commands[args].__doc__
32 elif self.admin_commands.has_key(args):
33 halp = self.admin_commands[args].__doc__
34 else:
35 halp = 'Nyaaa? This command does not...'
36 else:
37 halp ='''List of functions
38 User command: %s
39 Master command: %s
41 Type help <command> to learn more
42 '''%(self.help['com'],self.help['admin'])
43 self.send(halp)
45 def nia_tr(self,args):
46 '''Usage: tr <from lang> <to lang> <text>
47 Example: tr en ja Hello world!
48 Translated text into another language.
49 en - English
50 ru - Russian
51 ja - Japan
52 ko - Korean
53 de - German
54 fr - French
55 it - Italian
56 es - Spanish
57 et - Estonian
58 hi - Hindi
59 '''
61 tmp = re.findall('([\w]{2})[\s]*?([\w]{2})[\s]*?(.*?)$',args)
62 if tmp:
63 tmp = tmp[0]
64 from_l, to_l, word = tmp[0],tmp[1],tmp[2]
65 self.send( translated(word, to_l, from_l))
66 else: self.send( 'Nyaa? Bad request...')
67 def nia_say(self,args):
68 '''Usage: say <text>
69 Send a message on behalf Bot'''
70 self.send( args)
71 def nia_show(self,args):
72 '''Usage: show http://example.com/image.jpg
73 Show a picture to chat. Works only in Gajim.'''
74 if re.search('http://',args):
75 text = self.XMLescape(args)
76 extra = '<a href="%s"><img src="%s"/></a>'%(text,text)
77 self.send(False, text, extra)
78 else:
79 self.send( 'Nyaaa? This does not link...')
81 def nia_google(self, args):
82 '''Search in google.com'''
83 flag, text, extra = google(args,'web')
84 self.send(text, extra, flag)
85 def nia_enwiki(self, args):
86 '''Search in en.wikipedia.org'''
87 flag, text, extra = google('site:http://en.wikipedia.org %s'%args,'web')
88 def nia_ruwiki(self, args):
89 '''Search in http://ru.wikipedia.org'''
90 flag, text, extra = google('site:http://ru.wikipedia.org %s'%args,'web')
91 self.send(text, extra, flag)
92 def nia_wa(self, args):
93 '''Search in world-art.ru'''
94 flag, text, extra = google('site:http://www.world-art.ru %s'%args,'web')
95 self.send(text, extra, flag)
96 def nia_adb(self, args):
97 '''Search in anidb.info'''
98 flag, text, extra = google('site:http://anidb.info %s'%args,'web')
99 self.send(text, extra, flag)
100 def nia_lurk(self, args):
101 '''Search in lurkmore.ru'''
102 flag, text, extra = google('site:http://lurkmore.ru/ %s'%args,'web')
103 self.send(text, extra, flag)
104 def nia_gpic(self, args):
105 '''Usage: gpic <word>
106 Find a picture in google.com and show to chat. Works only in Gajim.'''
107 flag, text, extra = google(args,'images')
108 self.send(text, extra, flag)
110 def nia_alias(self, args):
111 '''Usage: alias <cmd> = '<command, arguments>'
112 Set alias'''
113 tmp = re.findall('^(.*?)(?:[\s]{0,})=(?:[\s]{0,})\'(.*)\'',args)
114 if tmp:
115 tmp = tmp[0]
116 if not self.commands.has_key(tmp[0]) and not self.alias.has_key(tmp[0]) and not self.alias.has_key(tmp[0]):
117 self.alias[tmp[0]] = tmp[1]
118 mess = 'Set alias %s = %s'%(tmp[0],tmp[1])
119 else:
120 mess = 'Nyaaa... Name alias should not overlap with existing commands and alias.'
121 else:
122 mess = 'Nyaaa... Invalid syntax. Type "help alias".'
123 self.send(mess)
125 def nia_rmalias(self,args):
126 '''Usage: rmalias <alias>
127 Remove alias'''
128 if self.alias.has_key(args):
129 del self.alias[args]
130 def nia_lsalias(self,args):
131 '''Usage: lsalias
132 List all alias'''
133 self.send('List alias:\n%s'%'\n'.join(['%s = %s'%(i,self.alias[i]) for i in self.alias]))
137 def nia_version(self,args):
138 '''Usage: version [|<Nick>]'''
139 nick = self.nick
140 conf = '%s@%s'%(nick.getNode(),nick.getDomain())
141 self.toversion = ''
142 args = re.findall('^(.*?)(?:|[\s])$',args)[0]
143 if not args:
144 to = nick
145 else:
146 to = '%s/%s'%(conf,args)
147 self.send_iq('get',to)
149 def admin_join(self,nick,conf):
150 '''Usage: join example@conference.example.com
151 Go to room bot'''
152 if not conf in self.CONFS:
153 self.CONFS.append(conf)
154 self.join_room((conf,))
155 else: pass
157 def admin_leave(self,nick,conf):
158 '''Usage: leave example@conference.example.com
159 Exit the room. Without arguments - to emerge from the current room.'''
160 if not conf:
161 conf = '%s@%s'%(nick.getNode(),nick.getDomain())
162 to = '%s/%s'%(conf,self.NICK)
163 self.send_system(to,'offline','unavailable')
164 if self.CONFS.count(conf):
165 self.CONFS.remove(conf)
167 def admin_joined(self,nick,conf):
168 '''Usage: joined
169 Show the list of rooms in which the bot.'''
170 self.send(' '.join(self.CONFS))
172 def admin_ignore(self,nick,user):
173 '''Usage: ignore <user>
174 Ignore bot user.'''
175 user = '%s/%s'%(self.to,user)
176 if self.type_f or (user in self.ignore):
177 self.ignore.append(user)
178 return False
180 def admin_noignore(self,nick,user):
181 '''Usage: noignore <user>
182 Remove from user ignore'''
183 for i in xrange(self.ignore.count(user)):
184 self.ignore.remove(user)
186 def admin_lsignore(self,nick,user):
187 '''Usage: lsignore
188 Show list ignored users'''
189 self.send(' '.join(self.ignore))
191 def admin_savecfg(self,nick,args):
192 '''Usage: savecfg
193 Save current configuration'''
194 self.config(True,self.CONFS,self.ignore)
196 def _admin_restart(self,nick,args):
197 '''Перезапустить бота.'''
198 print 'restarting'
199 self.leave_room(self.CONFS)
200 os.spawnl(os.P_NOWAIT, 'python', 'python' ,'nia.py')
202 def admin_exit(self,nick,args):
203 '''Usage: exit
204 Poweroff bot.'''
205 sys.exit()
209 def google(word,type):
210 def web(results):
211 if results:
212 url = urllib.unquote(results[0]['url'])
213 title1 = results[0]['titleNoFormatting']
214 title2 = results[0]['title']
215 content = re.sub('(<b>)|(</b>)','',results[0]['content'])
216 text = '%s\n%s\n%s'%(title1,content,url)
217 text = re.sub('&#39;','\'',unescape(text))
218 #print text
220 extra = '''<a href="%s">%s</a>
221 <p>%s</p>
222 '''%(url,title2,content)
223 return True, text, extra
224 else: return True, 'Nyaaa... Ничего не нашла.', ''
225 def images(results):
226 if results:
227 imgurl = results[randint(0,len(results)-1)]['unescapedUrl']
228 extra = '<a href="%s"><img src="%s"/></a>'%(imgurl,imgurl)
229 return False,imgurl, extra
230 else: return True, 'Nyaaa... Ничего не нашла.', ''
231 #http://code.google.com/apis/ajaxsearch/documentation/reference.html#_intro_fonje
232 word = urllib.quote(word.encode('utf-8'))
233 src = urllib.urlopen('http://ajax.googleapis.com/ajax/services/search/%s?v=1.0&q=%s&hl=ru'%(type,word)).read()
234 convert = loads(src)
235 results = convert['responseData']['results']
236 if type == 'web':
237 return web(results)
238 if type == 'images':
239 return images(results)
242 def translated(word, to_l, from_l=None):
243 '''Usage: tr <from lang> <to lang> <text>
244 Example: tr en ja Hello world!
245 Translated text into another language.
246 en - English
247 ru - Russian
248 uk - Ukrainian
249 ja - Japan
250 zn - Chinese
251 ko - Korean
252 de - German
253 fr - French
254 it - Italian
255 es - Spanish
256 et - Estonian
257 hi - Hindi
258 sa - Sanskrit
260 google_lang = {\
261 'AFRIKAANS' : 'af', 'ALBANIAN' : 'sq', 'AMHARIC' : 'am',
262 'ARABIC' : 'ar', 'ARMENIAN' : 'hy', 'AZERBAIJANI' : 'az',
263 'BASQUE' : 'eu', 'BELARUSIAN' : 'be', 'BENGALI' : 'bn',
264 'BIHARI' : 'bh', 'BULGARIAN' : 'bg', 'BURMESE' : 'my',
265 'CATALAN' : 'ca', 'CHEROKEE' : 'chr',
266 'CHINESE' : 'zh', 'CHINESE_SIMPLIFIED' : 'zh-CN', 'CHINESE_TRADITIONAL' : 'zh-TW',
267 'CROATIAN' : 'hr', 'CZECH' : 'cs', 'DANISH' : 'da',
268 'DHIVEHI' : 'dv', 'DUTCH': 'nl', 'ENGLISH' : 'en',
269 'ESPERANTO' : 'eo', 'ESTONIAN' : 'et', 'FILIPINO' : 'tl',
270 'FINNISH' : 'fi', 'FRENCH' : 'fr', 'GALICIAN' : 'gl',
271 'GEORGIAN' : 'ka', 'GERMAN' : 'de', 'GREEK' : 'el',
272 'GUARANI' : 'gn', 'GUJARATI' : 'gu', 'HEBREW' : 'iw',
273 'HINDI' : 'hi', 'HUNGARIAN' : 'hu', 'ICELANDIC' : 'is',
274 'INDONESIAN' : 'id', 'INUKTITUT' : 'iu', 'ITALIAN' : 'it',
275 'JAPANESE' : 'ja', 'KANNADA' : 'kn', 'KAZAKH' : 'kk',
276 'KHMER' : 'km', 'KOREAN' : 'ko', 'KURDISH': 'ku',
277 'KYRGYZ': 'ky', 'LAOTHIAN': 'lo', 'LATVIAN' : 'lv',
278 'LITHUANIAN' : 'lt', 'MACEDONIAN' : 'mk', 'MALAY' : 'ms',
279 'MALAYALAM' : 'ml', 'MALTESE' : 'mt', 'MARATHI' : 'mr',
280 'MONGOLIAN' : 'mn', 'NEPALI' : 'ne', 'NORWEGIAN' : 'no',
281 'ORIYA' : 'or', 'PASHTO' : 'ps', 'PERSIAN' : 'fa',
282 'POLISH' : 'pl', 'PORTUGUESE' : 'pt-PT', 'PUNJABI' : 'pa',
283 'ROMANIAN' : 'ro', 'RUSSIAN' : 'ru', 'SANSKRIT' : 'sa',
284 'SERBIAN' : 'sr', 'SINDHI' : 'sd', 'SINHALESE' : 'si',
285 'SLOVAK' : 'sk', 'SLOVENIAN' : 'sl', 'SPANISH' : 'es',
286 'SWAHILI' : 'sw', 'SWEDISH' : 'sv', 'TAJIK' : 'tg',
287 'TAMIL' : 'ta', 'TAGALOG' : 'tl', 'TELUGU' : 'te',
288 'THAI' : 'th', 'TIBETAN' : 'bo', 'TURKISH' : 'tr',
289 'UKRAINIAN' : 'uk', 'URDU' : 'ur', 'UZBEK' : 'uz',
290 'UIGHUR' : 'ug', 'VIETNAMESE' : 'vi'
292 def transl(o_word, from_l, to_l):
293 word = urllib.quote(o_word.encode('utf-8'))
294 url = 'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=%s&langpair=%s%%7C%s'%(word, from_l, to_l)
295 src = urllib.urlopen(url).read()
296 convert = loads(src)
297 status = convert['responseStatus']
298 #print status, type(status), convert
299 if status == 200:
300 results = convert['responseData']['translatedText']
301 return results
302 else: return o_word
303 def detect_lang(word):
304 word = urllib.quote(word.encode('utf-8'))
305 url = 'http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=%s'%word
306 src = urllib.urlopen(url).read()
307 convert = loads(src)
308 results = convert['responseData']['language']
309 #print results
310 return results
312 transl = transl(word, from_l, to_l)
313 return transl
314 #http://code.google.com/apis/ajaxlanguage/documentation/reference.html#_fonje_detect
317 if __name__ == '__main__':
318 nia = Nia()
319 nia.online()
322 некоторые идеи были взяты из:
323 http://paste.org.ru/?ffxty8
324 http://paste.org.ru/?9iuvw2
325 http://wiki.wjsullivan.net/collaboration.cgi/SnakeBot