Skip to content

Commit ed2248a

Browse files
committed
automatic youtube subscription refreshing
1 parent 8e97437 commit ed2248a

File tree

3 files changed

+45
-1
lines changed

3 files changed

+45
-1
lines changed

event/event.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,6 @@ func AddListeners(s *discordgo.Session) {
3333
addCommandListeners(s)
3434
addVoiceStateListeners(s)
3535

36-
addScheduledTriggers(s)
3736
addYouTubeListeners(s)
37+
addScheduledTriggers(s)
3838
}

event/scheduledTriggers.go

+11
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,15 @@ import (
1818
"time"
1919

2020
"cake4everybot/event/command/birthday"
21+
webYT "cake4everybot/webserver/youtube"
2122

2223
"github.com/bwmarrin/discordgo"
2324
"github.com/spf13/viper"
2425
)
2526

2627
func addScheduledTriggers(s *discordgo.Session) {
2728
go scheduleBirthdayCheck(s)
29+
go refreshYoutube()
2830
}
2931

3032
func scheduleBirthdayCheck(s *discordgo.Session) {
@@ -43,3 +45,12 @@ func scheduleBirthdayCheck(s *discordgo.Session) {
4345
birthday.Check(s)
4446
}
4547
}
48+
49+
func refreshYoutube() {
50+
for {
51+
webYT.RefreshSubscriptions()
52+
53+
// loop every 4 days
54+
time.Sleep(4 * 24 * time.Hour)
55+
}
56+
}

webserver/youtube/discord.go

+33
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@
1515
package youtube
1616

1717
import (
18+
"fmt"
1819
"log"
20+
"net/http"
1921

2022
"github.com/bwmarrin/discordgo"
2123
)
@@ -53,3 +55,34 @@ func UnsubscribeChannel(channelID string) {
5355
log.Printf("YouTube: unsubscribed '%s' from announcements", channelID)
5456
}
5557
}
58+
59+
// RefreshSubscriptions sends a subscription request to the youtube hub
60+
func RefreshSubscriptions() {
61+
for id := range subscribtions {
62+
log.Printf("[YouTube] Requesting refresh subscription for id '%s'...", id)
63+
64+
url := "https://pubsubhubbub.appspot.com/subscribe"
65+
req, err := http.NewRequest(http.MethodGet, url, nil)
66+
if err != nil {
67+
log.Printf("Error on creating refresh subscription: %v", err)
68+
continue
69+
}
70+
71+
req.Form.Set("hub.callback", "https://webhook.cake4everyone.de/api/yt_pubsubhubbub")
72+
req.Form.Set("hub.topic", fmt.Sprintf("https://www.youtube.com/xml/feeds/videos.xml?channel_id=%s", id))
73+
req.Form.Set("hub.verify", "sync")
74+
req.Form.Set("hub.mode", "subscribeconst")
75+
76+
resp, err := http.DefaultClient.Do(req)
77+
if err != nil {
78+
log.Printf("[YouTube] Refresh request failed: %v", err)
79+
}
80+
81+
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
82+
log.Printf("[YouTube] Refreshing for channel '%s' failed with status %d", id, resp.StatusCode)
83+
continue
84+
}
85+
86+
log.Printf("[YouTube] Successfully refreshed subscription for channel '%s'", id)
87+
}
88+
}

0 commit comments

Comments
 (0)