Skip to content

Commit

Permalink
Add !hn command to get a random story from /best
Browse files Browse the repository at this point in the history
  • Loading branch information
rcy committed Jul 12, 2024
1 parent 4c31424 commit 7536892
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
42 changes: 42 additions & 0 deletions handlers/hn/hn.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package hn

import (
"encoding/json"
"fmt"
"goirc/bot"
"math/rand"
"net/http"
)

func Handle(params bot.HandlerParams) error {
resp, err := http.Get("https://hacker-news.firebaseio.com/v0/beststories.json")
if err != nil {
return err
}
defer resp.Body.Close()
ids := []int{}

err = json.NewDecoder(resp.Body).Decode(&ids)
if err != nil {
return err
}

id := ids[rand.Intn(30)]

resp, err = http.Get(fmt.Sprintf("https://hacker-news.firebaseio.com/v0/item/%d.json", id))
if err != nil {
return err
}
defer resp.Body.Close()
var item struct {
Title string `json:"title"`
URL string `json:"url"`
}
err = json.NewDecoder(resp.Body).Decode(&item)
if err != nil {
return err
}
params.Privmsgf(params.Target, "%s - %s", item.Title, item.URL)

return nil
}
2 changes: 2 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"goirc/handlers/day"
"goirc/handlers/epigram"
"goirc/handlers/gold"
"goirc/handlers/hn"
"goirc/handlers/kinfonet"
"goirc/handlers/mlb"
"goirc/handlers/weather"
Expand Down Expand Up @@ -95,4 +96,5 @@ func addHandlers(b *bot.Bot) {
b.Handle(`^!xweather (.+)$`, weather.XHandle)
b.Handle(`^!k`, kinfonet.TodaysQuoteHandler)
b.Handle(`^!gold`, gold.Handle)
b.Handle(`^!hn`, hn.Handle)
}

0 comments on commit 7536892

Please sign in to comment.