Move out "split_at_xiaokai" filter

This commit is contained in:
Richard Chien 2016-12-31 21:29:55 +08:00
parent c62fafa69e
commit ee7df2ab37
5 changed files with 40 additions and 16 deletions

View File

@ -1,5 +1,7 @@
# 编写过滤器
## 写法
编写过滤器比较简单,只需要调用 `filter.py` 中的 `add_filter` 函数,传入过滤器函数和优先级,即可。
比如我们需要做一个消息拦截器,当匹配到消息中有不文明词汇,就发送一条警告,并拦截消息不让后续过滤器和命令处理,代码可能如下:
@ -22,3 +24,17 @@ add_filter(_interceptor, 100)
一般建议优先级设置为 0100 之间。
过滤器函数返回 True 表示让消息继续传递,返回 False 表示拦截消息。由于很多情况下可能不需要拦截,因此为了方便起见,将不返回值的情况(返回 None作为不拦截处理因此只要返回结果 is not False 就表示不拦截。
## 现有的几个重要过滤器
### 消息日志过滤器
此过滤器用于把收到的消息打印在标准输出,在 `filters/message_logger_1000.py` 中定义,优先级 1000一般不建议添加其它优先级比它高的过滤器以确保日志不受任何干扰。
### 分离@开头过滤器
用于分离群组和讨论组中消息开头的 `@CCZU 小开`,优先级 50`filters/split_at_xiaokai_50.py` 中定义。通过此过滤器的消息的 `content` 字段会被更新为分离掉开头的剩余部分,也就是说通过此过滤器的消息,就是确定用户的意图就是和这个 bot 说话的消息。
### 命令分发过滤器
用于处理消息中的命令,优先级 0`filters/command_dispatcher_0.py` 中定义。

View File

@ -31,22 +31,8 @@ def _load_commands():
def _dispatch_command(ctx_msg):
try:
content = ctx_msg.get('content', '')
content = ctx_msg.get('content', '').lstrip()
source = get_source(ctx_msg)
if content.startswith('@'):
my_group_nick = ctx_msg.get('receiver')
if not my_group_nick:
raise SkipException
at_me = '@' + my_group_nick
if not content.startswith(at_me):
raise SkipException
content = content[len(at_me):]
else:
# Not starts with '@'
if ctx_msg.get('type') == 'group_message' or ctx_msg.get('type') == 'discuss_message':
# And it's a group message, so we don't reply
raise SkipException
content = content.lstrip()
start_flag = None
for flag in _command_start_flags:
# Match the command start flag

View File

@ -6,7 +6,7 @@ def _print_help_message(ctx_msg):
a = ['help', '怎么用', '怎么用啊', '你好', '你好啊', '帮助',
'用法', '使用帮助', '使用指南', '使用说明', '使用方法',
'你能做什么', '你能做些什么', '你会做什么', '你会做些什么']
if ctx_msg.get('content', '') in a:
if ctx_msg.get('content', '').strip() in a:
core.help('', ctx_msg)
return False
return True

View File

@ -0,0 +1,22 @@
from filter import add_filter
def _split_at_xiaokai(ctx_msg):
if ctx_msg.get('type') == 'group_message' or ctx_msg.get('type') == 'discuss_message':
content = ctx_msg.get('content', '')
if content.startswith('@'):
my_group_nick = ctx_msg.get('receiver')
if not my_group_nick:
return False
at_me = '@' + my_group_nick
if not content.startswith(at_me):
return False
content = content[len(at_me):]
else:
# Not starts with '@'
return False
ctx_msg['content'] = content.lstrip()
return True
add_filter(_split_at_xiaokai, priority=50)