添加 random 系列命令,对命令起始符为空的情况进行用户友好处理

This commit is contained in:
Richard Chien 2017-02-18 18:58:24 +08:00
parent 21c27ea6c5
commit 6e1ac79024
7 changed files with 110 additions and 15 deletions

View File

@ -18,24 +18,27 @@ _fallback_command = get_fallback_command_after_nl_processors()
@cr.restrict(full_command_only=True)
def process(args_text, ctx_msg):
sentence = args_text.strip()
if not sentence:
core.echo('你什么都没说哦~', ctx_msg)
return
potential_commands = parse_potential_commands(sentence)
potential_commands = sorted(filter(lambda x: x[0] > 60, potential_commands), key=lambda x: x[0], reverse=True)
# If it's a fallback and with empty start flag, then don't send verbose information
hide_verbose = ctx_msg.get('is_fallback') and ctx_msg.get('start_flag') == ''
if len(potential_commands) > 0:
most_possible_cmd = potential_commands[0]
core.echo(
'识别出最可能的等价命令:\n' + ' '.join((most_possible_cmd[1], most_possible_cmd[2])),
ctx_msg
ctx_msg,
internal=hide_verbose
)
ctx_msg['parsed_data'] = most_possible_cmd[3]
cmdhub.call(most_possible_cmd[1], most_possible_cmd[2], ctx_msg)
else:
# if ctx_msg.get('from_voice'):
# Special for voice message
if _fallback_command:
core.echo('暂时无法理解你的意思,下面将使用备用命令 ' + _fallback_command + '……', ctx_msg)
core.echo('暂时无法理解你的意思,下面将使用备用命令 ' + _fallback_command + '……',
ctx_msg,
internal=hide_verbose)
cmdhub.call(_fallback_command, sentence, ctx_msg)
return
pass
# core.echo('暂时无法理解你的意思。\n'
# '由于自然语言识别还非常不完善,建议使用命令来精确控制我。\n'
# '如需帮助请发送「使用帮助」。', ctx_msg)

82
commands/random.py Normal file
View File

@ -0,0 +1,82 @@
import re
import random
import string
from command import CommandRegistry, split_arguments
from commands import core
__registry__ = cr = CommandRegistry()
@cr.register('随机数')
@cr.register('number', hidden=True)
@split_arguments()
def number(_, ctx_msg, internal=False, argv=None):
if len(argv) == 0 or not re.match('x\d+', argv[-1]):
n = 1
else:
n = max(1, int(argv[-1][1:]))
argv = argv[:-1]
if len(argv) > 2 or any((not re.match('-?\d+', num) for num in argv)):
core.echo('参数有错误哦~\n正确的使用方法(主要看参数,你的命令是对的~):\n\n'
'/random.number\n'
'/random.number x5\n'
'/random.number 100\n'
'/random.number 100 x10\n'
'/random.number 50 100\n'
'/random.number 50 100 x3',
ctx_msg, internal)
return
if len(argv) == 1:
argv.append(1)
start, end = (int(argv[0]), int(argv[1])) if len(argv) == 2 else (None, None)
start, end = (min(start, end), max(start, end)) if start is not None else (start, end)
result = []
for _ in range(n):
result.append(random.randint(start, end) if start is not None else random.random())
core.echo(', '.join(str(num) for num in result), ctx_msg, internal)
return result
@cr.register('随机字符')
@cr.register('char', hidden=True)
@split_arguments()
def char(_, ctx_msg, internal=False, argv=None):
if len(argv) > 2 or (len(argv) == 2 and not re.match('x\d+', argv[-1])):
core.echo('参数有错误哦~\n正确的使用方法(主要看参数,你的命令是对的~):\n\n'
'/random.char\n'
'/random.char x5\n'
'/random.char ABCDEFG\n'
'/random.char ABCDEFG x10\n',
ctx_msg, internal)
return
chars = string.ascii_letters + string.digits
size = 1
if len(argv) and re.match('x\d+', argv[-1]):
size = max(1, int(argv[-1][1:]))
argv = argv[:-1]
if len(argv):
chars = argv[0]
result = ''.join(random.choice(chars) for _ in range(size))
core.echo(result, ctx_msg, internal)
return result
@cr.register('随机化')
@cr.register('shuffle', hidden=True)
@split_arguments()
def char(_, ctx_msg, internal=False, argv=None):
if len(argv) == 0:
core.echo('请传入正确的参数哦~', ctx_msg, internal)
return argv
random.shuffle(argv)
core.echo(', '.join(argv), ctx_msg, internal)
return argv

View File

@ -324,6 +324,7 @@ def _send_add_job_help_msg(ctx_msg, internal):
'/scheduler.add_job 0 22 * * * --multi zhihu-daily-job\n'
'zhihu\n'
'echo 今天又是很棒的一天哦!\n'
'\n'
'例 2\n'
'以下命令将每 5 分钟发送一条提示:\n'
'/scheduler.add_job -M */5 tip-job echo 提示内容',

View File

@ -79,14 +79,14 @@ def weather(args_text, ctx_msg):
@cr.register('joke')
@cr.register('笑话', '说笑话', '说个笑话')
def weather(_, ctx_msg):
def joke(_, ctx_msg):
data = ai.tuling123('说个笑话', ctx_msg, internal=True)
core.echo(data.get('text', ''), ctx_msg)
@cr.register('baike')
@cr.register('百科', '查百科')
def weather(args_text, ctx_msg):
def baike(args_text, ctx_msg):
query = args_text.strip()
if not query:
core.echo('请在命令后加上要查的关键词哦~(命令和关键词用空格或逗号隔开)', ctx_msg)

View File

@ -115,7 +115,6 @@ def translate_to(args_text, ctx_msg):
})
if resp.status_code == 200:
data = resp.json()
print(data)
if 'trans_result' in data:
core.echo('翻译结果(百度翻译):\n' + '\n'.join([x['dst'] for x in data['trans_result']]), ctx_msg)
return

View File

@ -15,8 +15,8 @@ _command_args_start_flags = get_command_args_start_flags()
@as_filter(priority=0)
def _dispatch_command(ctx_msg):
text = ctx_msg.get('text', '').lstrip()
try:
text = ctx_msg.get('text', '').lstrip()
if not text:
raise SkipException
source = get_source(ctx_msg)
@ -26,6 +26,7 @@ def _dispatch_command(ctx_msg):
if text.startswith(flag):
start_flag = flag
break
ctx_msg['start_flag'] = start_flag
if start_flag is None or len(text) <= len(start_flag):
# Note: use `start_flag is None` here because empty string is allowed to be the start flag
# No command, check if a session exists
@ -35,6 +36,7 @@ def _dispatch_command(ctx_msg):
# Use fallback
if _fallback_command:
command = [_fallback_command, text]
ctx_msg['is_fallback'] = True
else:
# No fallback
raise SkipException
@ -55,7 +57,15 @@ def _dispatch_command(ctx_msg):
# Skip this message
pass
except CommandNotExistsError:
core.echo('暂时还没有这个命令哦~', ctx_msg)
if ctx_msg['start_flag'] == '' and _fallback_command:
# Empty command start flag is allowed, use fallback
command = [_fallback_command, text]
command[0] = command[0].lower()
ctx_msg['command'] = command[0]
ctx_msg['is_fallback'] = True
cmdhub.call(command[0], command[1], ctx_msg)
else:
core.echo('暂时还没有这个命令哦~', ctx_msg)
except CommandPermissionError:
core.echo('你没有权限使用这个命令哦~', ctx_msg)
except CommandScopeError as se:

View File

@ -85,11 +85,11 @@ def get_command_name_separators():
def get_command_args_start_flags():
return tuple(sorted(('[ \t\n]+',) + config.get('command_args_start_flags', ()), reverse=True))
return tuple(sorted(('[ \\t\\n]+',) + config.get('command_args_start_flags', ()), reverse=True))
def get_command_args_separators():
return tuple(sorted(('[ \t\n]+',) + config.get('command_args_separators', ()), reverse=True))
return tuple(sorted(('[ \\t\\n]+',) + config.get('command_args_separators', ()), reverse=True))
def get_fallback_command():