一个简单的半对话、多步骤的工作流slack bot框架。
slackborg的Python项目详细描述
懒虫
Slackborg是一个半对话、多步骤工作流的框架 懒散的机器人。我们才刚刚开始。有主意吗?提出问题。 有密码吗?打开拉取请求。
概念
懒汉有两件事你应该关心,那就是@command decorator和Conversation类。
@command
@command是您放置在要实现的函数上的装饰器 响应给定的命令。命令可以是multi_step,即 假设每次 新消息传入,直到会话显式关闭。是的 如何处理多步骤对话取决于你。如你所见, Conversationobject包含所有需要做出决策的数据 每次调用处理程序时。如果您的命令不是multi_step, 处理程序返回后,会话立即关闭。
@command参数:
- match_string:要传入的regex字符串 re.compile。必需
- flags:要传递到re模块的任何标志 re.compile。
- multi_step:如果命令是多步骤的,则设置为True。 默认值False。
Conversation
Conversation对象是命令的唯一参数 处理程序。会话对于给定频道中的给定用户是唯一的。 当消息传入时,会话管理器检查 会话在发送到的频道中存在。 如果它还不存在,则构造一个会话对象,并且 命令管理器尝试将命令与会话匹配。如果它 找到一个,则在对话中调用其处理程序。如果谈话 使用最新消息及其命令处理程序更新 在更新的对话中调用。
Conversation字段:
- user_id:发件人的空闲用户id
- user_data:发件人的完全可宽延用户数据(在 首先创建对话)
- channel_id:会话的空闲频道id
- channel_data:会话的完全空闲通道数据(已获取 第一次创建会话时–仅当它是 频道而不是dm)
- initial_message:负责 创建此对话。
- messages:其余消息。不包括 ``初始信息``。
- latest_message:最近的消息。
- context:可以放置任何数据的字典 在消息之间坚持对话。这就是魔法 用于在会话中执行多步命令。
Conversation方法:
- say(message):向频道发送消息。
- close():关闭对话。
安装
现在,我可能会建议旋转一个virtualenv并运行 python setup.py develop在里面。
用法
编写一个脚本来声明您的命令并运行您的bot,比如 所以:
import os import random import re import time from slackborg import * # Get Bot ID and API Token from env -- make sure to put these in your env! BOT_ID = os.environ.get('SLACK_BOT_ID') BOT_TOKEN = os.environ.get('SLACK_BOT_TOKEN') # Define a default response to any non-matching commands. The default default is to silently ignore the command and close the conversation. @default_command def default_cmd(conversation): conversation.say("I see, sir {}".format(conversation.user_data['profile']['first_name'])) # Define a command by a regex string, and optionally any flags you'd give the re.compile method. @command('hello', flags=re.IGNORECASE) def hello(conversation): conversation.say("Hello! I am C-3PO, human-cyborg relations!") # By default, a command is single-step and auto-closes its conversation upon the handler returning. # You can override this. @command('sum', flags=re.IGNORECASE, multi_step=True) def do_sum(c): print c operands = c.context.setdefault('operands', []) if len(c.messages): if 'done' in c.latest_message.lower(): c.say("The sum of {} = {}".format( " + ".join(str(o) for o in operands), str(sum(operands)) ) ) c.close() else: try: operands.append(int(c.latest_message)) c.say("So far: {}...".format( " + ".join(str(o) for o in operands) )) except: c.say("That input wasn't a number. Try again!") else: c.say("Just enter your operands, one by one, and then type `done` when you're done!") def main(): borg = SlackBorg(BOT_ID, BOT_TOKEN) borg.run() if __name__ == '__main__': main() # End
谢谢
Some of the patterns used in this framework borrow ideologies from _lins05/slackbot, so I thank the existing developers of that library for their prior work. Perhaps we can bring these two libraries together, eventually! Or keep them separate :D