iT邦幫忙

2021 iThome 鐵人賽

DAY 23
0
DevOps

Dev's Ops 啟程系列 第 23

[Day 23] Mattermost - ChatOps

ChatOps with Mattermost

chatops好處

  • 成本低
  • 互動性佳
  • 即時反應提高效率
  • 訊息公開透明化
  • 提升團隊維運經驗
    • 因為是公開訊息所以大家可以在窗口很透明的看到操作,以學習經驗

chatops成本

聊天機器人開發、維護


chatops實作

  • 監聽
  • 確認指令
  • 發動

git clone 範例專案

git clone https://github.com/mattermost/mattermost-bot-sample-golang
cd mattermost-bot-sample-golang 

建立一個使用者給bot使用

然後把此帳號加入到設定好的要監聽的channel內

設定

然後點開bot_sample.go查看

調整const內容

const (
	SAMPLE_NAME = "Mattermost Bot Sample"

	USER_EMAIL    = "my@email.yoyoyoy"
	USER_PASSWORD = "ithomebot"
	USER_NAME     = "ithome-bot"
	USER_FIRST    = "Sample"
	USER_LAST     = "Bot"

	TEAM_NAME        = "rainforest"
	CHANNEL_LOG_NAME = "gitea"
)

調整http連線設定

func main() {
	println(SAMPLE_NAME)

	SetupGracefulShutdown()

	client = model.NewAPIv4Client("http://localhost:8065")

調整WS連線設定

調整第67行 ws參數將 ws://localhost:8065 改為你的URL

	// Lets start listening to some channels via the websocket!
	webSocketClient, err := model.NewWebSocketClient4("ws://localhost:8065", client.AuthToken)
	if err != nil {
		println("We failed to connect to the web socket")
		PrintError(err)
	}

查看觸發command的單字

看一下

func HandleMsgFromDebuggingChannel(){}
	    // if you see any word matching 'alive' then respond
		if matched, _ := regexp.MatchString(`(?:^|\W)alive(?:$|\W)`, post.Message); matched {
			SendMsgToDebuggingChannel("Yes I'm running", post.Id)
			return
		}

		// if you see any word matching 'up' then respond
		if matched, _ := regexp.MatchString(`(?:^|\W)up(?:$|\W)`, post.Message); matched {
			SendMsgToDebuggingChannel("Yes I'm running", post.Id)
			return
		}

		// if you see any word matching 'running' then respond
		if matched, _ := regexp.MatchString(`(?:^|\W)running(?:$|\W)`, post.Message); matched {
			SendMsgToDebuggingChannel("Yes I'm running", post.Id)
			return
		}

		// if you see any word matching 'hello' then respond
		if matched, _ := regexp.MatchString(`(?:^|\W)hello(?:$|\W)`, post.Message); matched {
			SendMsgToDebuggingChannel("Yes I'm running", post.Id)
			return
		}

所以此機器人當收到「alive, up, running, hello」時,會有互動。

在此專案內下指令測試

go run *.go

啟動後會在Terminal上顯示

Ithome Mattermost Bot
Server detected and is running version 5.32.0

與BOT互動

https://ithelp.ithome.com.tw/upload/images/20210927/2011528971JuKWhw6y.png


新增互動指令

我們練習一下加個把當下目錄列出來的指令

把原本執行的go run中斷掉

func HandleMsgFromDebuggingChannel(){}

下面新增 ls 指令列出該目錄檔案

		if matched, _ := regexp.MatchString(`(?:^|\W)ithome(?:$|\W)`, post.Message); matched {
			cmd := exec.Command("ls")
			out, err := cmd.CombinedOutput()

			if err != nil {
				log.Fatalf("cmd.Run() failed with %s\n", err)
			}

			SendMsgToDebuggingChannel(string(out), post.Id)

			return
		}

儲存後,再下一次指令

go run *.go

https://ithelp.ithome.com.tw/upload/images/20210929/20115289LnJGASrKWw.png

這樣就完成簡單的chatops小小範例囉,之後看你們要加什麼上去都可以 :)


上一篇
[Day 22] Mattermost - with Drone Plugin
下一篇
[Day 24] BDD - godog 小試身手
系列文
Dev's Ops 啟程30

尚未有邦友留言

立即登入留言