Skip to content

Instantly share code, notes, and snippets.

@fasmide
Last active Aug 24, 2020
Embed
What would you like to do?
package main
import (
"fmt"
"log"
"net/http"
"net/url"
"os"
"strings"
"github.com/slack-go/slack"
)
const destinationChannel = "C0CJRSFGW"
// #etordadgangen
const gameChannel = "C01956TBMTP"
func main() {
api := slack.New(
os.Getenv("SLACK_API"),
// slack.OptionDebug(true),
slack.OptionLog(log.New(os.Stdout, "slack-bot: ", log.Lshortfile|log.LstdFlags)),
)
rtm := api.NewRTM()
go rtm.ManageConnection()
words := make([]string, 0)
for msg := range rtm.IncomingEvents {
fmt.Print("Event Received: ")
switch ev := msg.Data.(type) {
case *slack.ConnectedEvent:
fmt.Println("Infos:", ev.Info)
fmt.Println("Connection counter:", ev.ConnectionCount)
case *slack.MessageEvent:
fmt.Printf("Message: %v\n", ev)
// rtm.SendMessage(rtm.NewOutgoingMessage("Hello world", ev.Channel))
if ev.Channel != gameChannel {
continue
}
if ev.Type != "message" {
continue
}
if len(ev.Text) <= 0 {
continue
}
if ev.Text[0] == '<' {
continue
}
word := strings.TrimSpace(ev.Text)
words = append(words, word)
if strings.ContainsAny(word, ".!?") {
go sendAudio(rtm, strings.Join(words, " "))
words = make([]string, 0)
}
case *slack.RTMError:
fmt.Printf("Error: %s\n", ev.Error())
case *slack.InvalidAuthEvent:
fmt.Printf("Invalid credentials")
return
default:
// Ignore other events..
// fmt.Printf("Unexpected: %v\n", msg.Data)
}
}
}
func sendAudio(rtm *slack.RTM, s string) {
// https://www.dr.dk/tjenester/tts?text=-Edb-personen%20G%C3
url := url.URL{}
q := url.Query()
q.Add("text", fmt.Sprint("-", s))
url.RawQuery = q.Encode()
url.Path = "/tjenester/tts"
url.Scheme = "https"
url.Host = "dr.dk"
log.Printf(url.String())
payload, err := http.Get(url.String())
if err != nil {
log.Printf("could not fetch tts: %s", err)
return
}
defer payload.Body.Close()
_, err = rtm.UploadFile(slack.FileUploadParameters{
Reader: payload.Body,
Channels: []string{destinationChannel},
Filename: fmt.Sprint(s, "mp3"),
})
if err != nil {
log.Printf("could not upload tts to slack: %s", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment