Passed
Push — master ( f1973d...f7aab9 )
by Viktor
01:37
created

bot/twitch.go   A

Size/Duplication

Total Lines 142
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
cc 17
eloc 108
dl 0
loc 142
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A bot.TwitchInit 0 11 5
A bot.*Twitch.AddStream 0 26 4
B bot.*Twitch.Update 0 32 8
1
package bot
2
3
import (
4
	"encoding/json"
5
	"errors"
6
	"fmt"
7
	"github.com/bwmarrin/discordgo"
8
	"net/http"
9
	"strings"
10
	"time"
11
)
12
13
type Twitch struct {
0 ignored issues
show
introduced by
exported type Twitch should have comment or be unexported
Loading history...
14
	Streams []*TwitchStream
15
	Guilds  map[string]*TwitchGuild
16
	DB      *DBWorker
17
	Conf    *Config
18
	Discord *discordgo.Session
19
}
20
21
type TwitchGuild struct {
0 ignored issues
show
introduced by
exported type TwitchGuild should have comment or be unexported
Loading history...
22
	ID      string
23
	Streams []*TwitchStream
24
}
25
26
type TwitchStream struct {
0 ignored issues
show
introduced by
exported type TwitchStream should have comment or be unexported
Loading history...
27
	Login          string
28
	Guild          string
29
	Channel        string
30
	IsOnline       bool
31
	IsCustom       bool
32
	CustomMessage  string
33
	CustomImageURI string
34
}
35
36
type TwitchStreamResult struct {
0 ignored issues
show
introduced by
exported type TwitchStreamResult should have comment or be unexported
Loading history...
37
	Data []TwitchStreamData `json:"data"`
38
}
39
40
type TwitchStreamData struct {
0 ignored issues
show
introduced by
exported type TwitchStreamData should have comment or be unexported
Loading history...
41
	ID           string `json:"id"`
42
	UserID       string `json:"user_id"`
43
	UserName     string `json:"user_name"`
44
	GameID       string `json:"game_id"`
45
	Type         string `json:"type"`
46
	Title        string `json:"title"`
47
	Viewers      int    `json:"viewer_count"`
48
	Language     string `json:"language"`
49
	ThumbnailURL string `json:"thumbnail_url"`
50
}
51
52
type TwitchUserResult struct {
0 ignored issues
show
introduced by
exported type TwitchUserResult should have comment or be unexported
Loading history...
53
	Data []TwitchUserData `json:"data"`
54
}
55
56
type TwitchUserData struct {
0 ignored issues
show
introduced by
exported type TwitchUserData should have comment or be unexported
Loading history...
57
	ID              string `json:"id"`
58
	Login           string `json:"login"`
59
	Name            string `json:"display_name"`
60
	Type            string `json:"type"`
61
	BroadcasterType string `json:"broadcaster_type"`
62
	Description     string `json:"description"`
63
	ProfileImgURL   string `json:"profile_image_url"`
64
	OfflineImgURL   string `json:"offline_image_url"`
65
	Views           int    `json:"view_count"`
66
}
67
68
func TwitchInit(session *discordgo.Session, conf *Config, db *DBWorker) *Twitch {
0 ignored issues
show
introduced by
exported function TwitchInit should have comment or be unexported
Loading history...
69
	guilds := make(map[string]*TwitchGuild)
70
	var streams []*TwitchStream
71
	for _, g := range session.State.Guilds {
72
		guildStreams := db.GetTwitchStreams(g.ID)
73
		for _, s := range guildStreams {
74
			streams = append(streams, s)
75
		}
76
		guilds[g.ID] = &TwitchGuild{g.ID, guildStreams}
77
	}
78
	return &Twitch{streams, guilds, db, conf, session}
79
}
80
81
func (t *Twitch) Update() {
0 ignored issues
show
introduced by
exported method Twitch.Update should have comment or be unexported
Loading history...
82
	for _, s := range t.Streams {
83
		timeout := time.Duration(time.Duration(1) * time.Second)
84
		client := &http.Client{
85
			Timeout: time.Duration(timeout),
86
		}
87
		req, _ := http.NewRequest("GET", fmt.Sprintf("https://api.twitch.tv/helix/streams?user_login=%v", s.Login), nil)
88
		req.Header.Add("Client-ID", t.Conf.Twitch.ClientID)
89
		resp, err := client.Do(req)
90
		var result TwitchStreamResult
91
		if err == nil {
92
			err = json.NewDecoder(resp.Body).Decode(&result)
93
			if err != nil {
94
				t.DB.Log("Twitch", "", "Parsing Twitch API stream error")
95
				continue
96
			}
97
			if len(result.Data) > 0 {
98
				if s.IsOnline == false {
99
					s.IsOnline = true
100
					imgUrl := strings.Replace(result.Data[0].ThumbnailURL, "{width}", "720", -1)
0 ignored issues
show
introduced by
var imgUrl should be imgURL
Loading history...
101
					imgUrl = strings.Replace(imgUrl, "{height}", "480", -1)
102
					emb := NewEmbed(fmt.Sprintf("Hey @here %v is now live on https://www.twitch.tv/%v", result.Data[0].UserName, s.Login)).
103
						Field("Stream", result.Data[0].Title, true).
104
						AttachImgURL(imgUrl)
105
					_, _ = t.Discord.ChannelMessageSendEmbed(s.Channel, emb.GetEmbed())
106
				}
107
			} else {
108
				if s.IsOnline == true {
109
					s.IsOnline = false
110
				}
111
			}
112
			t.DB.UpdateStream(s)
113
		}
114
	}
115
}
116
117
func (t *Twitch) AddStream(guild, channel, login string) error {
0 ignored issues
show
introduced by
exported method Twitch.AddStream should have comment or be unexported
Loading history...
118
	timeout := time.Duration(time.Duration(1) * time.Second)
119
	client := &http.Client{
120
		Timeout: time.Duration(timeout),
121
	}
122
	req, _ := http.NewRequest("GET", fmt.Sprintf("https://api.twitch.tv/helix/users?login=%v", login), nil)
123
	req.Header.Add("Client-ID", t.Conf.Twitch.ClientID)
124
	resp, err := client.Do(req)
125
	var result TwitchUserResult
126
	if err == nil {
127
		err = json.NewDecoder(resp.Body).Decode(&result)
128
		if err != nil {
129
			return errors.New("parsing streamer error")
130
		}
131
		if len(result.Data) > 0 {
132
			stream := TwitchStream{}
133
			stream.Login = login
134
			stream.Channel = channel
135
			stream.Guild = guild
136
			t.Streams = append(t.Streams, &stream)
137
			t.Guilds[guild].Streams = append(t.Guilds[guild].Streams, &stream)
138
		}
139
	} else {
140
		return errors.New("getting streamer error")
141
	}
142
	return nil
143
}
144