|
| 1 | +// This example connects to Slack via RTM and listens for events. |
| 2 | +// |
| 3 | +// Before the fix for #1544, the events "apps_uninstalled", "activity", and |
| 4 | +// "badge_counts_updated" were not mapped and would appear as |
| 5 | +// UnmarshallingErrorEvent with an "Received unmapped event" message. |
| 6 | +// |
| 7 | +// Usage: |
| 8 | +// |
| 9 | +// export SLACK_BOT_TOKEN=xoxb-... |
| 10 | +// go run ./examples/unmapped_events/ |
| 11 | +// |
| 12 | +// Then interact with your workspace (open channels, browse around) and watch |
| 13 | +// for unmapped event errors in the output. The "activity" and |
| 14 | +// "badge_counts_updated" events tend to appear during normal workspace usage. |
| 15 | +// The "apps_uninstalled" event appears when an app is removed. |
| 16 | +package main |
| 17 | + |
| 18 | +import ( |
| 19 | + "fmt" |
| 20 | + "log" |
| 21 | + "os" |
| 22 | + |
| 23 | + "github.com/slack-go/slack" |
| 24 | +) |
| 25 | + |
| 26 | +func main() { |
| 27 | + token := os.Getenv("SLACK_BOT_TOKEN") |
| 28 | + if token == "" { |
| 29 | + fmt.Println("SLACK_BOT_TOKEN environment variable is required") |
| 30 | + os.Exit(1) |
| 31 | + } |
| 32 | + |
| 33 | + api := slack.New( |
| 34 | + token, |
| 35 | + slack.OptionDebug(true), |
| 36 | + slack.OptionLog(log.New(os.Stdout, "slack-bot: ", log.Lshortfile|log.LstdFlags)), |
| 37 | + ) |
| 38 | + |
| 39 | + rtm := api.NewRTM() |
| 40 | + go rtm.ManageConnection() |
| 41 | + |
| 42 | + for msg := range rtm.IncomingEvents { |
| 43 | + switch ev := msg.Data.(type) { |
| 44 | + case *slack.ConnectedEvent: |
| 45 | + fmt.Printf("Connected: %s (connection count: %d)\n", ev.Info.User.ID, ev.ConnectionCount) |
| 46 | + |
| 47 | + case *slack.AppsUninstalledEvent: |
| 48 | + fmt.Printf("Apps uninstalled: %+v\n", ev) |
| 49 | + |
| 50 | + case *slack.ActivityEvent: |
| 51 | + fmt.Printf("Activity: subtype=%s key=%s\n", ev.SubType, ev.Key) |
| 52 | + |
| 53 | + case *slack.BadgeCountsUpdatedEvent: |
| 54 | + fmt.Printf("Badge counts updated: %+v\n", ev) |
| 55 | + |
| 56 | + case *slack.UnmarshallingErrorEvent: |
| 57 | + // Before the fix, apps_uninstalled/activity/badge_counts_updated |
| 58 | + // end up here as unmapped events. |
| 59 | + fmt.Printf("UNMAPPED EVENT ERROR: %v\n", ev.ErrorObj) |
| 60 | + |
| 61 | + case *slack.InvalidAuthEvent: |
| 62 | + fmt.Println("Invalid credentials") |
| 63 | + return |
| 64 | + |
| 65 | + case *slack.DisconnectedEvent: |
| 66 | + if ev.Intentional { |
| 67 | + return |
| 68 | + } |
| 69 | + |
| 70 | + default: |
| 71 | + fmt.Printf("Event: type=%s data=%T\n", msg.Type, ev) |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments