slack init: Simple interaction with slack bot

ref: https://github.com/nlopes/slack/blob/master/examples/websocket/websocket.go

Effect:

Send the command ads with text, which slack BOT returns.

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "regexp"
 6     "github.com/nlopes/slack"
 7 )
 8 
 9 func main() {
10 
11     api := slack.New("your bot token")
12     // slack.New("YOUR_TOKEN_HERE", slack.OptionDebug(true))
13 
14     rtm := api.NewRTM()  //Real-time message
15     go rtm.ManageConnection()
16 
17     for msg := range rtm.IncomingEvents {
18         fmt.Print("Event Received: ")
19         switch ev := msg.Data.(type) {
20         case *slack.HelloEvent:
21             // Ignore hello
22 
23         case *slack.ConnectedEvent:
24             fmt.Println("Infos:", ev.Info)
25             fmt.Println("Connection counter:", ev.ConnectionCount)
26             rtm.SendMessage(rtm.NewOutgoingMessage("Hello world", "CB9NY3BAP"))
27 
28         case *slack.MessageEvent:
29             if(ev.Type == "message") {
30                 fmt.Printf("Message: %v\n", ev)
31                 reg := regexp.MustCompile(`^ads\s`)  //Regular matching ads
32 
33                 if(reg.MatchString(ev.Text)) {  //Receive commands starting with ads
34                     fmt.Println(ev.Text)
35                     rtm.SendMessage(rtm.NewOutgoingMessage(ev.Text, ev.Channel))  //Return the received text
36                 }
37             }
38 
39         case *slack.PresenceChangeEvent:
40             fmt.Printf("Presence Change: %v\n", ev)
41 
42         case *slack.LatencyReport:
43             fmt.Printf("Current latency: %v\n", ev.Value)
44 
45         case *slack.RTMError:
46             fmt.Printf("Error: %s\n", ev.Error())
47 
48         case *slack.InvalidAuthEvent:
49             fmt.Printf("Invalid credentials")
50             return
51 
52         default:
53 
54             // Ignore other events..
55              fmt.Printf("Unexpected: %v\n", msg.Data)
56         }
57     }
58 }

 

posted @ 2019-07-19 10:56  GuoXinxin  阅读(216)  评论(0编辑  收藏  举报