-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
330 lines (290 loc) · 8.41 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
package main
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"html/template"
"net/url"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/PaulSonOfLars/gotgbot/parsemode"
"github.com/PaulSonOfLars/gotgbot/v2"
"github.com/PaulSonOfLars/gotgbot/v2/ext"
"github.com/PaulSonOfLars/gotgbot/v2/ext/handlers"
"github.com/PaulSonOfLars/gotgbot/v2/ext/handlers/filters/message"
"github.com/joho/godotenv"
log "github.com/sirupsen/logrus"
"github.com/zmb3/spotify/v2"
auth "github.com/zmb3/spotify/v2/auth"
"golang.org/x/oauth2/clientcredentials"
)
const (
EnvProduction = "PROD"
EnvDevelopment = "DEV"
)
var (
spotifyClient *spotify.Client
spotifyConfig *clientcredentials.Config
)
func getEnvOrFatal(key string) string {
value := os.Getenv(key)
if value == "" {
exit(fmt.Sprintf("Environment variable not set: %s", key))
}
return value
}
func exit(msg string) {
_, _ = fmt.Fprintln(os.Stderr, msg)
os.Exit(1)
}
func main() {
var timeout int64
var logLevel string
flag.StringVar(&logLevel, "log-level", "debug", "Set the log level (debug, info, warn, error, fatal, panic)")
flag.Int64Var(&timeout, "timeout", 0, "Set the timeout value in seconds")
flag.Parse()
if timeout < 0 {
exit("Timeout value must be greater than 0")
}
level, err := log.ParseLevel(logLevel)
if err != nil {
exit(fmt.Sprintf("Unknown log level: %s", logLevel))
}
log.SetLevel(level)
err = godotenv.Load()
if err != nil {
log.WithError(err).Fatal("Error loading .env file")
}
environment := os.Getenv("ENVIRONMENT")
if environment == "" {
environment = EnvDevelopment
}
if environment != EnvProduction {
log.SetFormatter(&log.TextFormatter{
ForceColors: true,
DisableQuote: true,
QuoteEmptyFields: true,
FullTimestamp: true,
})
}
log.Debug("Environment: ", environment)
telegramToken := getEnvOrFatal("TELEGRAM_TOKEN")
spotifyClientID := getEnvOrFatal("SPOTIFY_CLIENT_ID")
spotifyClientSecret := getEnvOrFatal("SPOTIFY_CLIENT_SECRET")
bot, err := gotgbot.NewBot(telegramToken, nil)
if err != nil {
log.WithError(err).Fatal("Failed to create new bot")
}
// Set up a Spotify API client
spotifyConfig = &clientcredentials.Config{
ClientID: spotifyClientID,
ClientSecret: spotifyClientSecret,
TokenURL: auth.TokenURL,
}
err = initSpotifyClient()
if err != nil {
log.WithError(err).Fatal("Error during Spotify client creation")
}
dispatcher := ext.NewDispatcher(&ext.DispatcherOpts{
// If a handler returns an error, log it and continue going.
Error: func(b *gotgbot.Bot, ctx *ext.Context, err error) ext.DispatcherAction {
log.WithError(err).Error("An error occurred while handling update")
return ext.DispatcherActionEndGroups
},
})
dispatcher.AddHandlerToGroup(&HandleAnything{}, -1)
dispatcher.AddHandler(handlers.NewMessage(message.Audio, handleAudioMessage))
dispatcher.AddHandler(handlers.NewMessage(message.All, handleUnknownMessage))
updater := ext.NewUpdater(
dispatcher,
&ext.UpdaterOpts{
UnhandledErrFunc: func(err error) {
log.WithError(err).Error("Updater error")
},
},
)
err = updater.StartPolling(
bot,
&ext.PollingOpts{
DropPendingUpdates: false,
GetUpdatesOpts: &gotgbot.GetUpdatesOpts{
Timeout: timeout,
AllowedUpdates: []string{},
RequestOpts: &gotgbot.RequestOpts{
Timeout: time.Second * time.Duration(timeout+10),
},
},
},
)
if err != nil {
log.WithError(err).Fatal("Failed to start polling")
}
log.Info("Bot started: https://t.me/", bot.User.Username)
if environment == EnvProduction {
// We don't care about graceful shutdown in development
signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-signals
log.Info("Received shutdown signal, stopping bot...")
s := time.Now().UnixMilli()
errStop := updater.Stop()
f := time.Now().UnixMilli()
sec := float64(f-s) / 1000
log.Debugf("Time took to stop %.3f", sec)
if errStop != nil {
log.WithError(errStop).Error("Unable to stop bot")
return
}
}()
}
updater.Idle()
}
func initSpotifyClient() error {
token, err := spotifyConfig.Token(context.Background())
if err != nil {
return fmt.Errorf("error during Spotify token creation: %w", err)
}
spotifyAuth := auth.New(
auth.WithClientID(spotifyConfig.ClientID),
auth.WithClientSecret(spotifyConfig.ClientSecret),
)
newToken, err := spotifyAuth.RefreshToken(context.Background(), token)
if err != nil {
return fmt.Errorf("error refreshing Spotify token: %w", err)
}
httpClient := spotifyAuth.Client(context.Background(), newToken)
spotifyClient = spotify.New(httpClient)
return nil
}
type HandleAnything struct {
ext.Handler
}
func (h *HandleAnything) CheckUpdate(_ *gotgbot.Bot, _ *ext.Context) bool {
return true
}
func (h *HandleAnything) HandleUpdate(_ *gotgbot.Bot, ctx *ext.Context) error {
if log.IsLevelEnabled(log.DebugLevel) {
// explicit log level check to avoid useless json manipulation
raw, err := json.Marshal(&ctx.Update)
if err != nil {
return fmt.Errorf("failed to marshal update: %w", err)
}
log.WithFields(log.Fields{
"data": string(raw),
}).Debug("Handling update")
}
return ext.ContinueGroups
}
func (h *HandleAnything) Name() string {
return "anything"
}
func handleAudioMessage(bot *gotgbot.Bot, ctx *ext.Context) (err error) {
msg := ctx.EffectiveMessage
title := strings.TrimSpace(msg.Audio.Title)
author := strings.TrimSpace(msg.Audio.Performer)
query := strings.TrimSpace(fmt.Sprintf("%s %s", title, author))
if query == "" {
query = msg.Audio.FileName
query = strings.TrimSuffix(query, ".mp3")
query = strings.TrimSpace(query)
}
if query == "" {
_, errSendMsg := msg.Reply(bot, "Audio metadata or filename is missing.", nil)
checkSendMsgErr(errSendMsg)
return fmt.Errorf("audio metadata or filename is missing")
}
results, err := searchSpotify(query)
if err != nil {
_, errSendMsg := msg.Reply(bot, "Failed to search Spotify.", nil)
checkSendMsgErr(errSendMsg)
return err
}
searchBtn := gotgbot.InlineKeyboardButton{
Text: "Search",
Url: buildSpotifyUserSearchURL(query),
}
total := results.Tracks.Total
if total == 0 {
text := fmt.Sprintf("No results found on Spotify by query `%s`", query)
opts := &gotgbot.SendMessageOpts{
ReplyMarkup: &gotgbot.InlineKeyboardMarkup{
InlineKeyboard: [][]gotgbot.InlineKeyboardButton{{searchBtn}},
},
}
_, err = msg.Reply(bot, text, opts)
return
}
track := results.Tracks.Tracks[0]
text, err := buildResultText(&track)
if err != nil {
return err
}
_, errSendMsg := msg.Reply(bot, text,
&gotgbot.SendMessageOpts{
ParseMode: parsemode.Html,
LinkPreviewOptions: &gotgbot.LinkPreviewOptions{
PreferSmallMedia: true,
ShowAboveText: true,
},
ReplyMarkup: &gotgbot.InlineKeyboardMarkup{
InlineKeyboard: [][]gotgbot.InlineKeyboardButton{{searchBtn}},
},
},
)
return errSendMsg
}
func checkSendMsgErr(err error) {
if err == nil {
return
}
log.WithError(err).Error("Failed to send message")
}
func handleUnknownMessage(bot *gotgbot.Bot, ctx *ext.Context) error {
_, errSendMsg := ctx.EffectiveMessage.Reply(bot, "Send me an audio file to search on Spotify.", nil)
return errSendMsg
}
type trackData struct {
Name, Artists, URL string
}
func searchSpotify(query string) (*spotify.SearchResult, error) {
results, err := spotifyClient.Search(context.Background(), query, spotify.SearchTypeTrack)
if err != nil && strings.Contains(err.Error(), "token expired") {
if refreshErr := initSpotifyClient(); refreshErr != nil {
return nil, refreshErr
}
return spotifyClient.Search(context.Background(), query, spotify.SearchTypeTrack)
}
return results, err
}
// buildSpotifyUserSearchURL constructs a Spotify search URL for the user with the given query.
func buildSpotifyUserSearchURL(query string) string {
baseURL := "https://open.spotify.com/search"
return fmt.Sprintf("%s/%s", baseURL, url.PathEscape(query))
}
func buildResultText(track *spotify.FullTrack) (text string, err error) {
artists := make([]string, len(track.Artists))
for i, artist := range track.Artists {
artists[i] = artist.Name
}
buf := bytes.Buffer{}
tpl, err := template.New("track").Parse(`<a href="{{.URL}}">{{.Name}}</a>
by <b>{{.Artists}}</b>`)
if err != nil {
return
}
td := trackData{
Name: track.Name,
Artists: strings.Join(artists, ", "),
URL: track.ExternalURLs["spotify"],
}
if err = tpl.Execute(&buf, td); err != nil {
return
}
return buf.String(), nil
}