Python 的 ChatOps 库：Opsdroid 和 Errbot
机器人 运维 chatbot

> 
> 学习一下 Python 世界里最广泛使用的 ChatOps 库：每个都能做什么，如何使用。
> 
> 
> 


![](/data/attachment/album/201903/24/100736j64t9ts14tjtvojl.jpg)


ChatOps 是基于会话导向而进行的开发。其思路是你可以编写能够对聊天窗口中的某些输入进行回复的可执行代码。作为一个开发者，你能够用 ChatOps 从 Slack 合并拉取请求，自动从收到的 Facebook 消息中给某人分配支持工单，或者通过 IRC 检查开发状态。


在 Python 世界，最为广泛使用的 ChatOps 库是 Opsdroid 和 Errbot。在这个月的 Python 专栏，让我们一起聊聊使用它们是怎样的体验，它们各自适用于什么方面以及如何着手使用它们。


### Opsdroid


[Opsdroid](https://opsdroid.github.io/) 是一个相对年轻的（始于 2016）Python 开源聊天机器人库。它有着良好的开发文档，不错的教程，并且包含能够帮助你对接流行的聊天服务的插件。


#### 它内置了什么


库本身并没有自带所有你需要上手的东西，但这是故意的。轻量级的框架鼓励你去运用它现有的连接器（Opsdroid 所谓的帮你接入聊天服务的插件）或者去编写你自己的，但是它并不会因自带你所不需要的连接器而自贬身价。你可以轻松使用现有的 Opsdroid 连接器来接入：


* 命令行
* Cisco Spark
* Facebook
* GitHub
* Matrix
* Slack
* Telegram
* Twitter
* Websocket


Opsdroid 会调用使聊天机器人能够展现它们的“技能”的函数。这些技能其实是异步 Python 函数，并使用 Opsdroid 叫做“匹配器”的匹配装饰器。你可以设置你的 Opsdroid 项目，来使用同样从你设置文件所在的代码中的“技能”。你也可以从外面的公共或私人仓库调用这些“技能”。


你同样可以启用一些现存的 Opsdroid “技能”，包括 [seen](https://github.com/opsdroid/skill-seen) —— 它会告诉你聊天机器人上次是什么时候看到某个用户的，以及 [weather](https://github.com/opsdroid/skill-weather) —— 会将天气报告给用户。


最后，Opdroid 允许你使用现存的数据库模块设置数据库。现在 Opdroid 支持的数据库包括：


* Mongo
* Redis
* SQLite


你可以在你的 Opdroid 项目中的 `configuration.yaml` 文件设置数据库、技能和连接器。


#### Opsdroid 的优势


**Docker 支持：**从一开始 Opsdroid 就打算在 Docker 中良好运行。在 Docker 中的指导是它 [安装文档](https://opsdroid.readthedocs.io/en/stable/#docker) 中的一部分。使用 Opsdroid 和 Docker Compose 也很简单：将 Opsdroid 设置成一种服务，当你运行 `docker-compose up` 时，你的 Opsdroid 服务将会开启你的聊天机器人也将就绪。



```
version: "3"

services:
  opsdroid:
    container_name: opsdroid
    build:
      context: .
      dockerfile: Dockerfile
```

**丰富的连接器：** Opsdroid 支持九种像 Slack 和 Github 等从外部接入的服务连接器。你所要做的一切就是在你的设置文件中启用那些连接器，然后把必须的口令或者 API 密匙传过去。比如为了启用 Opsdroid 以在一个叫做 `#updates` 的 Slack 频道发帖，你需要将以下代码加入你设置文件的 `connectors` 部分：



```
 - name: slack
    api-token: "this-is-my-token"
    default-room: "#updates"
```

在设置 Opsdroid 以接入 Slack 之前你需要[添加一个机器人用户](https://api.slack.com/bot-users)。


如果你需要接入一个 Opsdroid 不支持的服务，在[文档](https://opsdroid.readthedocs.io/en/stable/extending/connectors/)里有有添加你自己的连接器的教程。


**相当不错的文档：** 特别是对于一个在积极开发中的新兴库来说，Opsdroid 的文档十分有帮助。这些文档包括一篇带你创建几个不同的基本技能的[教程](https://opsdroid.readthedocs.io/en/stable/tutorials/introduction/)。Opsdroid 在[技能](https://opsdroid.readthedocs.io/en/stable/extending/skills/)、[连接器](https://opsdroid.readthedocs.io/en/stable/extending/connectors/)、[数据库](https://opsdroid.readthedocs.io/en/stable/extending/databases/)，以及[匹配器](https://opsdroid.readthedocs.io/en/stable/matchers/overview/)方面的文档也十分清晰。


它所支持的技能和连接器的仓库为它的技能提供了富有帮助的示范代码。


**自然语言处理：** Opsdroid 的技能里面能使用正则表达式，但也同样提供了几个包括 [Dialogflow](https://opsdroid.readthedocs.io/en/stable/matchers/dialogflow/)，[luis.ai](https://opsdroid.readthedocs.io/en/stable/matchers/luis.ai/)，[Recast.AI](https://opsdroid.readthedocs.io/en/stable/matchers/recast.ai/) 以及 [wit.ai](https://opsdroid.readthedocs.io/en/stable/matchers/wit.ai/) 的 NLP API。


#### Opsdroid 可能的不足


Opsdroid 对它的一部分连接器还没有启用全部的特性。比如说，Slack API 允许你向你的消息添加颜色柱、图片以及其他的“附件”。Opsdroid Slack 连接器并没有启用“附件”特性，所以如果那些特性对你来说很重要的话，你需要编写一个自定义的 Slack 连接器。如果连接器缺少一个你需要的特性，Opsdroid 将欢迎你的[贡献](https://opsdroid.readthedocs.io/en/stable/contributing/)。文档中可以使用更多的例子，特别是对于预料到的使用场景。


#### 示例用法



```
from opsdroid.matchers import match_regex
import random


@match_regex(r'hi|hello|hey|hallo')
async def hello(opsdroid, config, message):
    text = random.choice(["Hi {}", "Hello {}", "Hey {}"]).format(message.user)
    await message.respond(text)
```

*hello/\_\_init\_\_.py*



```
connectors:
  - name: websocket

skills:
  - name: hello
    repo: "https://github.com/<user_id>/hello-skill"

```

*configuration.yaml*


### Errbot


[Errbot](http://errbot.io/en/latest/) 是一个功能齐全的开源聊天机器人。Errbot 发行于 2012 年，并且拥有人们从一个成熟的项目能期待的一切，包括良好的文档、优秀的教程以及许多帮你连入现有的流行聊天服务的插件。


#### 它内置了什么


不像采用了较轻量级方式的 Opsdroid，Errbot 自带了你需要可靠地创建一个自定义机器人的一切东西。


Errbot 包括了对于本地 XMPP、IRC、Slack、Hipchat 以及 Telegram 服务的支持。它通过社区支持的后端列出了另外十种服务。


#### Errbot 的优势


**良好的文档：** Errbot 的文档成熟易读。


**动态插件架构：** Errbot 允许你通过和聊天机器人交谈安全地安装、卸载、更新、启用以及禁用插件。这使得开发和添加特性十分简便。感谢 Errbot 的颗粒性授权系统，出于安全意识这所有的一切都可以被锁闭。


当某个人输入 `!help`，Errbot 使用你的插件的文档字符串来为可获取的命令生成文档，这使得了解每行命令的作用更加简便。


**内置的管理和安全特性：** Errbot 允许你限制拥有管理员权限的用户列表，甚至细粒度访问控制。比如说你可以限制特定用户或聊天房间访问特定命令。


**额外的插件框架：** Errbot 支持钩子、回调、子命令、webhook、轮询以及其它[更多特性](http://errbot.io/en/latest/features.html#extensive-plugin-framework)。如果那些还不够，你甚至可以编写[动态插件](http://errbot.io/en/latest/user_guide/plugin_development/dynaplugs.html)。当你需要基于在远程服务器上的可用命令来启用对应的聊天命令时，这个特性十分有用。


**自带测试框架：** Errbot 支持 [pytest](http://pytest.org/)，同时也自带一些能使你简便测试插件的有用功能。它的“[测试你的插件](http://errbot.io/en/latest/user_guide/plugin_development/testing.html)”的文档出于深思熟虑，并提供了足够的资料让你上手。


#### Errbot 可能的不足


**以 “!” 开头：** 默认情况下，Errbot 命令发出时以一个惊叹号打头（`!help` 以及 `!hello`）。一些人可能会喜欢这样，但是另一些人可能认为这让人烦恼。谢天谢地，这很容易关掉。


**插件元数据** 首先，Errbot 的 [Hello World](http://errbot.io/en/latest/index.html#simple-to-build-upon) 插件示例看上去易于使用。然而我无法加载我的插件，直到我进一步阅读了教程并发现我还需要一个 `.plug` 文档，这是一个 Errbot 用来加载插件的文档。这可能比较吹毛求疵了，但是在我深挖文档之前，这对我来说都不是显而易见的。


### 示例用法



```
import random
from errbot import BotPlugin, botcmd

class Hello(BotPlugin):

    @botcmd
    def hello(self, msg, args):
        text = random.choice(["Hi {}", "Hello {}", "Hey {}"]).format(message.user)
        return text
```

*hello.py*



```
[Core]
Name = Hello
Module = hello

[Python]
Version = 2+

[Documentation]
Description = Example "Hello" plugin
```

*hello.plug*


你用过 Errbot 或 Opsdroid 吗？如果用过请留下关于你对于这些工具印象的留言。




---


via: <https://opensource.com/article/18/3/python-chatops-libraries-opsdroid-and-errbot>


作者：[Jeff Triplett](https://opensource.com/users/laceynwilliams), [Lacey Williams Henschel](https://opensource.com/users/laceynwilliams) 译者：[tomjlw](https://github.com/tomjlw) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
ChatOps is conversation-driven development. The idea is you can write code that is executed in response to something typed in a chat window. As a developer, you could use ChatOps to merge pull requests from Slack, automatically assign a support ticket to someone from a received Facebook message, or check the status of a deployment through IRC.

In the Python world, the most widely used ChatOps libraries are Opsdroid and Errbot. In this month's Python column, let's chat about what it's like to use them, what each does well, and how to get started with them.

## Opsdroid

[Opsdroid](https://opsdroid.github.io/) is a relatively young (since 2016) open source chatbot library written in Python. It has good documentation, a great tutorial, and includes plugins to help you connect to popular chat services.

### What's built in


The library itself doesn't ship with everything you need to get started, but this is by design. The lightweight framework encourages you to enable its existing connectors (what Opsdroid calls the plugins that help you connect to chat services) or write your own, but it doesn't weigh itself down by shipping with connectors you may not need. You can easily enable existing Opsdroid connectors for:

Opsdroid calls the functions the chatbot performs "skills." Skills are `async`

Python functions and use Opsdroid's matching decorators, called "matchers." You can configure your Opsdroid project to use skills from the same codebase your configuration file is in or import skills from outside public or private repositories.

You can enable some existing Opsdroid skills as well, including [seen](https://github.com/opsdroid/skill-seen), which tells you when a specific user was last seen by the bot, and [weather](https://github.com/opsdroid/skill-weather), which will report the weather to the user.

Finally, Opdroid allows you to configure databases using its existing database modules. Current databases with Opsdroid support include:

You configure databases, skills, and connectors in the `configuration.yaml`

file in your Opsdroid project.

### Opsdroid pros

**Docker support:** Opsdroid is meant to work well in Docker from the get-go. Docker instructions are part of its [installation documentation](https://opsdroid.readthedocs.io/en/stable/#docker). Using Opsdroid with Docker Compose is also simple: Set up Opsdroid as a service and when you run `docker-compose up`

, your Opsdroid service will start and your chatbot will be ready to chat.

```
version: "3"
services:
opsdroid:
container_name: opsdroid
build:
context: .
dockerfile: Dockerfile
```


**Lots of connectors:** Opsdroid supports nine connectors to services like Slack and GitHub out of the box; all you need to do is enable those connectors in your configuration file and pass necessary tokens or API keys. For example, to enable Opsdroid to post in a Slack channel named `#updates`

, add this to the `connectors`

section of your configuration file:

```
- name: slack
api-token: "this-is-my-token"
default-room: "#updates"
```


You will have to [add a bot user](https://api.slack.com/bot-users) to your Slack workspace before configuring Opsdroid to connect to Slack.

If you need to connect to a service that Opsdroid does not support, there are instructions for adding your own connectors in the [docs](https://opsdroid.readthedocs.io/en/stable/extending/connectors/).

**Pretty good docs.** Especially for a young-ish library in active development, Opsdroid's docs are very helpful. The docs include a [tutorial](https://opsdroid.readthedocs.io/en/stable/tutorials/introduction/) that leads you through creating a couple of different basic skills. The Opsdroid documentation on [skills](https://opsdroid.readthedocs.io/en/stable/extending/skills/), [connectors](https://opsdroid.readthedocs.io/en/stable/extending/connectors/), [databases](https://opsdroid.readthedocs.io/en/stable/extending/databases/), and [matchers](https://opsdroid.readthedocs.io/en/stable/matchers/overview/) is also clear.

The repositories for its supported skills and connectors provide helpful example code for when you start writing your own custom skills and connectors.

**Natural language processing:** Opsdroid supports regular expressions for its skills, but also several NLP APIs, including [Dialogflow](https://opsdroid.readthedocs.io/en/stable/matchers/dialogflow/), [luis.ai](https://opsdroid.readthedocs.io/en/stable/matchers/luis.ai/), [Recast.AI](https://opsdroid.readthedocs.io/en/stable/matchers/recast.ai/), and [wit.ai](https://opsdroid.readthedocs.io/en/stable/matchers/wit.ai/).

### Possible Opsdroid concern

Opsdroid doesn't yet enable the full features of some of its connectors. For example, the Slack API allows you to add color bars, images, and other "attachments" to your message. The Opsdroid Slack connector doesn't enable the "attachments" feature, so you would need to write a custom Slack connector if those features were important to you. If a connector is missing a feature you need, though, Opsdroid would welcome your [contribution](https://opsdroid.readthedocs.io/en/stable/contributing/). The docs could use some more examples, especially of expected use cases.

### Example usage

`hello/__init__.py`


```
from opsdroid.matchers import match_regex
import random
@match_regex(r'hi|hello|hey|hallo')
async def hello(opsdroid, config, message):
text = random.choice(["Hi {}", "Hello {}", "Hey {}"]).format(message.user)
await message.respond(text)
```


`configuration.yaml`


```
connectors:
- name: websocket
skills:
- name: hello
repo: "https://github.com/<user_id>/hello-skill"
```


## Errbot

[Errbot](http://errbot.io/en/latest/) is a batteries-included open source chatbot. Errbot was released in 2012 and has everything anyone would expect from a mature project, including good documentation, a great tutorial, and plenty of plugins to help you connect to existing popular chat services.

### What's built in

Unlike Opsdroid, which takes a more lightweight approach, Errbot ships with everything you need to build a customized bot safely.

Errbot includes support for XMPP, IRC, Slack, Hipchat, and Telegram services natively. It lists support for 10 other services through community-supplied backends.

### Errbot pros

**Good docs:** Errbot's docs are mature and easy to use.

**Dynamic plugin architecture:** Errbot allow you to securely install, uninstall, update, enable, and disable plugins by chatting with the bot. This makes development and adding features easy. For the security conscious, this can all be locked down thanks to Errbot's granular permission system.

Errbot uses your plugin docstrings to generate documentation for available commands when someone types `!help`

, which makes it easier to know what each command does.

**Built-in administration and security:** Errbot allows you to restrict lists of users who have administrative rights and even has fine-grained access controls. For example, you can restrict which commands may be called by specific users and/or specific rooms.

**Extensive plugin framework:** Errbot supports hooks, callbacks, subcommands, webhooks, polling, and many [more features](http://errbot.io/en/latest/features.html#extensive-plugin-framework). If those aren't enough, you can even write [Dynamic plugins](http://errbot.io/en/latest/user_guide/plugin_development/dynaplugs.html). This feature is useful if you want to enable chat commands based on what commands are available on a remote server.

**Ships with a testing framework:** Errbot supports [pytest](http://pytest.org/) and ships with some useful utilities that make testing your plugins easy and possible. Its "[testing your plugins](http://errbot.io/en/latest/user_guide/plugin_development/testing.html)" docs are well thought out and provide enough to get started.

### Possible Errbot concerns

**Initial !:** By default, Errbot commands are issued starting with an exclamation mark (`!help`

and `!hello`

). Some people may like this, but others may find it annoying. Thankfully, this is easy to turn off.

**Plugin metadata:** At first, Errbot's [Hello World](http://errbot.io/en/latest/index.html#simple-to-build-upon) plugin example seems easy to use. However, I couldn't get my plugin to load until I read further into the tutorial and discovered that I also needed a `.plug`

file, a file Errbot uses to load plugins. This is a pretty minor nitpick, but it wasn't obvious to me until I dug further into the docs.

### Example usage

`hello.py`


```
import random
from errbot import BotPlugin, botcmd
class Hello(BotPlugin):
@botcmd
def hello(self, msg, args):
text = random.choice(["Hi {}", "Hello {}", "Hey {}"]).format(message.user)
return text
```


`hello.plug`


```
[Core]
Name = Hello
Module = hello
[Python]
Version = 2+
[Documentation]
Description = Example "Hello" plugin
```


Have you used Errbot or Opsdroid? If so, please leave a comment with your impressions on these tools.

## 1 Comment