-
Notifications
You must be signed in to change notification settings - Fork 1
/
application.go
185 lines (163 loc) · 5.28 KB
/
application.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/joho/godotenv"
"github.com/jzelinskie/geddit"
"io/ioutil"
"log"
"net/http"
"os"
"time"
)
type EmbedData struct {
Embeds []Embed `json:"embeds"`
}
type Embed struct {
Title string `json:"title,omitempty"`
URL string `json:"url,omitempty"`
Color string `json:"color,omitempty"`
Description string `json:"description,omitempty"`
Fields []EmbedField `json:"fields,omitempty"`
Author EmbedAuthor `json:"author,omitempty"`
}
type EmbedField struct {
Name string `json:"name,omitempty"`
Value string `json:"value,omitempty"`
Inline bool `json:"inline,omitempty"`
}
type EmbedAuthor struct {
Name string `json:"name,omitempty"`
URL string `json:"url,omitempty"`
IconURL string `json:"icon_url,omitempty"`
ProxyIconURL string `json:"proxy_icon_url,omitempty"`
}
type Bookmark struct {
LastID string
}
func (bookmark *Bookmark) getLastID(session *geddit.OAuthSession, subreddit string) string {
optLimit1 := geddit.ListingOptions{Limit: 1}
submissions, _ := session.SubredditSubmissions(subreddit, geddit.NewSubmissions, optLimit1)
bookmark.LastID = submissions[0].FullID
return bookmark.LastID
}
// Custom logging function
type Clog struct{}
func (Clog) debug(message string) {
fmt.Printf("[DEBUG] %v\n", message)
}
func (Clog) info(message string) {
fmt.Printf("[INFO] %v\n", message)
}
func (Clog) warn(message string) {
fmt.Printf("[WARNING] %v\n", message)
}
func (Clog) err(error error) {
log.Fatal(fmt.Sprintf("[ERROR] %v\n", error))
}
func main() {
// Variables
var tickRate time.Duration = 1 * time.Minute
var optBefore geddit.ListingOptions
bookmark := new(Bookmark)
clog := new(Clog)
// Load .env
err := godotenv.Load()
if err != nil {
clog.err(errors.New(fmt.Sprintf("Error loading .env file: %v", err)))
}
redditClient := os.Getenv("REDDIT_CLIENT")
redditSecret := os.Getenv("REDDIT_SECRET")
redditUsername := os.Getenv("REDDIT_USERNAME")
redditPassword := os.Getenv("REDDIT_PASSWORD")
discordWebhookClient := os.Getenv("DISCORD_WEBHOOK_CLIENT")
discordWebhookSecret := os.Getenv("DISCORD_WEBHOOK_SECRET")
// Configuration
webhookBaseURL := "https://discordapp.com/api/v7/webhooks/"
requestUrl := fmt.Sprintf("%v%v/%v", webhookBaseURL, discordWebhookClient, discordWebhookSecret)
subreddit := "shitredditsays"
subredditPretty := "ShitRedditSays"
iconURL := "https://i.imgur.com/3NtinwD.png"
// New oAuth session for Reddit API
session, err := geddit.NewOAuthSession(
redditClient,
redditSecret,
"brdecho v0.02",
"http://airsi.de",
)
if err != nil {
clog.err(errors.New(fmt.Sprintf("Error in creating Reddit session object: %v", err)))
}
// Create new auth token for confidential clients (personal scripts/apps).
err = session.LoginAuth(redditUsername, redditPassword)
if err != nil {
clog.err(errors.New(fmt.Sprintf("Error logging in to Reddit: %v", err)))
}
// Get our initial bookmark
bookmark.getLastID(session, subreddit)
// Main loop
timer := time.Tick(tickRate)
for now := range timer {
clog.debug(fmt.Sprintf("now: %v", now))
// Get submissions since our bookmark
submissions, _ := session.SubredditSubmissions(subreddit, geddit.NewSubmissions, optBefore)
// If there's no new submissions, move on
if len(submissions) < 1 {
clog.debug("No new submissions. Continuing.")
continue
}
// Only work with the next submission
submission := submissions[0]
// Update bookmark
bookmark.LastID = submission.FullID
optBefore = geddit.ListingOptions{Before: bookmark.LastID, Limit: 1}
clog.debug(fmt.Sprintf("New FullID is: %v, Thumbnail URL is: %s", submission.FullID, submission.ThumbnailURL))
/// Process submission to send to webhook
// Prep a HTTP form data object
embeds := EmbedData{Embeds: []Embed{
{
Title: fmt.Sprintf("New post to r/%v", subredditPretty),
URL: submission.FullPermalink(),
Color: "16763904",
// Description: s.URL,
Fields: []EmbedField{
{
Name: submission.Title,
Value: submission.URL,
Inline: false,
},
},
Author: EmbedAuthor{
Name: submission.Author,
URL: fmt.Sprintf("https://www.reddit.com/user/%s/", submission.Author),
IconURL: iconURL,
},
},
}}
// Create json byte data for body
jsonEmbeds, err := json.Marshal(embeds)
if err != nil {
clog.err(errors.New(fmt.Sprintf("Error marshalling JSON data: %v", err)))
}
clog.debug(fmt.Sprintf("json embeds data: %s", jsonEmbeds))
// POST to Discord
response, err := http.Post(requestUrl, "application/json", bytes.NewBuffer(jsonEmbeds))
if err != nil {
clog.err(errors.New(fmt.Sprintf("Error in HTTP POST to Discord: %v", err)))
}
body_byte, err := ioutil.ReadAll(response.Body)
if err != nil {
clog.err(errors.New(fmt.Sprintf("Error from Discord after HTTP POST: %v", err)))
}
// Print POST response
clog.info(fmt.Sprintf("post response: %s", body_byte))
// Look ahead to see if there's more submissions to process
optInnerBefore := geddit.ListingOptions{Before: bookmark.LastID}
submissions, _ = session.SubredditSubmissions(subreddit, geddit.NewSubmissions, optInnerBefore)
if len(submissions) > 0 {
clog.warn(fmt.Sprintf("%v submissions left to process", len(submissions)))
}
} // main loop
}