Created
May 18, 2022 00:32
-
-
Save Dreeseaw/c83f0e5c7c6502f383913f47a0827d18 to your computer and use it in GitHub Desktop.
A Google Cloud Function (Go 1.16) that changes a streamer's lights based on chat events
This file contains 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 p contains an HTTP Cloud Function. | |
package p | |
import ( | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"net/http" | |
"strings" | |
"net/url" | |
) | |
// TwitchWebhookTarget is our default entry point | |
func TwitchWebhookTarget(w http.ResponseWriter, r *http.Request) { | |
body, err := ioutil.ReadAll(r.Body) | |
if err != nil { | |
panic(err) | |
} | |
jsonMap := make(map[string]interface{}) | |
err = json.Unmarshal(body, &jsonMap) | |
if err != nil { | |
panic(err) | |
} | |
dumpMap("", jsonMap) | |
// for twitch to verify the webhook | |
challenge, exists := jsonMap["challenge"] | |
if exists == true { | |
w.Write([]byte(rawurlEncode(challenge.(string)))) | |
return | |
} | |
// time to find this data | |
eventData, exists2 := jsonMap["event"] | |
if !exists2 { | |
panic("n event data from twitch") | |
} | |
evData := eventData.(map[string]interface{}) | |
userInput, exists3 := evData["user_input"] | |
if !exists3 { | |
panic("event data found, but no user_input field") | |
} | |
input := userInput.(string) | |
// input is the user input with data type string | |
sendLightChange(input) | |
return | |
} | |
func rawurlEncode(str string) string { | |
return strings.Replace(url.QueryEscape(str), "+", "%20", -1) | |
} | |
func dumpMap(space string, m map[string]interface{}) { | |
for k, v := range m { | |
if mv, ok := v.(map[string]interface{}); ok { | |
fmt.Printf("{ %v: \n", k) | |
dumpMap(space+"\t", mv) | |
fmt.Printf("} \n") | |
} else { | |
fmt.Printf("%v %v : %v \n", space, k, v) | |
} | |
} | |
} | |
func sendLightChange(userInput string) { | |
params := url.Values{} | |
params.Add("color", userInput) | |
body := strings.NewReader(params.Encode()) | |
req, err := http.NewRequest("PUT", "https://api.lifx.com/v1/lights/all/state", body) | |
if err != nil { | |
panic(err) | |
} | |
req.Header.Set("Authorization", "Bearer <Your TiFX Lights API Token>") | |
req.Header.Set("Content-Type", "application/x-www-form-urlencoded") | |
resp, err := http.DefaultClient.Do(req) | |
if err != nil { | |
panic(err) | |
} | |
defer resp.Body.Close() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment