-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
311 lines (260 loc) · 7.93 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
/*
MIT License
Copyright (c) 2019 Oded Shapira
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// Package main is responsible for launching the bot.
package main
import (
"flag"
"fmt"
"github.com/bwmarrin/discordgo"
"github.com/dondish/lionplayer/core"
"github.com/dondish/lionplayer/youtube"
"os"
"os/signal"
"regexp"
"strconv"
"strings"
"syscall"
"time"
)
var (
seekPattern, _ = regexp.Compile("(?:([0-9]{1,2})h)?(?:([0-9]{1,2})m)?(?:([0-9]{1,2})s)?") // A pattern to seek
)
func init() {
flag.StringVar(&token, "t", "", "Bot Token")
flag.Parse()
}
var token string
var ytsrc = youtube.New(nil)
var tracks = make(map[string]core.Playable)
var lastpacket core.Packet
func main() {
if token == "" {
fmt.Println("No token provided. Please run: airhorn -t <bot token>")
return
}
// Create a new Discord session using the provided bot token.
dg, err := discordgo.New("Bot " + token)
if err != nil {
fmt.Println("Error creating Discord session: ", err)
return
}
// Register ready as a callback for the ready events.
dg.AddHandler(ready)
// Register messageCreate as a callback for the messageCreate events.
dg.AddHandler(messageCreate)
// Register guildCreate as a callback for the guildCreate events.
dg.AddHandler(guildCreate)
// Open the websocket and begin listening.
err = dg.Open()
if err != nil {
fmt.Println("Error opening Discord session: ", err)
}
// Wait here until CTRL-C or other term signal is received.
fmt.Println("Lionplayer is now running. Press CTRL-C to exit.")
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
<-sc
// Cleanly close down the Discord session.
dg.Close()
}
// This function will be called (due to AddHandler above) when the bot receives
// the "ready" event from Discord.
func ready(s *discordgo.Session, event *discordgo.Ready) {
// Set the playing status.
s.UpdateStatus(0, "Playing music using Go only!")
}
// This function will be called (due to AddHandler above) every time a new
// message is created on any channel that the autenticated bot has access to.
func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
// Ignore all messages created by the bot itself
// This isn't required in this specific example but it's a good practice.
if m.Author.ID == s.State.User.ID {
return
}
// check if the message is "!airhorn"
track, ok := tracks[m.GuildID]
if strings.HasPrefix(m.Content, "!!play") && !ok {
// Find the channel that the message came from.
c, err := s.State.Channel(m.ChannelID)
if err != nil {
// Could not find channel.
return
}
splut := strings.Split(m.Content, " ")
if len(splut) == 1 || !ytsrc.CheckVideoUrl(strings.TrimSpace(splut[1])) {
_, err := s.ChannelMessageSend(c.ID, "Please provide a correct url")
if err != nil {
return
}
return
}
videoID, err := ytsrc.ExtractVideoId(strings.TrimSpace(splut[1]))
if err != nil {
return
}
// Find the guild for that channel.
g, err := s.State.Guild(c.GuildID)
if err != nil {
// Could not find guild.
return
}
// Look for the message sender in that guild's current voice states.
for _, vs := range g.VoiceStates {
if vs.UserID == m.Author.ID {
err = playSound(s, g.ID, vs.ChannelID, videoID, c.ID)
if err != nil {
fmt.Println("Error playing sound:", err)
}
return
}
}
} else if strings.HasPrefix(m.Content, "!!stop") {
if track != nil {
track.Close()
}
} else if strings.HasPrefix(m.Content, "!!seek") {
// Find the channel that the message came from.
c, err := s.State.Channel(m.ChannelID)
if err != nil {
// Could not find channel.
return
}
if track == nil {
_, err := s.ChannelMessageSend(c.ID, "Not playing anything")
if err != nil {
return
}
return
}
splut := strings.Split(m.Content, " ")
if len(splut) == 1 || !seekPattern.MatchString(strings.TrimSpace(splut[1])) {
_, err := s.ChannelMessageSend(c.ID, "Please provide a correct seek")
if err != nil {
return
}
return
}
matches := seekPattern.FindStringSubmatch(strings.TrimSpace(splut[1]))
var hour, minute, second int
if matches[1] != "" {
hour, _ = strconv.Atoi(matches[1])
}
if matches[2] != "" {
minute, _ = strconv.Atoi(matches[2])
}
if matches[3] != "" {
second, _ = strconv.Atoi(matches[3])
}
ms := time.Duration(hour)*time.Hour + time.Duration(minute)*time.Minute + time.Duration(second)*time.Second
trackseek, ok := track.(core.PlaySeekable)
if ok {
_ = trackseek.Seek(ms)
} else {
_, _ = s.ChannelMessageSend(c.ID, "Track is not seekable")
return
}
} else if strings.HasPrefix(m.Content, "!!pause") {
if track != nil {
track.Pause(true)
}
} else if strings.HasPrefix(m.Content, "!!unpause") || strings.HasPrefix(m.Content, "!resume") {
if track != nil {
track.Pause(false)
}
} else if strings.HasPrefix(m.Content, "!!position") {
c, err := s.State.Channel(m.ChannelID)
if err != nil {
// Could not find channel.
return
}
if track != nil {
_, err = s.ChannelMessageSend(c.ID, lastpacket.Timecode.String())
if err != nil {
return
}
}
}
}
// This function will be called (due to AddHandler above) every time a new
// guild is joined.
func guildCreate(s *discordgo.Session, event *discordgo.GuildCreate) {
if event.Guild.Unavailable {
return
}
for _, channel := range event.Guild.Channels {
if channel.ID == event.Guild.ID {
_, _ = s.ChannelMessageSend(channel.ID, "Airhorn is ready! Type !airhorn while in a voice channel to play a sound.")
return
}
}
}
// loadSound attempts to load an encoded sound file from disk.
// playSound plays the current buffer to the provided channel.
func playSound(s *discordgo.Session, guildID, channelID, videoID, msgchannel string) (err error) {
// Join the provided voice channel.
vc, err := s.ChannelVoiceJoin(guildID, channelID, false, true)
if err != nil {
return err
}
// Sleep for a specified amount of time before playing the sound
time.Sleep(250 * time.Millisecond)
// Start speaking.
vc.Speaking(true)
defer func() {
// Stop speaking
vc.Speaking(false)
// Sleep for a specificed amount of time before ending.
time.Sleep(250 * time.Millisecond)
// Disconnect from the provided voice channel.
vc.Disconnect()
}()
trac, err := ytsrc.PlayVideo(videoID)
if err != nil {
return err
}
if trac.IsStream {
_, err = s.ChannelMessageSend(msgchannel, fmt.Sprintf("Now Playing - %s - %s [LIVE]", trac.Title, trac.Author))
} else {
_, err = s.ChannelMessageSend(msgchannel, fmt.Sprintf("Now Playing - %s - %s [%s]", trac.Title, trac.Author, trac.Length))
}
if err != nil {
return err
}
file, err := trac.PlaySeekable()
if err != nil {
return err
}
tracks[guildID] = file
go file.Play()
c := file.Chan()
for {
packet, ok := <-c
lastpacket = packet
// If this is the end of the file, just return.
if !ok {
_ = file.Close()
break
}
// Append encoded pcm data to the buffer.
vc.OpusSend <- packet.Data
}
delete(tracks, guildID)
return nil
}