Skip to content

Instantly share code, notes, and snippets.

@mikejk8s
Created March 30, 2023 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikejk8s/8b95a318d45fb03efd1ef0743cc77e78 to your computer and use it in GitHub Desktop.
Save mikejk8s/8b95a318d45fb03efd1ef0743cc77e78 to your computer and use it in GitHub Desktop.
slack channel adder
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"github.com/slack-go/slack"
"github.com/slack-go/slack/slackevents"
)
func main() {
// Initialize the Slack API client with bot token
api := slack.New(os.Getenv("BOT_TOKEN"))
// Start the HTTP server to listen for incoming events from Slack
http.HandleFunc("/slack/events", func(w http.ResponseWriter, r *http.Request) {
// Check if the request is a URL verification request
if r.Method == "POST" {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
var response slackevents.ChallengeResponse
err = json.Unmarshal(body, &response)
if err != nil {
log.Printf("Error unmarshaling response: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text")
w.Write([]byte(response.Challenge))
return
}
// Parse the incoming request
body, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
// Parse the Slack event from the request body
event, err := slackevents.ParseEvent(json.RawMessage(body), slackevents.OptionNoVerifyToken())
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
// Handle the Slack event
switch event.Type {
case slackevents.CallbackEvent:
innerEvent := event.InnerEvent
switch ev := innerEvent.Data.(type) {
case *slackevents.MessageEvent:
// Ignore messages from bots
if ev.BotID != "" {
return
}
// Check if the message contains an email address
if strings.Contains(ev.Text, "@") {
// Get the user ID of the user to invite
user, err := api.GetUserByEmail(ev.Text)
if err != nil {
api.PostMessage(ev.Channel, slack.MsgOptionText("Failed to get user", false))
return
}
userID := user.ID
// Invite the user to the private channels
channels := []string{"test-logs", "testbot1"}
for _, channel := range channels {
params := slack.CreateConversationParams{
ChannelName: channel,
IsPrivate: true,
TeamID: "",
}
conv, err := api.CreateConversation(params)
if err != nil {
api.PostMessage(ev.Channel, slack.MsgOptionText(fmt.Sprintf("Failed to create channel %s", channel), false))
return
}
_, err = api.InviteUsersToConversation(conv.ID, userID)
if err != nil {
api.PostMessage(ev.Channel, slack.MsgOptionText(fmt.Sprintf("Failed to invite user %s to channel %s", userID, channel), false))
return
}
api.PostMessage(ev.Channel, slack.MsgOptionText(fmt.Sprintf("Invited user %s to channel %s", userID, conv.Name), false))
}
}
}
}
w.WriteHeader(http.StatusOK)
})
// Start the HTTP server and listen for incoming requests
log.Println("Starting server on port 8080...")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatalf("Failed to start server: %v", err)
}
}
module slackchans
go 1.20
require github.com/slack-go/slack v0.12.0
require github.com/gorilla/websocket v1.5.0 // indirect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment