命令处理程序 Telethon

Command handler Telethon

我开始使用 Telethon 库构建一个机器人,但找不到一种干净的方法来将命令与文本分开。

例如,使用 python-telegram-bot 库,我可以像这样检索命令后的第一个参数:

def test(update, context):
    arg_1 = context.args[0]
    print(arg_1) # Prints the first word after the command

所以...有一种方法可以使用 Telethon 制作类似的东西吗? (我正在使用这段代码从命令中拆分文本,但我认为这种方法不是很好):

txt = event.message.message.lower()
try:
    txt.split("!raw ")[1]
    text = event.message.message[4:]
except Exception as e:
    text = ""
    

if text:
    do_something()

如果您有按以下方式定义的处理程序:

@client.on(events.NewMessage(pattern=r'!raw (\w+)'))
async def handler(event):
    ...

然后您可以访问 event.pattern_match:

arg = event.pattern_match.group(1)
print(arg)  # first word

不过,使用.split()也可以:

parts = event.raw_text.split()
if len(parts) > 1:
    arg = parts[1]

(您还可以通过在用户使用错误命令时告知用户来构建更好的用户体验。)