Last active
December 6, 2021 18:29
-
-
Save julianeon/dc683ea28f48bc1601e22b8648926fce to your computer and use it in GitHub Desktop.
Reddit API script: fetching the top subreddit posts for "JavaScript" and writing to file.
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 main | |
import ( | |
"context" | |
"fmt" | |
"io" | |
"os" | |
"log" | |
"github.com/vartanbeno/go-reddit/reddit" | |
) | |
var ctx = context.Background() | |
func WriteFile(subreddit string, filename string) error { | |
data:=fetchPosts(subreddit); | |
file, err := os.Create(filename) | |
if err != nil { | |
return err | |
} | |
defer file.Close() | |
_, err = io.WriteString(file, data) | |
if err != nil { | |
return err | |
} | |
return file.Sync() | |
} | |
func EmptyFile(filename string) { | |
e := os.Remove(filename) | |
if e != nil { | |
log.Fatal(e) | |
} | |
o, _ := os.Stat(filename) | |
if o != nil { | |
log.Fatal(o) | |
} | |
} | |
func fetchPosts(sub string) string { | |
id:= "fake" | |
secret:= "alsofake" | |
username:= "veryfake" | |
password:= "extrafake" | |
credentials := reddit.Credentials{ID: id, Secret: secret, Username: username, Password: password} | |
client, _ := reddit.NewClient(credentials) | |
posts, _, err :=client.Subreddit.TopPosts(ctx, sub, &reddit.ListPostOptions{ | |
ListOptions: reddit.ListOptions{ | |
Limit: 100, | |
}, | |
Time: "today", | |
}) | |
text:=""; | |
if err != nil { | |
fmt.Println(err) | |
text= "empty"; | |
} | |
for _, post := range posts { | |
texttitle:=fmt.Sprintf("* %s\n", post.Title) | |
textlink:=fmt.Sprintf("** %s\n", post.URL) | |
text=text+texttitle+textlink; | |
} | |
return text; | |
} | |
func main() { | |
subreddit:="javascript"; | |
fn:=subreddit+".org" | |
EmptyFile(fn) | |
WriteFile(subreddit,fn); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment