all repos — disgord @ a4093084b5f92b1e3c91c66c157baba16346c4dc

A simple Discord bot in Go.

add youtube search
Marco Andronaco andronacomarco@gmail.com
Tue, 22 Oct 2024 09:47:34 +0200
commit

a4093084b5f92b1e3c91c66c157baba16346c4dc

parent

451c462955a02ed969386fe816392b8e1fc1cfe2

4 files changed, 55 insertions(+), 2 deletions(-)

jump to
M docker-compose.yamldocker-compose.yaml

@@ -1,4 +1,4 @@

-name: telegle +name: disgord services: app:
M src/globals/utils.gosrc/globals/utils.go

@@ -1,12 +1,18 @@

package globals import ( + "errors" "fmt" + "io" + "net/http" + "regexp" "strings" "github.com/bwmarrin/discordgo" "github.com/kkdai/youtube/v2" ) + +var searchPattern = regexp.MustCompile(`watch\?v\x3d([a-zA-Z0-9_-]{11})`) func GetVoiceChannelID(s *discordgo.Session, m *discordgo.MessageCreate) (response string, g *discordgo.Guild, voiceChannelID string) { if m.Member == nil {

@@ -96,3 +102,24 @@ logger.Errorf("could not save config: %s", err)

} return defaultPrefix } + +func Search(keywords []string) (videoID string, err error) { + resp, err := http.Get("https://www.youtube.com/results?search_query=" + strings.Join(keywords, "+")) + if err != nil { + return + } + defer resp.Body.Close() + + pageContent, err := io.ReadAll(resp.Body) + if err != nil { + return + } + + matches := searchPattern.FindAllStringSubmatch(string(pageContent), -1) + if len(matches) == 0 { + err = errors.New("no video found") + return + } + + return matches[0][1], nil +}
M src/music/commands.gosrc/music/commands.go

@@ -40,7 +40,7 @@ return gl.MsgError

} // Get the video information - video, err := yt.GetVideo(args[0]) + video, err := getVideo(args) if err != nil { logger.Errorf("could not get video: %v", err) return gl.MsgError
A src/music/video.go

@@ -0,0 +1,26 @@

+package music + +import ( + "strings" + + gl "github.com/BiRabittoh/disgord/src/globals" + "github.com/kkdai/youtube/v2" +) + +func getVideo(args []string) (*youtube.Video, error) { + video, err := yt.GetVideo(args[0]) + if err == nil { + return video, nil + } + + if !strings.HasPrefix(err.Error(), "extractVideoID failed") { + return nil, err + } + + id, err := gl.Search(args) + if err != nil || id == "" { + return nil, err + } + + return yt.GetVideo(id) +}