BibleBot/rdrama.go

85 lines
1.6 KiB
Go
Raw Normal View History

2022-12-17 13:03:35 +00:00
package main
import (
"encoding/json"
2022-12-18 04:08:07 +00:00
"fmt"
2022-12-17 13:03:35 +00:00
"net/http"
2022-12-18 04:08:07 +00:00
"net/url"
"time"
2022-12-17 13:03:35 +00:00
)
2022-12-18 04:08:07 +00:00
type RDramaClient struct {
2022-12-17 13:03:35 +00:00
baseURL string
apiKey string
}
2022-12-18 04:08:07 +00:00
func NewRDramaClient(baseURL, apiKey string) *RDramaClient {
return &RDramaClient{
2022-12-17 13:03:35 +00:00
baseURL: baseURL,
apiKey: apiKey,
}
}
2022-12-18 04:08:07 +00:00
func (c *RDramaClient) makeRequest(method, path string, v interface{}) error {
2022-12-17 13:03:35 +00:00
url := c.baseURL + path
req, err := http.NewRequest(method, url, nil)
if err != nil {
return err
}
2022-12-18 04:08:07 +00:00
req.Header.Add("Authorization", fmt.Sprintf("%s", c.apiKey))
2022-12-17 13:03:35 +00:00
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
2022-12-18 04:08:07 +00:00
if !(resp.StatusCode >= 200 && resp.StatusCode < 300) {
2022-12-17 13:03:35 +00:00
return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
return json.NewDecoder(resp.Body).Decode(v)
}
type CommentResponse struct {
Data []Comment `json:"data"`
}
type Comment struct {
ID int `json:"id"`
2022-12-18 04:08:07 +00:00
Author string `json:"author_name"`
Text string `json:"body"`
2022-12-17 13:03:35 +00:00
}
2022-12-18 04:08:07 +00:00
type SearchParams struct {
Hole string
After time.Time
Before time.Time
2022-12-17 13:03:35 +00:00
}
2022-12-18 04:08:07 +00:00
func (c *RDramaClient) GetComments(params SearchParams) ([]Comment, error) {
var s string
if params.Hole != "" {
s += fmt.Sprintf("hole:%s", params.Hole)
2022-12-17 13:03:35 +00:00
}
2022-12-18 04:08:07 +00:00
nullTime := time.Time{}
if params.After != nullTime {
s += fmt.Sprintf(" after:%d", params.After.Unix())
}
if params.Before != nullTime {
s += fmt.Sprintf(" before:%d", params.Before.Unix())
}
v := url.Values{}
v.Set("q", s)
url := "/search/comments?" + v.Encode()
fmt.Printf("URL: %s\n", url)
var comments CommentResponse
if err := c.makeRequest("GET", url, &comments); err != nil {
return nil, err
2022-12-17 13:03:35 +00:00
}
2022-12-18 04:08:07 +00:00
return comments.Data, nil
2022-12-17 13:03:35 +00:00
}