清除无用的语句;修正一处笔误
[gaetalk.git] / gaetalk.py
blob7e523cbe10f5182c9752b7ce2174f2f4c8bfe811
1 #!/usr/bin/env python2
2 # vim:fileencoding=utf-8
4 import re
5 import logging
6 import datetime
8 from google.appengine.ext import db
9 from google.appengine.api import xmpp
11 import utils
12 import config
14 helpre = re.compile(r'^\W{0,2}help$')
16 #用户所有资源离线时,会加上“完全”二字
17 OFFLINE = u'离线'
18 AWAY = u'离开'
19 XAWAY = u'离开'
20 BUSY = u'忙碌'
21 ONLINE = u'在线'
22 CHAT = u'和我说话吧'
24 NEW = u'加入'
25 LEAVE = u'退出'
26 NICK = u'昵称更改 (%s -> %s)'
27 SNOOZE = u'snooze %ds'
28 BLACK = u'禁言 %s %ds'
29 BLACK_AUTO = u'被禁言 %ds'
30 KICK = u'删除 %s (%s)'
31 ADMIN = u'%s 成为管理员 (by %s)'
32 UNADMIN = u'%s 不再是管理员 (by %s)'
33 NOTICE = u'通告:%s'
34 BLOCK = u'封禁 %s,原因:%s'
35 UNBLOCK = u'解封 %s'
37 STATUS_CODE = {
38 '': ONLINE,
39 'away': AWAY,
40 'dnd': BUSY,
41 'xa': XAWAY,
42 'chat': CHAT,
45 #状态的排序顺序
46 STATUS_LIST = [CHAT, ONLINE, AWAY, XAWAY, BUSY, OFFLINE]
48 timezone = datetime.timedelta(hours=config.timezoneoffset)
50 class User(db.Model):
51 jid = db.StringProperty(required=True, indexed=True)
52 nick = db.StringProperty(required=True, indexed=True)
54 add_date = db.DateTimeProperty(auto_now_add=True)
55 last_online_date = db.DateTimeProperty()
56 last_offline_date = db.DateTimeProperty()
57 last_speak_date = db.DateTimeProperty()
59 msg_count = db.IntegerProperty(required=True, default=0)
60 msg_chars = db.IntegerProperty(required=True, default=0)
61 credit = db.IntegerProperty(required=True, default=0)
63 black_before = db.DateTimeProperty(auto_now_add=True)
64 snooze_before = db.DateTimeProperty()
65 flooding_point = db.IntegerProperty(default=0)
67 avail = db.StringProperty(required=True)
68 is_admin = db.BooleanProperty(required=True, default=False)
69 resources = db.StringListProperty(required=True)
70 #允许他人私信?
71 reject_pm = db.BooleanProperty(default=False)
73 prefix = db.StringProperty(required=True, default=config.default_prefix)
74 nick_pattern = db.StringProperty(required=True, default='[%s]')
75 nick_changed = db.BooleanProperty(required=True, default=False)
76 intro = db.StringProperty()
78 class Log(db.Model):
79 time = db.DateTimeProperty(auto_now_add=True, indexed=True)
80 msg = db.StringProperty(required=True, multiline=True)
81 jid = db.StringProperty()
82 nick = db.StringProperty()
83 type = db.StringProperty(required=True, indexed=True,
84 choices=set(['chat', 'member', 'admin', 'misc']))
86 class Group(db.Model):
87 time = db.DateTimeProperty(auto_now_add=True)
88 topic = db.StringProperty(multiline=True)
89 status = db.StringProperty()
91 class BlockedUser(db.Model):
92 jid = db.StringProperty(required=True, indexed=True)
93 add_date = db.DateTimeProperty(auto_now_add=True)
94 reason = db.StringProperty()
96 def log_msg(sender, msg):
97 l = Log(jid=sender.jid, nick=sender.nick,
98 type='chat', msg=msg)
99 l.put()
101 def log_onoff(sender, action, resource=''):
102 if resource:
103 if action == OFFLINE and not sender.resources:
104 msg = u'完全%s (%s)' % (action, resource)
105 else:
106 msg = '%s (%s)' % (action, resource)
107 else:
108 msg = action
109 l = Log(jid=sender.jid, nick=sender.nick,
110 type='member', msg=msg)
111 l.put()
113 def log_admin(sender, action):
114 l = Log(jid=sender.jid, nick=sender.nick,
115 type='admin', msg=action)
116 l.put()
118 def get_user_by_jid(jid):
119 return User.gql('where jid = :1', jid.lower()).get()
121 def get_user_by_nick(nick):
122 return User.gql('where nick = :1', nick).get()
124 def get_group_info():
125 return Group.all().get()
127 def get_blocked_user(jid):
128 return BlockedUser.gql('where jid = :1', jid.lower()).get()
130 def get_member_list():
131 r = []
132 now = datetime.datetime.now()
133 #一个查询中最多只能有一个不等比较
134 l = User.gql('where avail != :1', OFFLINE)
135 for u in l:
136 r.append(u)
137 return [unicode(x.jid) for x in r \
138 if x.snooze_before is None or x.snooze_before < now]
140 def send_to_all_except(jid, message):
141 if isinstance(jid, str):
142 jids = [x for x in get_member_list() if x != jid]
143 else:
144 jids = [x for x in get_member_list() if x not in jid]
145 logging.debug(jid)
146 logging.debug(jids)
147 try:
148 xmpp.send_message(jids, message)
149 except xmpp.InvalidJidError:
150 pass
152 def send_to_all(message):
153 jids = get_member_list()
154 xmpp.send_message(jids, message)
156 def send_status(jid):
157 u = get_blocked_user(jid)
158 if u is not None:
159 xmpp.send_presence(jid, status=u'您已经被本群封禁')
160 return
162 grp = get_group_info()
163 if grp is None or not grp.status:
164 xmpp.send_presence(jid)
165 else:
166 xmpp.send_presence(jid, status=grp.status)
168 def handle_message(msg):
169 jid = msg.sender.split('/')[0]
170 sender = get_blocked_user(jid)
171 if sender is not None:
172 msg.reply(u'您已经被本群封禁,原因为 %s。' % sender.reason)
173 return
174 sender = get_user_by_jid(jid)
175 if sender is None:
176 msg.reply('很抱歉,出错了,请尝试更改状态或者重新添加好友。')
177 return
178 if msg.body.startswith('?OTR:'):
179 msg.reply('不支持 OTR 加密!')
180 return
181 if msg.body in config.blocked_away_messages:
182 msg.reply('系统认为您的客户端正在自动发送离开消息。如果您认为这并不正确,请向管理员反馈。')
183 return
184 if len(msg.body) > 500:
185 msg.reply('由于技术限制,每条消息最长为 500 字。大段文本请贴 paste 网站。\m'
186 '如 http://paste.ubuntu.org.cn/ http://slexy.org/')
187 return
188 if sender.is_admin or sender.jid == config.root:
189 ch = AdminCommand(msg, sender)
190 else:
191 ch = BasicCommand(msg, sender)
192 if not ch.handled:
193 now = datetime.datetime.now()
194 if sender.black_before is not None \
195 and sender.black_before > now:
196 if (datetime.datetime.today()+timezone).date() == \
197 (sender.black_before+timezone).date():
198 format = '%H时%M分%S秒'
199 else:
200 format = '%m月%d日 %H时%M分%S秒'
201 msg.reply('你已被禁言至 ' \
202 + (sender.black_before+timezone).strftime(format))
203 return
205 if sender.last_speak_date is not None:
206 d = now - sender.last_speak_date
207 t = d.seconds
208 if d.days > 0 or t > 60:
209 sender.flooding_point = 0
210 else:
211 k = 1000 / (t * t + 1)
212 if k > 0:
213 sender.flooding_point += k
214 else:
215 sender.flooding_point = 0
217 k = sender.flooding_point / 1500
218 if k > 0:
219 msg.reply('刷屏啊?禁言 %d 分钟!' % k)
220 send_to_all_except(sender.jid,
221 (u'%s 已因刷屏而被禁言 %d 分钟。' % (sender.nick, k)) \
222 .encode('utf-8'))
223 log_onoff(sender, BLACK_AUTO % (60 * k))
224 sender.black_before = now + datetime.timedelta(seconds=60*k)
225 sender.put()
226 return
228 sender.last_speak_date = now
229 sender.snooze_before = None
230 try:
231 sender.msg_count += 1
232 sender.msg_chars += len(msg.body)
233 except TypeError:
234 sender.msg_count = 1
235 sender.msg_chars = len(msg.body)
236 sender.put()
237 body = utils.removelinks(msg.body)
238 for u in User.gql('where avail != :1', OFFLINE):
239 if u.snooze_before is not None and u.snooze_before >= now:
240 continue
241 if u.jid == sender.jid:
242 continue
243 try:
244 message = '%s %s' % (
245 u.nick_pattern % sender.nick,
246 body
248 xmpp.send_message(u.jid, message)
249 except xmpp.InvalidJidError:
250 pass
251 log_msg(sender, msg.body)
253 def try_add_user(jid, show=OFFLINE, resource=''):
254 '''使用 memcache 作为锁添加用户'''
255 u = get_blocked_user(jid)
256 if u is not None:
257 xmpp.send_message(jid, u'您已经被本群封禁,原因为 %s。' % u.reason)
258 return
260 L = utils.MemLock('add_user')
261 L.require()
262 try:
263 u = get_user_by_jid(jid)
264 if u is not None:
265 return
266 u = add_user(jid, show, resource)
267 finally:
268 L.release()
269 if show != OFFLINE:
270 log_onoff(u, show, resource)
271 logging.info(u'%s added', jid)
273 def add_user(jid, show=OFFLINE, resource=''):
274 '''resource 在 presence type 为 available 里使用'''
275 nick = jid.split('@')[0]
276 old = get_user_by_nick(nick)
277 while old:
278 nick += '_'
279 old = get_user_by_nick(nick)
280 u = User(jid=jid.lower(), avail=show, nick=nick)
281 if show != OFFLINE:
282 u.last_online_date = datetime.datetime.now()
283 if resource:
284 u.resources.append(resource)
285 u.put()
286 log_onoff(u, NEW)
287 logging.info(u'%s 已经加入' % jid)
288 send_status(jid)
289 xmpp.send_message(jid, u'欢迎 %s 加入!要获取使用帮助,请输入 %shelp,要获知群主题,请输入 %stopic。' % (
290 u.nick, u.prefix, u.prefix))
291 return u
293 def del_user(jid, by_cmd=False):
294 l = User.gql('where jid = :1', jid.lower())
295 for u in l:
296 if u.jid == config.root:
297 xmpp.send_message(jid, u'root 用户:离开前请确定你已做好善后工作!')
298 log_onoff(u, LEAVE)
299 if by_cmd:
300 logging.info(u'%s (%s) 已经离开 (通过使用命令)' % (u.nick, u.jid))
301 else:
302 logging.info(u'%s (%s) 已经离开' % (u.nick, u.jid))
303 u.delete()
305 class BasicCommand:
306 handled = True
307 def __init__(self, msg, sender):
308 self.sender = sender
309 self.msg = msg
311 if helpre.match(msg.body):
312 self.do_help()
313 elif msg.body.startswith(sender.prefix):
314 cmd = msg.body[len(sender.prefix):].split()
315 try:
316 handle = getattr(self, 'do_' + cmd[0])
317 except AttributeError:
318 msg.reply(u'错误:未知命令 %s' % cmd[0])
319 except IndexError:
320 msg.reply(u'错误:无命令')
321 except UnicodeEncodeError:
322 msg.reply(u'错误:命令名解码失败。此问题在 GAE 升级其 Python 到 3.x 后方能解决。')
323 else:
324 handle(cmd[1:])
325 logging.debug('%s did command %s' % (sender.jid, cmd[0]))
326 else:
327 self.handled = False
329 def do_online(self, args):
330 '''在线成员列表。可带一个参数,指定在名字中出现的一个子串。'''
331 r = []
332 pat = args[0] if args else None
333 now = datetime.datetime.now()
334 l = User.gql('where avail != :1', OFFLINE)
335 for u in l:
336 m = u.nick
337 if pat and m.find(pat) == -1:
338 continue
339 status = u.avail
340 if status != u'在线':
341 m += u' (%s)' % status
342 if u.snooze_before is not None and u.snooze_before > now:
343 m += u' (snoozing)'
344 if u.black_before is not None and u.black_before > now:
345 m += u' (已禁言)'
346 r.append(unicode('* ' + m))
347 r.sort()
348 n = len(r)
349 if pat:
350 r.insert(0, u'在线成员列表(包含子串 %s):' % pat)
351 r.append(u'共 %d 人。' % n)
352 else:
353 r.insert(0, u'在线成员列表:')
354 r.append(u'共 %d 人在线。' % n)
355 self.msg.reply(u'\n'.join(r).encode('utf-8'))
357 def do_lsadmin(self, args):
358 '''管理员列表'''
359 r = []
360 now = datetime.datetime.now()
361 l = User.gql('where is_admin = :1', True)
362 for u in l:
363 m = u.nick
364 status = u.avail
365 if status != u'在线':
366 m += u' (%s)' % status
367 if u.snooze_before is not None and u.snooze_before > now:
368 m += u' (snoozing)'
369 if u.black_before is not None and u.black_before > now:
370 m += u' (已禁言)'
371 r.append(unicode('* ' + m))
372 r.sort()
373 n = len(r)
374 r.insert(0, u'管理员列表:')
375 r.append(u'共 %d 位管理员。' % n)
376 self.msg.reply(u'\n'.join(r).encode('utf-8'))
378 def do_lsblocked(self, args):
379 '''列出被封禁用户名单'''
380 r = []
381 l = BlockedUser.all()
382 for u in l:
383 r.append(unicode('* %s (%s, %s)' % (u.jid,
384 utils.strftime(u.add_date, timezone),
385 u.reason)
388 r.sort()
389 n = len(r)
390 r.insert(0, u'封禁列表:')
391 r.append(u'共 %d 个 JID 被封禁。' % n)
392 self.msg.reply(u'\n'.join(r).encode('utf-8'))
394 def do_chatty(self, args):
395 '''消息数排行'''
396 r = []
397 for u in User.gql('ORDER BY msg_chars ASC'):
398 m = u.nick
399 m = u'* %s:\t%5d条,共 %s' % (
400 u.nick, u.msg_count,
401 utils.filesize(u.msg_chars))
402 r.append(m)
403 n = len(r)
404 r.insert(0, u'消息数量排行:')
405 r.append(u'共 %d 人。' % n)
406 self.msg.reply(u'\n'.join(r).encode('utf-8'))
408 def do_nick(self, args):
409 '''更改昵称,需要一个参数,不能使用大部分标点符号'''
410 if len(args) != 1:
411 self.msg.reply('错误:请给出你想到的昵称(不能包含空格)')
412 return
414 q = get_user_by_nick(args[0])
415 if q is not None:
416 self.msg.reply('错误:该昵称已被使用,请使用其它昵称')
417 elif not utils.checkNick(args[0]):
418 self.msg.reply('错误:非法的昵称')
419 else:
420 if not config.nick_can_change and self.sender.nick_changed:
421 self.msg.reply('乖哦,你已经没机会再改昵称了')
422 return
423 old_nick = self.sender.nick
424 log_onoff(self.sender, NICK % (old_nick, args[0]))
425 self.sender.nick = args[0]
426 self.sender.nick_changed = True
427 self.sender.put()
428 send_to_all_except(self.sender.jid,
429 (u'%s 的昵称改成了 %s' % (old_nick, args[0])).encode('utf-8'))
430 self.msg.reply('昵称更改成功!')
431 do_nick.__doc__ += ',最长 %d 字节' % config.nick_maxlen
433 def do_whois(self, args):
434 '''查看用户信息,参数为用户昵称'''
435 if len(args) != 1:
436 self.msg.reply('错误:你想知道关于谁的信息?')
437 return
439 u = get_user_by_nick(args[0])
440 if u is None:
441 self.msg.reply(u'Sorry,查无此人。')
442 return
444 now = datetime.datetime.now()
445 status = u.avail
446 addtime = (u.add_date + timezone).strftime('%Y年%m月%d日 %H时%M分').decode('utf-8')
447 allowpm = u'否' if u.reject_pm else u'是'
448 if u.snooze_before is not None and u.snooze_before > now:
449 status += u' (snoozing)'
450 if u.black_before is not None and u.black_before > now:
451 status += u' (已禁言)'
452 r = []
453 r.append(u'昵称:\t%s' % u.nick)
454 if self.sender.is_admin:
455 r.append(u'JID:\t%s' % u.jid)
456 r.append(u'状态:\t%s' % status)
457 r.append(u'消息数:\t%d' % u.msg_count)
458 r.append(u'消息总量:\t%s' % utils.filesize(u.msg_chars))
459 r.append(u'加入时间:\t%s' % addtime)
460 r.append(u'接收私信:\t%s' % allowpm)
461 r.append(u'自我介绍:\t%s' % u.intro)
462 self.msg.reply(u'\n'.join(r).encode('utf-8'))
464 def do_help(self, args=()):
465 '''显示本帮助。参数 long 显示详细帮助,也可指定命令名。'''
466 doc = []
467 prefix = self.sender.prefix
469 if len(args) > 1:
470 self.msg.reply('参数错误。')
471 return
472 arg = args[0] if args else None
474 if arg is None or arg == 'long':
475 for b in self.__class__.__bases__ + (self.__class__,):
476 for c, f in b.__dict__.items():
477 if c.startswith('do_'):
478 if arg is None:
479 doc.append(u'%s%s:\t%s' % (prefix, c[3:], f.__doc__.decode('utf-8').split(u',', 1)[0].split(u'。', 1)[0]))
480 else:
481 doc.append(u'%s%s:\t%s' % (prefix, c[3:], f.__doc__.decode('utf-8')))
482 doc.sort()
483 if arg is None:
484 doc.insert(0, u'** 命令指南 **\n(当前命令前缀 %s,可设置。使用 %shelp long 显示详细帮助)' % (prefix, prefix))
485 else:
486 doc.insert(0, u'** 命令指南 **\n(当前命令前缀 %s,可设置)' % prefix)
487 doc.append(u'要离开,直接删掉好友即可。')
488 doc.append(u'Gtalk 客户端用户要离开请使用 quit 命令。')
489 self.msg.reply(u'\n'.join(doc).encode('utf-8'))
490 else:
491 try:
492 handle = getattr(self, 'do_' + arg)
493 except AttributeError:
494 self.msg.reply(u'错误:未知命令 %s' % arg)
495 except UnicodeEncodeError:
496 self.msg.reply(u'错误:命令名解码失败。此问题在 GAE 升级其 Python 到 3.x 后方能解决。')
497 else:
498 self.msg.reply(u'%s%s:\t%s' % (prefix, arg, handle.__doc__.decode('utf-8')))
500 def do_topic(self, args=()):
501 '''查看群主题'''
502 grp = get_group_info()
503 if grp is None or not grp.topic:
504 self.msg.reply(u'没有设置群主题。')
505 else:
506 self.msg.reply(grp.topic)
508 def do_iam(self, args):
509 '''查看自己的信息'''
510 u = self.sender
511 addtime = (u.add_date + timezone).strftime('%Y年%m月%d日 %H时%M分').decode('utf-8')
512 allowpm = u'否' if u.reject_pm else u'是'
513 r = []
514 r.append(u'昵称:\t%s' % u.nick)
515 r.append(u'JID:\t%s' % u.jid)
516 r.append(u'资源:\t%s' % u' '.join(u.resources))
517 r.append(u'消息数:\t%d' % u.msg_count)
518 r.append(u'消息总量:\t%s' % utils.filesize(u.msg_chars))
519 r.append(u'加入时间:\t%s' % addtime)
520 r.append(u'命令前缀:\t%s' % u.prefix)
521 r.append(u'接收私信:\t%s' % allowpm)
522 r.append(u'自我介绍:\t%s' % u.intro)
523 self.msg.reply(u'\n'.join(r).encode('utf-8'))
525 def do_m(self, args):
526 '''发私信,需要昵称和内容两个参数。私信不会以任何方式被记录。用户可使用 set 命令设置是否接收私信。'''
527 if len(args) < 2:
528 self.msg.reply('请给出昵称和内容。')
529 return
531 target = get_user_by_nick(args[0])
532 if target is None:
533 self.msg.reply('Sorry,查无此人。')
534 return
536 if target.reject_pm:
537 self.msg.reply('很抱歉,对方不接收私信。')
538 return
540 msg = self.msg.body[len(self.sender.prefix):].split(None, 2)[-1]
541 msg = u'_私信_ %s %s' % (target.nick_pattern % self.sender.nick, msg)
542 if xmpp.send_message(target.jid, msg) == xmpp.NO_ERROR:
543 self.msg.reply(u'OK')
544 else:
545 self.msg.reply(u'消息发送失败')
547 def do_intro(self, arg):
548 '''设置自我介绍信息'''
549 if not arg:
550 self.msg.reply('请给出自我介绍的内容。')
551 return
553 msg = self.msg.body[len(self.sender.prefix):].split(None, 1)[-1]
554 u = self.sender
555 try:
556 u.intro = msg
557 except db.BadValueError:
558 # 过长文本已在 handle_message 中被拦截
559 self.msg.reply('错误:自我介绍内容只能为一行。')
560 return
562 u.put()
563 send_to_all_except(u.jid,
564 (u'%s 的新自我介绍:%s' % (u.nick, msg)).encode('utf-8'))
565 self.msg.reply(u'设置成功!')
567 def do_snooze(self, args):
568 '''暂停接收消息,参数为时间(默认单位为秒)。再次发送消息时自动清除'''
569 if len(args) != 1:
570 self.msg.reply('你想停止接收消息多久?')
571 return
572 else:
573 try:
574 n = utils.parseTime(args[0])
575 except ValueError:
576 self.msg.reply('Sorry,我无法理解你说的时间。')
577 return
579 try:
580 self.sender.snooze_before = datetime.datetime.now() + datetime.timedelta(seconds=n)
581 except OverflowError:
582 self.msg.reply('Sorry,你不能睡太久。')
583 return
584 self.sender.put()
585 if n == 0:
586 self.msg.reply('你已经醒来。')
587 else:
588 self.msg.reply('OK,停止接收消息 %s。' % utils.displayTime(n))
589 log_onoff(self.sender, SNOOZE % n)
591 def do_offline(self, args):
592 '''假装离线,让程序认为你的所有资源已离线。如在你离线时程序仍认为你在线,请使用此命令。'''
593 del self.sender.resources[:]
594 self.sender.avail = OFFLINE
595 self.sender.last_offline_date = datetime.datetime.now()
596 self.sender.put()
597 self.msg.reply('OK,在下次你说你在线之前我都认为你已离线。')
599 def do_fakeresource(self, args):
600 '''假装在线,人工加入一个新的资源,使程序认为你总是在线。使用 offline 命令可删除所有资源的记录。'''
601 self.sender.resources.append('fakeresouce')
602 self.sender.put()
603 self.msg.reply('OK,你将永远在线。')
605 def do_old(self, args):
606 '''聊天记录查询,可选一个数字参数。默认为最后20条。特殊参数 OFFLINE (不区分大小写)显示离线消息(最多 100 条)'''
607 s = self.sender
608 q = False
609 if not args:
610 q = Log.gql("WHERE type = 'chat' ORDER BY time DESC LIMIT 20")
611 elif len(args) == 1:
612 try:
613 n = int(args[0])
614 if n > 0:
615 q = Log.gql("WHERE type = 'chat' ORDER BY time DESC LIMIT %d" % n)
616 except ValueError:
617 if args[0].upper() == 'OFFLINE':
618 q = Log.gql("WHERE time < :1 AND time > :2 AND type = 'chat' ORDER BY time DESC LIMIT 100", s.last_online_date, s.last_offline_date)
619 else:
620 pass
621 if q is not False:
622 r = []
623 q = list(q)
624 q.reverse()
625 if q:
626 if datetime.datetime.today() - q[0].time > datetime.timedelta(hours=24):
627 show_date = True
628 else:
629 show_date = False
630 for l in q:
631 message = '%s %s %s' % (
632 utils.strftime(l.time, timezone, show_date),
633 s.nick_pattern % l.nick,
634 l.msg
636 r.append(message)
637 if r:
638 self.msg.reply(u'\n'.join(r).encode('utf-8'))
639 else:
640 self.msg.reply('没有符合的聊天记录。')
641 else:
642 self.msg.reply('Oops, 参数不正确哦。')
644 def do_set(self, args):
645 '''设置参数。参数格式 key=value;不带参数以查看说明。'''
646 #注意:选项名/值中不能包含空格
647 if len(args) != 1:
648 doc = []
649 for c, f in self.__class__.__dict__.items():
650 if c.startswith('set_'):
651 doc.append(u'* %s:\t%s' % (c[4:], f.__doc__.decode('utf-8')))
652 for b in self.__class__.__bases__:
653 for c, f in b.__dict__.items():
654 if c.startswith('set_'):
655 doc.append(u'* %s:\t%s' % (c[4:], f.__doc__.decode('utf-8')))
656 doc.sort()
657 doc.insert(0, u'设置选项:')
658 self.msg.reply(u'\n'.join(doc).encode('utf-8'))
659 else:
660 msg = self.msg
661 cmd = msg.body.split(None, 1)[1].split('=', 1)
662 if len(cmd) == 1:
663 msg.reply(u'错误:请给出选项值')
664 return
665 try:
666 handle = getattr(self, 'set_' + cmd[0])
667 except AttributeError:
668 msg.reply(u'错误:未知选项 %s' % cmd[0])
669 except IndexError:
670 msg.reply(u'错误:无选项')
671 except UnicodeEncodeError:
672 msg.reply(u'错误:选项名解码失败。此问题在 GAE 升级其 Python 到 3.x 后方能解决。')
673 else:
674 handle(cmd[1])
676 def do_quit(self, args):
677 '''删除用户数据。某些自称“不作恶”的公司的客户端会不按协议要求发送删除好友的消息,请 gtalk 官方客户端用户使用此命令退出。参见 http://xmpp.org/rfcs/rfc3921.html#rfc.section.6.3 。'''
678 del_user(self.sender.jid)
679 self.msg.reply(u'OK.')
681 def set_prefix(self, arg):
682 '''设置命令前缀'''
683 self.sender.prefix = arg
684 self.sender.put()
685 self.msg.reply(u'设置成功!')
687 def set_nickpattern(self, arg):
688 '''设置昵称显示格式,用 %s 表示昵称的位置'''
689 try:
690 arg % 'test'
691 except (TypeError, ValueError):
692 self.msg.reply(u'错误:不正确的格式')
693 return
695 self.sender.nick_pattern = arg
696 self.sender.put()
697 self.msg.reply(u'设置成功!')
699 def set_allowpm(self, arg):
700 '''设置是否接收私信,参数为 y(接收)或者 n(拒绝)'''
701 if arg not in 'yn':
702 self.msg.reply(u'错误的参数。')
703 return
705 if arg == 'y':
706 self.sender.reject_pm = False
707 else:
708 self.sender.reject_pm = True
709 self.sender.put()
710 self.msg.reply(u'设置成功!')
712 class AdminCommand(BasicCommand):
713 def do_kick(self, args):
714 '''删除某人。他仍可以重新加入。'''
715 if len(args) != 1:
716 self.msg.reply('请给出昵称。')
717 return
719 target = get_user_by_nick(args[0])
720 if target is None:
721 self.msg.reply('Sorry,查无此人。')
722 return
724 if target.jid == config.root:
725 self.msg.reply('不能删除 root 用户')
726 return
728 targetjid = target.jid
729 targetnick = target.nick
730 target.delete()
731 self.msg.reply((u'OK,删除 %s。' % target.nick).encode('utf-8'))
732 send_to_all_except(self.sender.jid, (u'%s 已被删除。' % target.nick) \
733 .encode('utf-8'))
734 xmpp.send_message(targetjid, u'你已被管理员从此群中删除,请删除该好友。')
735 log_admin(self.sender, KICK % (targetnick, targetjid))
737 def do_quiet(self, args):
738 '''禁言某人,参数为昵称和时间(默认单位秒)'''
739 if len(args) != 2:
740 self.msg.reply('请给出昵称和时间。')
741 return
742 else:
743 try:
744 n = utils.parseTime(args[1])
745 except ValueError:
746 self.msg.reply('Sorry,我无法理解你说的时间。')
747 return
749 target = get_user_by_nick(args[0])
750 if target is None:
751 self.msg.reply('Sorry,查无此人。')
752 return
754 target.black_before = datetime.datetime.now() + datetime.timedelta(seconds=n)
755 target.put()
756 self.msg.reply((u'OK,禁言 %s %s。' % (target.nick, utils.displayTime(n))).encode('utf-8'))
757 send_to_all_except((self.sender.jid, target.jid),
758 (u'%s 已被禁言 %s。' % (target.nick, utils.displayTime(n))) \
759 .encode('utf-8'))
760 xmpp.send_message(target.jid, u'你已被管理员禁言 %s。' % utils.displayTime(n))
761 log_admin(self.sender, BLACK % (target.nick, n))
763 def do_notice(self, arg):
764 '''发送群通告。只会发给在线的人,包括 snoozing 者。'''
765 if not arg:
766 self.msg.reply('请给出群通告的内容。')
767 return
769 msg = self.msg.body[len(self.sender.prefix):].split(None, 1)[-1]
771 l = User.gql('where avail != :1', OFFLINE)
772 log_admin(self.sender, NOTICE % msg)
773 for u in l:
774 try:
775 xmpp.send_message(u.jid, u'通告:' + msg)
776 except xmpp.InvalidJidError:
777 pass
779 def do_topic(self, args=()):
780 '''查看或设置群主题'''
781 grp = get_group_info()
782 if not args:
783 if grp is None or not grp.topic:
784 self.msg.reply(u'没有设置群主题。')
785 else:
786 self.msg.reply(grp.topic)
787 else:
788 grp = get_group_info()
789 if grp is None:
790 grp = Group()
791 grp.topic = self.msg.body[len(self.sender.prefix):].split(None, 1)[-1]
792 grp.put()
793 self.msg.reply(u'群主题已更新。')
795 def do_admin(self, args):
796 '''将某人添加为管理员'''
797 if len(args) != 1:
798 self.msg.reply(u'请给出昵称。')
799 return
801 target = get_user_by_nick(args[0])
802 if target is None:
803 self.msg.reply(u'Sorry,查无此人。')
804 return
806 if target.is_admin:
807 self.msg.reply(u'%s 已经是管理员了。' % target.nick)
808 return
810 target.is_admin = True
811 target.put()
812 send_to_all_except(target.jid,
813 (u'%s 已成为管理员。' % target.nick) \
814 .encode('utf-8'))
815 xmpp.send_message(target.jid, u'你已是本群管理员。')
816 log_admin(self.sender, ADMIN % (target.nick, self.sender.nick))
818 def do_unadmin(self, args):
819 '''取消某人管理员的权限'''
820 if len(args) != 1:
821 self.msg.reply(u'请给出昵称。')
822 return
824 target = get_user_by_nick(args[0])
825 if target is None:
826 self.msg.reply(u'Sorry,查无此人。')
827 return
829 if not target.is_admin:
830 self.msg.reply(u'%s 不是管理员。' % target.nick)
831 return
833 target.is_admin = False
834 target.put()
835 send_to_all_except(target.jid,
836 (u'%s 已不再是管理员。' % target.nick) \
837 .encode('utf-8'))
838 xmpp.send_message(target.jid, u'你已不再是本群管理员。')
839 log_admin(self.sender, UNADMIN % (target.nick, self.sender.nick))
841 def do_block(self, args):
842 '''封禁某个 ID,参数为用户昵称或者 ID(如果不是已经加入的 ID 的话),以及封禁原因'''
843 if len(args) < 2:
844 self.msg.reply(u'请给出要封禁的用户和原因。')
845 return
847 target = get_user_by_nick(args[0])
848 reason = self.msg.body[len(self.sender.prefix):].split(None, 2)[-1]
849 if target is None:
850 jid = args[0]
851 name = jid
852 fullname = name
853 else:
854 jid = target.jid
855 name = target.nick
856 fullname = '%s (%s)' % (name, jid)
857 target.delete()
858 u = BlockedUser.gql('where jid = :1', jid).get()
859 if u is not None:
860 self.msg.reply(u'此 JID 已经被封禁。')
861 return
863 u = BlockedUser(jid=jid, reason=reason)
864 u.put()
866 send_to_all_except(self.sender.jid,
867 (u'%s 已被本群封禁,理由为 %s。' % (name, reason)) \
868 .encode('utf-8'))
869 self.msg.reply(u'%s 已被本群封禁,理由为 %s。' % (fullname, reason))
870 xmpp.send_message(jid, u'你已被本群封禁,理由为 %s。' % reason)
871 xmpp.send_presence(jid, status=u'您已经被本群封禁')
872 log_admin(self.sender, BLOCK % (fullname, reason))
874 def do_unblock(self, args):
875 '''解封某个 ID'''
876 if len(args) != 1:
877 self.msg.reply(u'请给出要解封用户的 JID。')
878 return
880 target = get_blocked_user(args[0])
881 if target is None:
882 self.msg.reply(u'封禁列表中没有这个 JID。')
883 return
885 target.delete()
886 send_to_all((u'%s 已被解封禁。' % args[0]) \
887 .encode('utf-8'))
888 log_admin(self.sender, UNBLOCK % args[0])
890 def do_groupstatus(self, arg):
891 '''设置群状态'''
892 grp = get_group_info()
893 if grp is None:
894 grp = Group()
895 grp.status = self.msg.body[len(self.sender.prefix):].split(None, 1)[-1]
896 grp.put()
897 for u in User.all():
898 xmpp.send_presence(u.jid, status=grp.status)
899 self.msg.reply(u'设置成功!')