Issues (115)

api/news/news.go (4 issues)

Severity
1
package news
2
3
import (
4
	"encoding/json"
5
	"errors"
6
	"fmt"
7
	"github.com/FlameInTheDark/dtbot/bot"
8
	"net/http"
9
)
10
11
// NewsResponseData : News main struct
12
type NewsResponseData struct {
0 ignored issues
show
type name will be used as news.NewsResponseData by other packages, and that stutters; consider calling this ResponseData
Loading history...
13
	Status       string            `json:"status"`
14
	TotalResults int               `json:"totalResults"`
15
	Articles     []NewsArticleData `json:"articles"`
16
}
17
18
// NewsArticleData : News article struct
19
type NewsArticleData struct {
0 ignored issues
show
type name will be used as news.NewsArticleData by other packages, and that stutters; consider calling this ArticleData
Loading history...
20
	Source      NewsArticeleSourceData `json:"source"`
21
	Author      string                 `json:"author"`
22
	Title       string                 `json:"title"`
23
	Description string                 `json:"description"`
24
	URL         string                 `json:"url"`
25
	PublishedAt string                 `json:"publishedAt"`
26
}
27
28
// NewsArticeleSourceData : Article source struct
29
type NewsArticeleSourceData struct {
0 ignored issues
show
type name will be used as news.NewsArticeleSourceData by other packages, and that stutters; consider calling this ArticeleSourceData
Loading history...
30
	Id   string `json:"id"`
0 ignored issues
show
struct field Id should be ID
Loading history...
31
	Name string `json:"name"`
32
}
33
34
// GetNews returns news string
35
func GetNews(ctx *bot.Context) error {
36
	var (
37
		result   NewsResponseData
38
		category string
39
	)
40
	if len(ctx.Args) > 0 {
41
		category = ctx.Args[0]
42
	}
43
	resp, err := http.Get(fmt.Sprintf("https://newsapi.org/v2/top-headlines?country=%v&category=%v&apiKey=%v", ctx.DB.GetNewsCountry(ctx.Guild.ID), category, ctx.Conf.News.APIKey))
44
	if err != nil {
45
		ctx.Log("news", ctx.Guild.ID, fmt.Sprintf("Get news error: %v", err))
46
		return fmt.Errorf("get news error: %v", err)
47
	}
48
49
	err = json.NewDecoder(resp.Body).Decode(&result)
50
	if err != nil {
51
		ctx.Log("news", ctx.Guild.ID, fmt.Sprintf("Parse news error: %v", err))
52
		return fmt.Errorf("parse news error: %v", err)
53
	}
54
55
	if result.Status == "ok" {
56
		if len(result.Articles) > 0 {
57
			emb := bot.NewEmbed(ctx.Loc("news"))
58
			for i := 0; i < ctx.Conf.News.Articles; i++ {
59
				emb.Field(result.Articles[i].Title, result.Articles[i].Description+"\n"+result.Articles[i].URL, false)
60
			}
61
			emb.Footer(fmt.Sprintf("%v %v", ctx.Loc("requested_by"), ctx.Message.Author.Username))
62
			emb.Color(ctx.Conf.General.EmbedColor)
63
			_, _ = ctx.Discord.ChannelMessageSendEmbed(ctx.Message.ChannelID, emb.GetEmbed())
64
			return nil
65
		}
66
		return errors.New(ctx.Loc("news_404"))
67
	}
68
	return errors.New(ctx.Loc("news_api_error"))
69
}
70