聊天機器人開發、維護
git clone https://github.com/mattermost/mattermost-bot-sample-golang
cd mattermost-bot-sample-golang
然後把此帳號加入到設定好的要監聽的channel內
然後點開bot_sample.go查看
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"
)
func main() {
println(SAMPLE_NAME)
SetupGracefulShutdown()
client = model.NewAPIv4Client("http://localhost:8065")
調整第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)
}
看一下
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
把原本執行的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
這樣就完成簡單的chatops小小範例囉,之後看你們要加什麼上去都可以 :)