Last active
August 24, 2020 20:56
-
-
Save fasmide/7f3e5f477fca821fbbc4d7c437474382 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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