使用 Python 在 Mattermost 中创建 ChatOps 聊天机器人
ChatOps
![](/data/attachment/album/202304/05/092837ab3y8zft3hhv02hr.jpg)



> 
> 用一个简单的开源机器人在你的组织中实施 ChatOps。
> 
> 
> 


ChatOps 是一种协作模型，它将人员、流程、工具和自动化连接到一个透明的工作流中。[Mattermost](https://mattermost.com/) 是一个开源、自托管的消息平台，使组织能够安全、有效和高效地进行通信。它是 Slack、Discord 和其他专有消息平台的绝佳 [开源替代品](https://opensource.com/alternatives/slack)。本文概述了在 Mattermost 上创建 ChatOps 机器人的步骤，包括必要的代码示例和解释。


### 先决条件


在开始之前，请确保你可以访问 Mattermost 服务器，[安装 Python](https://opensource.com/article/17/10/python-101)，并 [使用 pip](https://opensource.com/article/20/3/pip-linux-mac-windows) 安装 Mattermost Python 驱动。


### 在 Mattermost 上创建一个机器人帐户


要创建机器人帐户，请访问 Mattermost 系统控制台，并添加具有适当访问权限的机器人帐户。获取机器人的用户名和密码以在 Python 脚本中使用。


### 设置 Mattermost Python 驱动


使用 `pip` 安装 Mattermost Python 驱动，并将其导入 Python 脚本。创建一个新的驱动实例并登录到 Mattermost 服务器。


### 在 Python 中创建 ChatOps 机器人


创建一个新的 Python 脚本，定义要导入的必要库，并使用 Mattermost 驱动的 API 实现机器人的功能。编写代码来处理消息、命令和其他事件，并使用 Mattermost 驱动的 API 方法向通道和用户发送消息和通知。最后，调试和测试 ChatOps 机器人。


### ChatOps 机器人代码示例


以下是响应用户消息的简单 ChatOps 机器人的示例 Python 代码：



```
from mattermostdriver import Driver

bot_username = 'bot_username'
bot_password = 'bot_password'
server_url = 'https://your.mattermost.server.url'

def main():
    driver = Driver({'url': server_url, 'login_id': bot_username, 'password': bot_password, 'scheme': 'https'})
    driver.login()
    team = driver.teams.get_team_by_name('team_name')
    channel = driver.channels.get_channel_by_name(team['id'], 'channel_name')

    @driver.on('message')
    def handle_message(post, **kwargs):
        if post['message'] == 'hello':
            driver.posts.create_post({
                'channel_id': post['channel_id'],
                'message': 'Hi there!'
            })

    driver.init_websocket()

if __name__ == '__main__':
    main()

```

### 添加功能


在 Mattermost 上创建基本的 ChatOps 机器人后，你可以添加更多功能来扩展其功能。以下是步骤：


* **确定要添加的功能**：在编写代码之前，你必须确定要添加到 ChatOps 机器人的功能。可以是从发送通知到与第三方工具集成的任何事情。
* **编写代码**：确定要添加的功能后，就可以开始编写代码了。代码将取决于添加的功能，但你可以使用 Mattermost Python 驱动与 Mattermost API 交互并实现该功能。
* **测试代码**：编写代码后，重要的是对其进行测试以确保其按预期工作。在将其部署到生产服务器之前，你可以在开发服务器或测试通道中测试代码。
* **部署代码**：当你对其进行了测试并且它按预期工作，你就可以将其部署到你的生产服务器。遵循你组织的部署流程并确保新代码不会破坏任何现有功能。
* **记录新功能**：记录你添加到 ChatOps 机器人的新功能非常重要。这将使其他团队成员更容易使用该机器人并了解其功能。


一个 ChatOps Bot 功能示例是与第三方工具集成并提供某些任务的状态更新。



```
from mattermostdriver import Driver
import requests

bot_username = 'bot_username'
bot_password = 'bot_password'
server_url = 'https://your.mattermost.server.url'

def main():
    driver = Driver({'url': server_url, 'login_id': bot_username, 'password': bot_password, 'scheme': 'https'})
    driver.login()
    team = driver.teams.get_team_by_name('team_name')
    channel = driver.channels.get_channel_by_name(team['id'], 'channel_name')

    @driver.on('message')
    def handle_message(post, **kwargs):
        if post['message'] == 'status':
            # Make a request to the third-party tool API to get the status
            response = requests.get('https://api.thirdpartytool.com/status')
            if response.status_code == 200:
                status = response.json()['status']
                driver.posts.create_post({
                    'channel_id': post['channel_id'],
                    'message': f'The status is {status}'
                })
            else:
                driver.posts.create_post({
                    'channel_id': post['channel_id'],
                    'message': 'Failed to get status'
                })

    driver.init_websocket()

if __name__ == '__main__':
    main()

```

在此示例中，ChatOps 机器人监听命令 `status` 并向第三方工具 API 发出请求以获取当前状态。然后它会在发出命令的 Mattermost 频道中发布状态更新。这使团队成员无需离开聊天平台即可快速获取任务状态的更新。


### 开源 ChatOps


总之，在 Mattermost 上创建 ChatOps 机器人是一个简单的过程，可以为你组织的沟通和工作流程带来许多好处。本文提供了分步分解和代码示例，可帮助你开始创建你的机器人，甚至可以通过添加新功能对其进行自定义。现在你了解了基础知识，你可以进一步探索 ChatOps 和 Mattermost 以优化团队的协作和生产力。




---


via: <https://opensource.com/article/23/3/chatbot-mattermost-python>


作者：[Dr. Michael J. Garbade](https://opensource.com/users/drmjg) 选题：[lkxed](https://github.com/lkxed/) 译者：[geekpi](https://github.com/geekpi) 校对：[wxy](https://github.com/wxy)


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


OK
ChatOps is a collaboration model that connects people, processes, tools, and automation into a transparent workflow. [Mattermost](https://mattermost.com/) is an open source, self-hosted messaging platform that enables organizations to communicate securely, effectively, and efficiently. It's a great [open source alternative](https://opensource.com/alternatives/slack) to Slack, Discord, and other proprietary messaging platforms. This article outlines the steps to create a ChatOps bot on Mattermost, including the necessary code examples and explanations.

## Prerequisites

Before starting, ensure that you have access to a Mattermost server, have [Python installed](https://opensource.com/article/17/10/python-101), and have installed the Mattermost Python driver [using pip](https://opensource.com/article/20/3/pip-linux-mac-windows).

## Create a bot account on Mattermost

To create a bot account, access the Mattermost System Console, and add a bot account with appropriate access permissions. Retrieve the bot's username and password for use in the Python script.

## Set up the Mattermost Python driver

Install the Mattermost Python driver using `pip`

, and import it in the Python script. Create a new driver instance and log in to the Mattermost server.

## Create the ChatOps bot in Python

Create a new Python script, define the necessary libraries to be imported, and implement the bot's functionality using the Mattermost driver's API. Write code to handle messages, commands, and other events, and use the Mattermost driver's API methods to send messages and notifications to channels and users. Finally, debug and test the ChatOps bot.

## Example of ChatOps bot code

Here is an example Python code for a simple ChatOps bot that responds to a user's message:

```
``````
from mattermostdriver import Driver
bot_username = 'bot_username'
bot_password = 'bot_password'
server_url = 'https://your.mattermost.server.url'
def main():
driver = Driver({'url': server_url, 'login_id': bot_username, 'password': bot_password, 'scheme': 'https'})
driver.login()
team = driver.teams.get_team_by_name('team_name')
channel = driver.channels.get_channel_by_name(team['id'], 'channel_name')
@driver.on('message')
def handle_message(post, **kwargs):
if post['message'] == 'hello':
driver.posts.create_post({
'channel_id': post['channel_id'],
'message': 'Hi there!'
})
driver.init_websocket()
if __name__ == '__main__':
main()
```



## Add features

Once you've created a basic ChatOps bot on Mattermost, you can add more features to extend its functionality. Here are the steps:

-
**Determine the feature you want to add**: Before writing the code, you must determine the feature to add to your ChatOps bot. This can be anything from sending notifications to integrating with third-party tools. -
**Write the code**: Once you have determined the feature you want to add, you can start writing the code. The code will depend on the feature you add, but you can use the Mattermost Python driver to interact with the Mattermost API and implement the feature. -
**Test the code**: After writing the code, it's important to test it to ensure that it works as expected. Before deploying it to your production server, you can test the code on a development server or in a test channel. -
**Deploy the code**: Once you have tested it and it works as expected, you can deploy it to your production server. Follow your organization's deployment process and ensure the new code doesn't break any existing functionality. -
**Document the new feature**: It's important to document the new feature you have added to your ChatOps bot. This will make it easier for other team members to use the bot and understand its capabilities.

One example of a ChatOps Bot feature could be integrating with a third-party tool and providing status updates on certain tasks.

```
``````
from mattermostdriver import Driver
import requests
bot_username = 'bot_username'
bot_password = 'bot_password'
server_url = 'https://your.mattermost.server.url'
def main():
driver = Driver({'url': server_url, 'login_id': bot_username, 'password': bot_password, 'scheme': 'https'})
driver.login()
team = driver.teams.get_team_by_name('team_name')
channel = driver.channels.get_channel_by_name(team['id'], 'channel_name')
@driver.on('message')
def handle_message(post, **kwargs):
if post['message'] == 'status':
# Make a request to the third-party tool API to get the status
response = requests.get('https://api.thirdpartytool.com/status')
if response.status_code == 200:
status = response.json()['status']
driver.posts.create_post({
'channel_id': post['channel_id'],
'message': f'The status is {status}'
})
else:
driver.posts.create_post({
'channel_id': post['channel_id'],
'message': 'Failed to get status'
})
driver.init_websocket()
if __name__ == '__main__':
main()
```


In this example, the ChatOps bot listens for the command "status" and makes a request to a third-party tool API to get the current status. It then posts the status update in the Mattermost channel where the command was issued. This allows team members to quickly get updates on the status of the task without having to leave the chat platform.

## Open source ChatOps

In summary, creating a ChatOps bot on Mattermost is a simple process that can bring numerous benefits to your organization's communication and workflow. This article has provided a step-by-step breakdown and code examples to help you get started on creating your bot and even customize it by adding new features. Now that you know the basics, you can further explore ChatOps and Mattermost to optimize your team's collaboration and productivity.

## Comments are closed.