From 28fbbd81085cc6de63d083f529f5764e32bc80a1 Mon Sep 17 00:00:00 2001 From: Fox_white Date: Thu, 30 Jun 2022 01:02:03 +0800 Subject: [PATCH 01/13] =?UTF-8?q?=E2=9C=A8=20=E7=8C=9C=E6=AD=8C=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0config?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugin/guessmusic/main.go | 177 +++++++++++++++++++++++++------------- 1 file changed, 116 insertions(+), 61 deletions(-) diff --git a/plugin/guessmusic/main.go b/plugin/guessmusic/main.go index db530e0b2e..14208df301 100644 --- a/plugin/guessmusic/main.go +++ b/plugin/guessmusic/main.go @@ -3,6 +3,8 @@ package guessmusic import ( "bytes" + "encoding/json" + "io/fs" "io/ioutil" "math/rand" "net/http" @@ -22,7 +24,6 @@ import ( "github.com/FloatTech/zbputils/ctxext" "github.com/FloatTech/zbputils/file" "github.com/FloatTech/zbputils/web" - "github.com/sirupsen/logrus" "github.com/tidwall/gjson" "github.com/wdvxdr1123/ZeroBot/extension/single" ) @@ -32,17 +33,27 @@ const ( ) var ( - musicPath = file.BOTPATH + "/data/guessmusic/music/" // 绝对路径,歌库根目录,通过指令进行更改 - cuttime = [...]string{"00:00:05", "00:00:30", "00:01:00"} // 音乐切割时间点,可自行调节时间(时:分:秒) + cuttime = [...]string{"00:00:05", "00:00:30", "00:01:00"} // 音乐切割时间点,可自行调节时间(时:分:秒) + config = Config{ // 默认 Config + MusicPath: file.BOTPATH + "/data/guessmusic/music/", // 绝对路径,歌库根目录,通过指令进行更改 + Local: true, // 是否使用本地音乐库 + Api: true, // 是否使用 Api + } ) +type Config struct { + MusicPath string `json:"musicPath"` + Local bool `json:"local"` + Api bool `json:"api"` +} + func init() { // 插件主体 engine := control.Register("guessmusic", &ctrl.Options[*zero.Ctx]{ DisableOnDefault: false, Help: "猜歌插件(该插件依赖ffmpeg)\n" + "- 个人猜歌\n" + "- 团队猜歌\n" + - "- 设置缓存歌库路径 [绝对路径]\n" + + "- 设置猜歌缓存歌库路径 [绝对路径]\n" + "注:默认歌库为网易云热歌榜\n" + "1.可在后面添加“-动漫”进行动漫歌猜歌\n-这个只能猜歌名和歌手\n" + "2.可在后面添加“-动漫2”进行动漫歌猜歌\n-这个可以猜番名,但歌手经常“未知”", @@ -62,15 +73,20 @@ func init() { // 插件主体 if err != nil { panic(err) } - cfgfile := engine.DataFolder() + "setpath.txt" - if file.IsExist(cfgfile) { - b, err := os.ReadFile(cfgfile) - if err == nil { - musicPath = binary.BytesToString(b) - logrus.Infoln("[guessmusic] set dir to", musicPath) + cfgFile := engine.DataFolder() + "config.json" + if file.IsExist(cfgFile) { + b, err := os.ReadFile(cfgFile) + if err != nil { + return + } + if err = json.Unmarshal(b, &config); err != nil { + return } + } else { + k, _ := json.MarshalIndent(config, "", " ") + _ = os.WriteFile(cfgFile, k, 0644) } - engine.OnRegex(`^设置缓存歌库路径(.*)$`, func(ctx *zero.Ctx) bool { + engine.OnRegex(`^设置猜歌(.*)(.*)$`, func(ctx *zero.Ctx) bool { if !zero.SuperUserPermission(ctx) { ctx.SendChain(message.Text("只有bot主人可以设置!")) return false @@ -78,20 +94,41 @@ func init() { // 插件主体 return true }).SetBlock(true). Handle(func(ctx *zero.Ctx) { - musicPath = ctx.State["regex_matched"].([]string)[1] - if musicPath == "" { - ctx.SendChain(message.Text("请输入正确的路径!")) - } - musicPath = strings.ReplaceAll(musicPath, "\\", "/") - if !strings.HasSuffix(musicPath, "/") { - musicPath += "/" - } - err := os.WriteFile(cfgfile, binary.StringToBytes(musicPath), 0644) - if err == nil { - ctx.SendChain(message.Text("成功!")) - } else { - ctx.SendChain(message.Text("ERROR:", err)) + option := ctx.State["regex_matched"].([]string)[1] + value := ctx.State["regex_matched"].([]string)[2] + switch option { + case "缓存歌库路径": + if value == "" { + ctx.SendChain(message.Text("请输入正确的路径!")) + } + musicPath := strings.ReplaceAll(value, "\\", "/") + if !strings.HasSuffix(musicPath, "/") { + musicPath += "/" + } + config.MusicPath = musicPath + k, _ := json.MarshalIndent(config, "", " ") + _ = os.WriteFile(cfgFile, k, 0644) + if err == nil { + ctx.SendChain(message.Text("成功!")) + } else { + ctx.SendChain(message.Text("ERROR:", err)) + } + case "本地": + choice, err := strconv.ParseBool(value) + if err != nil { + ctx.SendChain(message.Text("ERROR:", err)) + } + config.Local = choice + case "Api": + choice, err := strconv.ParseBool(value) + if err != nil { + ctx.SendChain(message.Text("ERROR:", err)) + } + config.Api = choice + default: + ctx.SendChain(message.Text("未知的设置类型,允许的类型为 缓存歌库路径, 本地, Api")) } + }) engine.OnRegex(`^(个人|团队)猜歌(-动漫|-动漫2)?$`, zero.OnlyGroup).SetBlock(true).Limit(ctxext.LimitByGroup). Handle(func(ctx *zero.Ctx) { @@ -103,7 +140,7 @@ func init() { // 插件主体 ctx.SendChain(message.Text("正在准备歌曲,请稍等\n回答“-[歌曲名称|歌手|提示|取消]”\n一共3段语音,6次机会")) } // 随机抽歌 - musicname, pathofmusic, err := musiclottery(mode, musicPath) + musicname, pathofmusic, err := musicLottery(mode, config.MusicPath) if err != nil { ctx.SendChain(message.Text(err)) return @@ -290,7 +327,7 @@ func init() { // 插件主体 } // 随机抽取音乐 -func musiclottery(mode, musicPath string) (musicname, pathofmusic string, err error) { +func musicLottery(mode, musicPath string) (musicname, pathofmusic string, err error) { switch mode { case "-动漫": pathofmusic = musicPath + "动漫/" @@ -309,47 +346,65 @@ func musiclottery(mode, musicPath string) (musicname, pathofmusic string, err er err = errors.Errorf("[读取本地列表错误]ERROR:%s", err) return } - // 随机抽取音乐从本地或者线上 - switch { - case len(files) == 0: - // 如果没有任何本地就下载歌曲 - switch mode { - case "-动漫": - musicname, err = getpaugramdata(pathofmusic) - case "-动漫2": - musicname, err = getanimedata(pathofmusic) + + if config.Local && config.Api { + switch { + case len(files) == 0: + // 如果没有任何本地就下载歌曲 + musicname, err = getApiMusic(mode, pathofmusic) + if err != nil { + err = errors.Errorf("[本地数据为0,歌曲下载错误]ERROR:%s", err) + return + } + case rand.Intn(2) == 0: + // [0,1)只会取到0,rand不允许的 + musicname = getLocalMusic(files) default: - musicname, err = getuomgdata(pathofmusic) + musicname, err = getApiMusic(mode, pathofmusic) + if err != nil { + // 如果下载失败就从本地抽一个歌曲 + musicname = getLocalMusic(files) + err = nil + } } - if err != nil { - err = errors.Errorf("[本地数据为0,歌曲下载错误]ERROR:%s", err) + return + } + if config.Local { + if len(files) == 0 { + err = errors.Errorf("[本地数据为0,未开启API数据]") return } - case rand.Intn(2) == 0: - // [0,1)只会取到0,rand不允许的 - if len(files) > 1 { - musicname = strings.Replace(files[rand.Intn(len(files))].Name(), ".mp3", "", 1) - } else { - musicname = strings.Replace(files[0].Name(), ".mp3", "", 1) - } - default: - switch mode { - case "-动漫": - musicname, err = getpaugramdata(pathofmusic) - case "-动漫2": - musicname, err = getanimedata(pathofmusic) - default: - musicname, err = getuomgdata(pathofmusic) - } + musicname = getLocalMusic(files) + return + } + if config.Api { + musicname, err = getApiMusic(mode, pathofmusic) if err != nil { - // 如果下载失败就从本地抽一个歌曲 - if len(files) > 1 { - musicname = strings.Replace(files[rand.Intn(len(files))].Name(), ".mp3", "", 1) - } else { - musicname = strings.Replace(files[0].Name(), ".mp3", "", 1) - } - err = nil + err = errors.Errorf("[获取API失败,未开启本地数据]ERROR:%s", err) } + return + } + err = errors.Errorf("[未开启API以及本地数据]") + return +} + +func getApiMusic(mode string, pathofmusic string) (musicname string, err error) { + switch mode { + case "-动漫": + musicname, err = getpaugramdata(pathofmusic) + case "-动漫2": + musicname, err = getanimedata(pathofmusic) + default: + musicname, err = getuomgdata(pathofmusic) + } + return +} + +func getLocalMusic(files []fs.FileInfo) (musicname string) { + if len(files) > 1 { + musicname = strings.Replace(files[rand.Intn(len(files))].Name(), ".mp3", "", 1) + } else { + musicname = strings.Replace(files[0].Name(), ".mp3", "", 1) } return } From 5f423ac00d9daa7e8190c961c8424a9dae3eda76 Mon Sep 17 00:00:00 2001 From: Fox_white Date: Thu, 30 Jun 2022 01:05:27 +0800 Subject: [PATCH 02/13] =?UTF-8?q?:books:=20=E7=8C=9C=E6=AD=8C=E5=B8=AE?= =?UTF-8?q?=E5=8A=A9=E4=BF=A1=E6=81=AF=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugin/guessmusic/main.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/plugin/guessmusic/main.go b/plugin/guessmusic/main.go index 14208df301..3b103893b1 100644 --- a/plugin/guessmusic/main.go +++ b/plugin/guessmusic/main.go @@ -54,6 +54,8 @@ func init() { // 插件主体 "- 个人猜歌\n" + "- 团队猜歌\n" + "- 设置猜歌缓存歌库路径 [绝对路径]\n" + + "- 设置本地 [t/f]\n" + + "- 设置Api [t/f]\n" + "注:默认歌库为网易云热歌榜\n" + "1.可在后面添加“-动漫”进行动漫歌猜歌\n-这个只能猜歌名和歌手\n" + "2.可在后面添加“-动漫2”进行动漫歌猜歌\n-这个可以猜番名,但歌手经常“未知”", From 3b344467683ae59bd874f9ff5effda0186c401a5 Mon Sep 17 00:00:00 2001 From: Fox_white Date: Thu, 30 Jun 2022 01:14:55 +0800 Subject: [PATCH 03/13] =?UTF-8?q?:books:=20=E7=8C=9C=E6=AD=8C=E5=B8=AE?= =?UTF-8?q?=E5=8A=A9=E4=BF=A1=E6=81=AF=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 +++++- plugin/guessmusic/main.go | 4 ++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index f2efee9682..140ba2fd80 100644 --- a/README.md +++ b/README.md @@ -578,7 +578,11 @@ print("run[CQ:image,file="+j["img"]+"]") - [x] 团队猜歌 - - [x] 设置缓存歌库路径 [绝对路径] + - [x] 设置猜歌缓存歌库路径 [绝对路径] + + - [x] 设置猜歌本地 [t/f] + + - [x] 设置猜歌Api [t/f] - 注:默认歌库为网易云热歌榜 diff --git a/plugin/guessmusic/main.go b/plugin/guessmusic/main.go index 3b103893b1..4574d9f18d 100644 --- a/plugin/guessmusic/main.go +++ b/plugin/guessmusic/main.go @@ -54,8 +54,8 @@ func init() { // 插件主体 "- 个人猜歌\n" + "- 团队猜歌\n" + "- 设置猜歌缓存歌库路径 [绝对路径]\n" + - "- 设置本地 [t/f]\n" + - "- 设置Api [t/f]\n" + + "- 设置猜歌本地 [t/f]\n" + + "- 设置猜歌Api [t/f]\n" + "注:默认歌库为网易云热歌榜\n" + "1.可在后面添加“-动漫”进行动漫歌猜歌\n-这个只能猜歌名和歌手\n" + "2.可在后面添加“-动漫2”进行动漫歌猜歌\n-这个可以猜番名,但歌手经常“未知”", From 697a632f8b07c36e3a1443dc4bc92073337455cd Mon Sep 17 00:00:00 2001 From: Fox_white Date: Thu, 30 Jun 2022 08:30:19 +0800 Subject: [PATCH 04/13] =?UTF-8?q?=E2=9C=A8=20=E7=8C=9C=E6=AD=8C=E9=94=99?= =?UTF-8?q?=E8=AF=AF=E4=BF=A1=E6=81=AF=E7=BB=A7=E6=89=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugin/guessmusic/main.go | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/plugin/guessmusic/main.go b/plugin/guessmusic/main.go index 4574d9f18d..60458ca76d 100644 --- a/plugin/guessmusic/main.go +++ b/plugin/guessmusic/main.go @@ -108,8 +108,6 @@ func init() { // 插件主体 musicPath += "/" } config.MusicPath = musicPath - k, _ := json.MarshalIndent(config, "", " ") - _ = os.WriteFile(cfgFile, k, 0644) if err == nil { ctx.SendChain(message.Text("成功!")) } else { @@ -130,7 +128,8 @@ func init() { // 插件主体 default: ctx.SendChain(message.Text("未知的设置类型,允许的类型为 缓存歌库路径, 本地, Api")) } - + k, _ := json.MarshalIndent(config, "", " ") + _ = os.WriteFile(cfgFile, k, 0644) }) engine.OnRegex(`^(个人|团队)猜歌(-动漫|-动漫2)?$`, zero.OnlyGroup).SetBlock(true).Limit(ctxext.LimitByGroup). Handle(func(ctx *zero.Ctx) { @@ -430,7 +429,7 @@ func getpaugramdata(musicPath string) (musicname string, err error) { downmusic := musicPath + "/" + musicname + ".mp3" response, err := http.Head(musicurl) if err != nil || response.StatusCode != 200 { - err = errors.Errorf("the music is missed") + err = errors.Errorf("the music is missed, %s", err) return } if file.IsNotExist(downmusic) { @@ -466,7 +465,7 @@ func getanimedata(musicPath string) (musicname string, err error) { downmusic := musicPath + "/" + musicname + ".mp3" response, err := http.Head(musicurl) if err != nil || response.StatusCode != 200 { - err = errors.Errorf("the music is missed") + err = errors.Errorf("the music is missed, %s", err) return } if file.IsNotExist(downmusic) { From d1291dc024fecc006fc4c9bfe82e02701b0b4ba0 Mon Sep 17 00:00:00 2001 From: Fox_white Date: Thu, 30 Jun 2022 09:51:23 +0800 Subject: [PATCH 05/13] =?UTF-8?q?=E2=9C=A8=20=E9=94=99=E8=AF=AF=E5=A4=84?= =?UTF-8?q?=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugin/guessmusic/main.go | 31 ++++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/plugin/guessmusic/main.go b/plugin/guessmusic/main.go index 60458ca76d..79c733743b 100644 --- a/plugin/guessmusic/main.go +++ b/plugin/guessmusic/main.go @@ -85,8 +85,14 @@ func init() { // 插件主体 return } } else { - k, _ := json.MarshalIndent(config, "", " ") - _ = os.WriteFile(cfgFile, k, 0644) + k, err := json.MarshalIndent(config, "", " ") + if err != nil { + return + } + err = os.WriteFile(cfgFile, k, 0644) + if err != nil { + return + } } engine.OnRegex(`^设置猜歌(.*)(.*)$`, func(ctx *zero.Ctx) bool { if !zero.SuperUserPermission(ctx) { @@ -102,34 +108,41 @@ func init() { // 插件主体 case "缓存歌库路径": if value == "" { ctx.SendChain(message.Text("请输入正确的路径!")) + return } musicPath := strings.ReplaceAll(value, "\\", "/") if !strings.HasSuffix(musicPath, "/") { musicPath += "/" } config.MusicPath = musicPath - if err == nil { - ctx.SendChain(message.Text("成功!")) - } else { - ctx.SendChain(message.Text("ERROR:", err)) - } case "本地": choice, err := strconv.ParseBool(value) if err != nil { ctx.SendChain(message.Text("ERROR:", err)) + return } config.Local = choice case "Api": choice, err := strconv.ParseBool(value) if err != nil { ctx.SendChain(message.Text("ERROR:", err)) + return } config.Api = choice default: ctx.SendChain(message.Text("未知的设置类型,允许的类型为 缓存歌库路径, 本地, Api")) + return + } + k, err := json.MarshalIndent(config, "", " ") + if err != nil { + ctx.SendChain(message.Text("ERROR:", err)) + } + err = os.WriteFile(cfgFile, k, 0644) + if err == nil { + ctx.SendChain(message.Text("成功!")) + } else { + ctx.SendChain(message.Text("ERROR:", err)) } - k, _ := json.MarshalIndent(config, "", " ") - _ = os.WriteFile(cfgFile, k, 0644) }) engine.OnRegex(`^(个人|团队)猜歌(-动漫|-动漫2)?$`, zero.OnlyGroup).SetBlock(true).Limit(ctxext.LimitByGroup). Handle(func(ctx *zero.Ctx) { From a6b5da3c424adefebc7c959d865cafe702efe013 Mon Sep 17 00:00:00 2001 From: Fox_white Date: Thu, 30 Jun 2022 09:56:07 +0800 Subject: [PATCH 06/13] =?UTF-8?q?=E2=9C=A8=20=E9=94=99=E8=AF=AF=E5=A4=84?= =?UTF-8?q?=E7=90=86ep2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugin/guessmusic/main.go | 1 + 1 file changed, 1 insertion(+) diff --git a/plugin/guessmusic/main.go b/plugin/guessmusic/main.go index 79c733743b..44982d1d78 100644 --- a/plugin/guessmusic/main.go +++ b/plugin/guessmusic/main.go @@ -136,6 +136,7 @@ func init() { // 插件主体 k, err := json.MarshalIndent(config, "", " ") if err != nil { ctx.SendChain(message.Text("ERROR:", err)) + return } err = os.WriteFile(cfgFile, k, 0644) if err == nil { From 89bf560fc3ba8ae002d45e3a68ea7b8a182dc3bd Mon Sep 17 00:00:00 2001 From: Fox_white Date: Thu, 30 Jun 2022 16:08:19 +0800 Subject: [PATCH 07/13] =?UTF-8?q?:bug:=20=E7=8C=9C=E6=AD=8C=E6=8F=92?= =?UTF-8?q?=E4=BB=B6bug=E4=BF=AE=E6=AD=A3=E5=92=8C=E5=91=BD=E5=90=8D?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 +- plugin/guessmusic/main.go | 285 ++++++++++++++++++++------------------ 2 files changed, 154 insertions(+), 135 deletions(-) diff --git a/README.md b/README.md index 140ba2fd80..9900bd8e96 100644 --- a/README.md +++ b/README.md @@ -580,9 +580,9 @@ print("run[CQ:image,file="+j["img"]+"]") - [x] 设置猜歌缓存歌库路径 [绝对路径] - - [x] 设置猜歌本地 [t/f] + - [x] 设置猜歌本地 [true/false] - - [x] 设置猜歌Api [t/f] + - [x] 设置猜歌Api [true/false] - 注:默认歌库为网易云热歌榜 diff --git a/plugin/guessmusic/main.go b/plugin/guessmusic/main.go index 44982d1d78..7e8051ea14 100644 --- a/plugin/guessmusic/main.go +++ b/plugin/guessmusic/main.go @@ -20,7 +20,7 @@ import ( ctrl "github.com/FloatTech/zbpctrl" "github.com/FloatTech/zbputils/binary" - control "github.com/FloatTech/zbputils/control" + "github.com/FloatTech/zbputils/control" "github.com/FloatTech/zbputils/ctxext" "github.com/FloatTech/zbputils/file" "github.com/FloatTech/zbputils/web" @@ -34,14 +34,14 @@ const ( var ( cuttime = [...]string{"00:00:05", "00:00:30", "00:01:00"} // 音乐切割时间点,可自行调节时间(时:分:秒) - config = Config{ // 默认 Config + cfg = config{ // 默认 config MusicPath: file.BOTPATH + "/data/guessmusic/music/", // 绝对路径,歌库根目录,通过指令进行更改 Local: true, // 是否使用本地音乐库 Api: true, // 是否使用 Api } ) -type Config struct { +type config struct { MusicPath string `json:"musicPath"` Local bool `json:"local"` Api bool `json:"api"` @@ -54,8 +54,8 @@ func init() { // 插件主体 "- 个人猜歌\n" + "- 团队猜歌\n" + "- 设置猜歌缓存歌库路径 [绝对路径]\n" + - "- 设置猜歌本地 [t/f]\n" + - "- 设置猜歌Api [t/f]\n" + + "- 设置猜歌本地 [true/false]\n" + + "- 设置猜歌Api [true/false]\n" + "注:默认歌库为网易云热歌榜\n" + "1.可在后面添加“-动漫”进行动漫歌猜歌\n-这个只能猜歌名和歌手\n" + "2.可在后面添加“-动漫2”进行动漫歌猜歌\n-这个可以猜番名,但歌手经常“未知”", @@ -77,24 +77,30 @@ func init() { // 插件主体 } cfgFile := engine.DataFolder() + "config.json" if file.IsExist(cfgFile) { - b, err := os.ReadFile(cfgFile) - if err != nil { - return - } - if err = json.Unmarshal(b, &config); err != nil { - return + reader, err := os.Open(cfgFile) + + defer func(reader *os.File) { + err = reader.Close() + if err != nil { + panic(err) + } + }(reader) + + if err == nil { + err = json.NewDecoder(reader).Decode(&cfg) + if err != nil { + panic(err) + } + } else { + panic(err) } } else { - k, err := json.MarshalIndent(config, "", " ") - if err != nil { - return - } - err = os.WriteFile(cfgFile, k, 0644) + err = saveConfig(cfgFile) if err != nil { - return + panic(err) } } - engine.OnRegex(`^设置猜歌(.*)(.*)$`, func(ctx *zero.Ctx) bool { + engine.OnRegex(`^设置猜歌(缓存歌库路径|本地|Api)\s*(.*)$`, func(ctx *zero.Ctx) bool { if !zero.SuperUserPermission(ctx) { ctx.SendChain(message.Text("只有bot主人可以设置!")) return false @@ -114,31 +120,23 @@ func init() { // 插件主体 if !strings.HasSuffix(musicPath, "/") { musicPath += "/" } - config.MusicPath = musicPath + cfg.MusicPath = musicPath case "本地": choice, err := strconv.ParseBool(value) if err != nil { ctx.SendChain(message.Text("ERROR:", err)) return } - config.Local = choice + cfg.Local = choice case "Api": choice, err := strconv.ParseBool(value) if err != nil { ctx.SendChain(message.Text("ERROR:", err)) return } - config.Api = choice - default: - ctx.SendChain(message.Text("未知的设置类型,允许的类型为 缓存歌库路径, 本地, Api")) - return - } - k, err := json.MarshalIndent(config, "", " ") - if err != nil { - ctx.SendChain(message.Text("ERROR:", err)) - return + cfg.Api = choice } - err = os.WriteFile(cfgFile, k, 0644) + err = saveConfig(cfgFile) if err == nil { ctx.SendChain(message.Text("成功!")) } else { @@ -155,29 +153,29 @@ func init() { // 插件主体 ctx.SendChain(message.Text("正在准备歌曲,请稍等\n回答“-[歌曲名称|歌手|提示|取消]”\n一共3段语音,6次机会")) } // 随机抽歌 - musicname, pathofmusic, err := musicLottery(mode, config.MusicPath) + musicName, pathOfMusic, err := musicLottery(mode, cfg.MusicPath) if err != nil { ctx.SendChain(message.Text(err)) return } // 切割音频,生成3个10秒的音频 outputPath := cachePath + gid + "/" - err = musiccut(musicname, pathofmusic, outputPath) + err = cutMusic(musicName, pathOfMusic, outputPath) if err != nil { ctx.SendChain(message.Text(err)) return } // 进行猜歌环节 ctx.SendChain(message.Record("file:///" + file.BOTPATH + "/" + outputPath + "0.wav")) - answerstring := strings.Split(musicname, " - ") + answerString := strings.Split(musicName, " - ") var next *zero.FutureEvent if ctx.State["regex_matched"].([]string)[1] == "个人" { next = zero.NewFutureEvent("message", 999, false, zero.OnlyGroup, zero.RegexRule(`^-\S{1,}`), ctx.CheckSession()) } else { next = zero.NewFutureEvent("message", 999, false, zero.OnlyGroup, zero.RegexRule(`^-\S{1,}`), zero.CheckGroup(ctx.Event.GroupID)) } - var countofmusic = 0 // 音频数量 - var countofanswer = 0 // 问答次数 + var musicCount = 0 // 音频数量 + var answerCount = 0 // 问答次数 recv, cancel := next.Repeat() defer cancel() wait := time.NewTimer(40 * time.Second) @@ -191,24 +189,24 @@ func init() { // 插件主体 msg := make(message.Message, 0, 3) msg = append(msg, message.Reply(ctx.Event.MessageID)) msg = append(msg, message.Text("猜歌超时,游戏结束\n答案是:", - "\n歌名:", answerstring[0], - "\n歌手:", answerstring[1])) + "\n歌名:", answerString[0], + "\n歌手:", answerString[1])) if mode == "-动漫2" { - msg = append(msg, message.Text("\n歌曲出自:", answerstring[2])) + msg = append(msg, message.Text("\n歌曲出自:", answerString[2])) } ctx.Send(msg) return case <-wait.C: wait.Reset(40 * time.Second) - countofmusic++ - if countofmusic > 2 { + musicCount++ + if musicCount > 2 { wait.Stop() continue } ctx.SendChain( message.Text("好像有些难度呢,再听这段音频,要仔细听哦"), ) - ctx.SendChain(message.Record("file:///" + file.BOTPATH + "/" + outputPath + strconv.Itoa(countofmusic) + ".wav")) + ctx.SendChain(message.Record("file:///" + file.BOTPATH + "/" + outputPath + strconv.Itoa(musicCount) + ".wav")) case c := <-recv: wait.Reset(40 * time.Second) tick.Reset(105 * time.Second) @@ -223,10 +221,10 @@ func init() { // 插件主体 msg := make(message.Message, 0, 3) msg = append(msg, message.Reply(c.Event.MessageID)) msg = append(msg, message.Text("游戏已取消,猜歌答案是", - "\n歌名:", answerstring[0], - "\n歌手:", answerstring[1])) + "\n歌名:", answerString[0], + "\n歌手:", answerString[1])) if mode == "-动漫2" { - msg = append(msg, message.Text("\n歌曲出自:", answerstring[2])) + msg = append(msg, message.Text("\n歌曲出自:", answerString[2])) } ctx.Send(msg) return @@ -237,8 +235,8 @@ func init() { // 插件主体 ), ) case answer == "提示": - countofmusic++ - if countofmusic > 2 { + musicCount++ + if musicCount > 2 { wait.Stop() ctx.Send( message.ReplyWithMessage(c.Event.MessageID, @@ -253,87 +251,87 @@ func init() { // 插件主体 message.Text("再听这段音频,要仔细听哦"), ), ) - ctx.SendChain(message.Record("file:///" + file.BOTPATH + "/" + outputPath + strconv.Itoa(countofmusic) + ".wav")) - case strings.Contains(answerstring[0], answer) || strings.EqualFold(answerstring[0], answer): + ctx.SendChain(message.Record("file:///" + file.BOTPATH + "/" + outputPath + strconv.Itoa(musicCount) + ".wav")) + case strings.Contains(answerString[0], answer) || strings.EqualFold(answerString[0], answer): wait.Stop() tick.Stop() after.Stop() msg := make(message.Message, 0, 3) msg = append(msg, message.Reply(c.Event.MessageID)) msg = append(msg, message.Text("太棒了,你猜对歌曲名了!答案是", - "\n歌名:", answerstring[0], - "\n歌手:", answerstring[1])) + "\n歌名:", answerString[0], + "\n歌手:", answerString[1])) if mode == "-动漫2" { - msg = append(msg, message.Text("\n歌曲出自:", answerstring[2])) + msg = append(msg, message.Text("\n歌曲出自:", answerString[2])) } ctx.Send(msg) return - case answerstring[1] == "未知" && answer == "未知": + case answerString[1] == "未知" && answer == "未知": ctx.Send( message.ReplyWithMessage(c.Event.MessageID, message.Text("该模式禁止回答“未知”"), ), ) - case strings.Contains(answerstring[1], answer) || strings.EqualFold(answerstring[1], answer): + case strings.Contains(answerString[1], answer) || strings.EqualFold(answerString[1], answer): wait.Stop() tick.Stop() after.Stop() msg := make(message.Message, 0, 3) msg = append(msg, message.Reply(c.Event.MessageID)) msg = append(msg, message.Text("太棒了,你猜对歌手名了!答案是", - "\n歌名:", answerstring[0], - "\n歌手:", answerstring[1])) + "\n歌名:", answerString[0], + "\n歌手:", answerString[1])) if mode == "-动漫2" { - msg = append(msg, message.Text("\n歌曲出自:", answerstring[2])) + msg = append(msg, message.Text("\n歌曲出自:", answerString[2])) } ctx.Send(msg) return default: - if mode == "-动漫2" && (strings.Contains(answerstring[2], answer) || strings.EqualFold(answerstring[2], answer)) { + if mode == "-动漫2" && (strings.Contains(answerString[2], answer) || strings.EqualFold(answerString[2], answer)) { wait.Stop() tick.Stop() after.Stop() ctx.Send(message.ReplyWithMessage(c.Event.MessageID, message.Text("太棒了,你猜对番剧名了!答案是:", - "\n歌名:", answerstring[0], - "\n歌手:", answerstring[1], - "\n歌曲出自:", answerstring[2]), + "\n歌名:", answerString[0], + "\n歌手:", answerString[1], + "\n歌曲出自:", answerString[2]), )) return } - countofmusic++ + musicCount++ switch { - case countofmusic > 2 && countofanswer < 6: + case musicCount > 2 && answerCount < 6: wait.Stop() - countofanswer++ + answerCount++ ctx.Send( message.ReplyWithMessage(c.Event.MessageID, message.Text("答案不对哦,加油啊~"), ), ) - case countofmusic > 2: + case musicCount > 2: wait.Stop() tick.Stop() after.Stop() msg := make(message.Message, 0, 3) msg = append(msg, message.Reply(c.Event.MessageID)) msg = append(msg, message.Text("次数到了,你没能猜出来。\n答案是:", - "\n歌名:", answerstring[0], - "\n歌手:", answerstring[1])) + "\n歌名:", answerString[0], + "\n歌手:", answerString[1])) if mode == "-动漫2" { - msg = append(msg, message.Text("\n歌曲出自:", answerstring[2])) + msg = append(msg, message.Text("\n歌曲出自:", answerString[2])) } ctx.Send(msg) return default: wait.Reset(40 * time.Second) - countofanswer++ + answerCount++ ctx.Send( message.ReplyWithMessage(c.Event.MessageID, message.Text("答案不对,再听这段音频,要仔细听哦"), ), ) - ctx.SendChain(message.Record("file:///" + file.BOTPATH + "/" + outputPath + strconv.Itoa(countofmusic) + ".wav")) + ctx.SendChain(message.Record("file:///" + file.BOTPATH + "/" + outputPath + strconv.Itoa(musicCount) + ".wav")) } } } @@ -341,91 +339,104 @@ func init() { // 插件主体 }) } +func saveConfig(cfgFile string) (err error) { + if reader, err := os.OpenFile(cfgFile, os.O_CREATE, os.ModePerm); err == nil { + err = json.NewEncoder(reader).Encode(&cfg) + if err != nil { + return err + } + } else { + return err + } + return nil +} + // 随机抽取音乐 -func musicLottery(mode, musicPath string) (musicname, pathofmusic string, err error) { +func musicLottery(mode, musicPath string) (musicName, pathOfMusic string, err error) { switch mode { case "-动漫": - pathofmusic = musicPath + "动漫/" + pathOfMusic = musicPath + "动漫/" case "-动漫2": - pathofmusic = musicPath + "动漫2/" + pathOfMusic = musicPath + "动漫2/" default: - pathofmusic = musicPath + "歌榜/" + pathOfMusic = musicPath + "歌榜/" } - err = os.MkdirAll(pathofmusic, 0755) + err = os.MkdirAll(pathOfMusic, 0755) if err != nil { err = errors.Errorf("[生成文件夹错误]ERROR:%s", err) return } - files, err := ioutil.ReadDir(pathofmusic) + files, err := ioutil.ReadDir(pathOfMusic) if err != nil { err = errors.Errorf("[读取本地列表错误]ERROR:%s", err) return } - if config.Local && config.Api { + if cfg.Local && cfg.Api { switch { case len(files) == 0: // 如果没有任何本地就下载歌曲 - musicname, err = getApiMusic(mode, pathofmusic) + musicName, err = getApiMusic(mode, pathOfMusic) if err != nil { err = errors.Errorf("[本地数据为0,歌曲下载错误]ERROR:%s", err) return } case rand.Intn(2) == 0: // [0,1)只会取到0,rand不允许的 - musicname = getLocalMusic(files) + musicName = getLocalMusic(files) default: - musicname, err = getApiMusic(mode, pathofmusic) + musicName, err = getApiMusic(mode, pathOfMusic) if err != nil { // 如果下载失败就从本地抽一个歌曲 - musicname = getLocalMusic(files) + musicName = getLocalMusic(files) err = nil } } return } - if config.Local { + if cfg.Local { if len(files) == 0 { - err = errors.Errorf("[本地数据为0,未开启API数据]") + err = errors.New("[本地数据为0,未开启API数据]") return } - musicname = getLocalMusic(files) + musicName = getLocalMusic(files) return } - if config.Api { - musicname, err = getApiMusic(mode, pathofmusic) + if cfg.Api { + musicName, err = getApiMusic(mode, pathOfMusic) if err != nil { - err = errors.Errorf("[获取API失败,未开启本地数据]ERROR:%s", err) + err = errors.Errorf("[获取API失败,未开启本地数据] ERROR:%s", err) + return } return } - err = errors.Errorf("[未开启API以及本地数据]") + err = errors.New("[未开启API以及本地数据]") return } -func getApiMusic(mode string, pathofmusic string) (musicname string, err error) { +func getApiMusic(mode string, musicPath string) (musicName string, err error) { switch mode { case "-动漫": - musicname, err = getpaugramdata(pathofmusic) + musicName, err = getPaugramData(musicPath) case "-动漫2": - musicname, err = getanimedata(pathofmusic) + musicName, err = getAnimeData(musicPath) default: - musicname, err = getuomgdata(pathofmusic) + musicName, err = getUOMGData(musicPath) } return } -func getLocalMusic(files []fs.FileInfo) (musicname string) { +func getLocalMusic(files []fs.FileInfo) (musicName string) { if len(files) > 1 { - musicname = strings.Replace(files[rand.Intn(len(files))].Name(), ".mp3", "", 1) + musicName = strings.Replace(files[rand.Intn(len(files))].Name(), ".mp3", "", 1) } else { - musicname = strings.Replace(files[0].Name(), ".mp3", "", 1) + musicName = strings.Replace(files[0].Name(), ".mp3", "", 1) } return } // 下载保罗API的歌曲 -func getpaugramdata(musicPath string) (musicname string, err error) { +func getPaugramData(musicPath string) (musicName string, err error) { api := "https://api.paugram.com/acgm/?list=1" referer := "https://api.paugram.com/" data, err := web.RequestDataWith(web.NewDefaultClient(), api, "GET", referer, ua) @@ -433,25 +444,29 @@ func getpaugramdata(musicPath string) (musicname string, err error) { return } name := gjson.Get(binary.BytesToString(data), "title").String() - artistsname := gjson.Get(binary.BytesToString(data), "artist").String() - musicurl := gjson.Get(binary.BytesToString(data), "link").String() - if name == "" || artistsname == "" { - err = errors.Errorf("the music is missed") + artistsName := gjson.Get(binary.BytesToString(data), "artist").String() + musicURL := gjson.Get(binary.BytesToString(data), "link").String() + if name == "" || artistsName == "" { + err = errors.New("下载音乐失败") + return + } + musicName = name + " - " + artistsName + downMusic := musicPath + "/" + musicName + ".mp3" + response, err := http.Head(musicURL) + if err != nil { + err = errors.Errorf("下载音乐失败, ERROR: %s", err) return } - musicname = name + " - " + artistsname - downmusic := musicPath + "/" + musicname + ".mp3" - response, err := http.Head(musicurl) - if err != nil || response.StatusCode != 200 { - err = errors.Errorf("the music is missed, %s", err) + if response.StatusCode != 200 { + err = errors.Errorf("下载音乐失败, Status Code: %d", response.StatusCode) return } - if file.IsNotExist(downmusic) { - data, err = web.GetData(musicurl + ".mp3") + if file.IsNotExist(downMusic) { + data, err = web.GetData(musicURL + ".mp3") if err != nil { return } - err = os.WriteFile(downmusic, data, 0666) + err = os.WriteFile(downMusic, data, 0666) if err != nil { return } @@ -460,7 +475,7 @@ func getpaugramdata(musicPath string) (musicname string, err error) { } // 下载animeMusic API的歌曲 -func getanimedata(musicPath string) (musicname string, err error) { +func getAnimeData(musicPath string) (musicName string, err error) { api := "https://anime-music.jijidown.com/api/v2/music" referer := "https://anime-music.jijidown.com/" data, err := web.RequestDataWith(web.NewDefaultClient(), api, "GET", referer, ua) @@ -468,26 +483,30 @@ func getanimedata(musicPath string) (musicname string, err error) { return } name := gjson.Get(binary.BytesToString(data), "res").Get("title").String() - artistsname := gjson.Get(binary.BytesToString(data), "res").Get("author").String() - acgname := gjson.Get(binary.BytesToString(data), "res").Get("anime_info").Get("title").String() - musicurl := gjson.Get(binary.BytesToString(data), "res").Get("play_url").String() - if name == "" || artistsname == "" { - err = errors.Errorf("the music is missed") + artistName := gjson.Get(binary.BytesToString(data), "res").Get("author").String() + acgName := gjson.Get(binary.BytesToString(data), "res").Get("anime_info").Get("title").String() + musicURL := gjson.Get(binary.BytesToString(data), "res").Get("play_url").String() + if name == "" || artistName == "" { + err = errors.New("下载音乐失败") + return + } + musicName = name + " - " + artistName + " - " + acgName + downMusic := musicPath + "/" + musicName + ".mp3" + response, err := http.Head(musicURL) + if err != nil { + err = errors.Errorf("下载音乐失败, ERROR: %s", err) return } - musicname = name + " - " + artistsname + " - " + acgname - downmusic := musicPath + "/" + musicname + ".mp3" - response, err := http.Head(musicurl) - if err != nil || response.StatusCode != 200 { - err = errors.Errorf("the music is missed, %s", err) + if response.StatusCode != 200 { + err = errors.Errorf("下载音乐失败, Status Code: %d", response.StatusCode) return } - if file.IsNotExist(downmusic) { - data, err = web.GetData(musicurl + ".mp3") + if file.IsNotExist(downMusic) { + data, err = web.GetData(musicURL + ".mp3") if err != nil { return } - err = os.WriteFile(downmusic, data, 0666) + err = os.WriteFile(downMusic, data, 0666) if err != nil { return } @@ -496,25 +515,25 @@ func getanimedata(musicPath string) (musicname string, err error) { } // 下载网易云热歌榜音乐 -func getuomgdata(musicPath string) (musicname string, err error) { +func getUOMGData(musicPath string) (musicname string, err error) { api := "https://api.uomg.com/api/rand.music?sort=%E7%83%AD%E6%AD%8C%E6%A6%9C&format=json" referer := "https://api.uomg.com/api/rand.music" data, err := web.RequestDataWith(web.NewDefaultClient(), api, "GET", referer, ua) if err != nil { return } - musicdata := gjson.Get(binary.BytesToString(data), "data") - name := musicdata.Get("name").String() - musicurl := musicdata.Get("url").String() - artistsname := musicdata.Get("artistsname").String() - musicname = name + " - " + artistsname - downmusic := musicPath + "/" + musicname + ".mp3" - if file.IsNotExist(downmusic) { - data, err = web.GetData(musicurl + ".mp3") + musicData := gjson.Get(binary.BytesToString(data), "data") + name := musicData.Get("name").String() + musicURL := musicData.Get("url").String() + artistsName := musicData.Get("artistsname").String() + musicname = name + " - " + artistsName + downMusic := musicPath + "/" + musicname + ".mp3" + if file.IsNotExist(downMusic) { + data, err = web.GetData(musicURL + ".mp3") if err != nil { return } - err = os.WriteFile(downmusic, data, 0666) + err = os.WriteFile(downMusic, data, 0666) if err != nil { return } @@ -523,14 +542,14 @@ func getuomgdata(musicPath string) (musicname string, err error) { } // 切割音乐成三个10s音频 -func musiccut(musicname, pathofmusic, outputPath string) (err error) { +func cutMusic(musicName, pathOfMusic, outputPath string) (err error) { err = os.MkdirAll(outputPath, 0755) if err != nil { err = errors.Errorf("[生成歌曲目录错误]ERROR:%s", err) return } var stderr bytes.Buffer - cmdArguments := []string{"-y", "-i", pathofmusic + musicname + ".mp3", + cmdArguments := []string{"-y", "-i", pathOfMusic + musicName + ".mp3", "-ss", cuttime[0], "-t", "10", file.BOTPATH + "/" + outputPath + "0.wav", "-ss", cuttime[1], "-t", "10", file.BOTPATH + "/" + outputPath + "1.wav", "-ss", cuttime[2], "-t", "10", file.BOTPATH + "/" + outputPath + "2.wav", "-hide_banner"} From 9448fff18793c8a18d976224be9ae89c44c6a73a Mon Sep 17 00:00:00 2001 From: Fox_white Date: Thu, 30 Jun 2022 22:24:42 +0800 Subject: [PATCH 08/13] =?UTF-8?q?=E2=9C=A8=20=E7=8C=9C=E6=AD=8C=E6=8F=92?= =?UTF-8?q?=E4=BB=B6=E4=B8=8D=E5=86=8D=E4=BD=BF=E7=94=A8gjson?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugin/guessmusic/main.go | 64 +++++++++++++++++++------------------ plugin/guessmusic/struct.go | 53 ++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 31 deletions(-) create mode 100644 plugin/guessmusic/struct.go diff --git a/plugin/guessmusic/main.go b/plugin/guessmusic/main.go index 7e8051ea14..30d4b69b53 100644 --- a/plugin/guessmusic/main.go +++ b/plugin/guessmusic/main.go @@ -19,12 +19,10 @@ import ( "github.com/wdvxdr1123/ZeroBot/message" ctrl "github.com/FloatTech/zbpctrl" - "github.com/FloatTech/zbputils/binary" "github.com/FloatTech/zbputils/control" "github.com/FloatTech/zbputils/ctxext" "github.com/FloatTech/zbputils/file" "github.com/FloatTech/zbputils/web" - "github.com/tidwall/gjson" "github.com/wdvxdr1123/ZeroBot/extension/single" ) @@ -41,12 +39,6 @@ var ( } ) -type config struct { - MusicPath string `json:"musicPath"` - Local bool `json:"local"` - Api bool `json:"api"` -} - func init() { // 插件主体 engine := control.Register("guessmusic", &ctrl.Options[*zero.Ctx]{ DisableOnDefault: false, @@ -78,14 +70,6 @@ func init() { // 插件主体 cfgFile := engine.DataFolder() + "config.json" if file.IsExist(cfgFile) { reader, err := os.Open(cfgFile) - - defer func(reader *os.File) { - err = reader.Close() - if err != nil { - panic(err) - } - }(reader) - if err == nil { err = json.NewDecoder(reader).Decode(&cfg) if err != nil { @@ -94,6 +78,10 @@ func init() { // 插件主体 } else { panic(err) } + err = reader.Close() + if err != nil { + panic(err) + } } else { err = saveConfig(cfgFile) if err != nil { @@ -421,7 +409,7 @@ func getApiMusic(mode string, musicPath string) (musicName string, err error) { case "-动漫2": musicName, err = getAnimeData(musicPath) default: - musicName, err = getUOMGData(musicPath) + musicName, err = getNetEaseData(musicPath) } return } @@ -443,9 +431,14 @@ func getPaugramData(musicPath string) (musicName string, err error) { if err != nil { return } - name := gjson.Get(binary.BytesToString(data), "title").String() - artistsName := gjson.Get(binary.BytesToString(data), "artist").String() - musicURL := gjson.Get(binary.BytesToString(data), "link").String() + var parsed paugramData + err = json.Unmarshal(data, &parsed) + if err != nil { + return + } + name := parsed.Title + artistsName := parsed.Artist + musicURL := parsed.Link if name == "" || artistsName == "" { err = errors.New("下载音乐失败") return @@ -482,10 +475,15 @@ func getAnimeData(musicPath string) (musicName string, err error) { if err != nil { return } - name := gjson.Get(binary.BytesToString(data), "res").Get("title").String() - artistName := gjson.Get(binary.BytesToString(data), "res").Get("author").String() - acgName := gjson.Get(binary.BytesToString(data), "res").Get("anime_info").Get("title").String() - musicURL := gjson.Get(binary.BytesToString(data), "res").Get("play_url").String() + var parsed animeData + err = json.Unmarshal(data, &parsed) + if err != nil { + return + } + name := parsed.Res.Title + artistName := parsed.Res.Author + acgName := parsed.Res.AnimeInfo.Title + musicURL := parsed.Res.PlayURL if name == "" || artistName == "" { err = errors.New("下载音乐失败") return @@ -515,19 +513,23 @@ func getAnimeData(musicPath string) (musicName string, err error) { } // 下载网易云热歌榜音乐 -func getUOMGData(musicPath string) (musicname string, err error) { +func getNetEaseData(musicPath string) (musicName string, err error) { api := "https://api.uomg.com/api/rand.music?sort=%E7%83%AD%E6%AD%8C%E6%A6%9C&format=json" referer := "https://api.uomg.com/api/rand.music" data, err := web.RequestDataWith(web.NewDefaultClient(), api, "GET", referer, ua) if err != nil { return } - musicData := gjson.Get(binary.BytesToString(data), "data") - name := musicData.Get("name").String() - musicURL := musicData.Get("url").String() - artistsName := musicData.Get("artistsname").String() - musicname = name + " - " + artistsName - downMusic := musicPath + "/" + musicname + ".mp3" + var parsed netEaseData + err = json.Unmarshal(data, &parsed) + if err != nil { + return + } + name := parsed.Data.Name + musicURL := parsed.Data.URL + artistsName := parsed.Data.Artistsname + musicName = name + " - " + artistsName + downMusic := musicPath + "/" + musicName + ".mp3" if file.IsNotExist(downMusic) { data, err = web.GetData(musicURL + ".mp3") if err != nil { diff --git a/plugin/guessmusic/struct.go b/plugin/guessmusic/struct.go new file mode 100644 index 0000000000..08b0ea4e6e --- /dev/null +++ b/plugin/guessmusic/struct.go @@ -0,0 +1,53 @@ +package guessmusic + +type config struct { + MusicPath string `json:"musicPath"` + Local bool `json:"local"` + Api bool `json:"api"` +} + +type paugramData struct { + ID int `json:"id"` + Title string `json:"title"` + Artist string `json:"artist"` + Album string `json:"album"` + Cover string `json:"cover"` + Lyric string `json:"lyric"` + SubLyric string `json:"sub_lyric"` + Link string `json:"link"` + Cached bool `json:"cached"` +} + +type animeData struct { + Msg string `json:"msg"` + Res struct { + ID string `json:"id"` + AnimeInfo struct { + Desc string `json:"desc"` + ID string `json:"id"` + Atime int `json:"atime"` + Logo string `json:"logo"` + Year int `json:"year"` + Bg string `json:"bg"` + Title string `json:"title"` + Month int `json:"month"` + } `json:"anime_info"` + PlayURL string `json:"play_url"` + Atime int `json:"atime"` + Title string `json:"title"` + Author string `json:"author"` + Type string `json:"type"` + Recommend bool `json:"recommend"` + } `json:"res"` + Code int `json:"code"` +} + +type netEaseData struct { + Code int `json:"code"` + Data struct { + Name string `json:"name"` + URL string `json:"url"` + Picurl string `json:"picurl"` + Artistsname string `json:"artistsname"` + } `json:"data"` +} From 3516088fba64133e8e0edccf5a27181a59104192 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=96=B9=E6=9F=B3=E7=85=9C?= <101934327+fangliuyu@users.noreply.github.com> Date: Fri, 1 Jul 2022 22:15:26 +0800 Subject: [PATCH 09/13] Update struct.go --- plugin/guessmusic/struct.go | 54 +++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/plugin/guessmusic/struct.go b/plugin/guessmusic/struct.go index 08b0ea4e6e..8a0bf94c97 100644 --- a/plugin/guessmusic/struct.go +++ b/plugin/guessmusic/struct.go @@ -51,3 +51,57 @@ type netEaseData struct { Artistsname string `json:"artistsname"` } `json:"data"` } + +type autumnfishData struct { + Result struct { + Songs []struct { + ID int `json:"id"` + Name string `json:"name"` + Artists []struct { + ID int `json:"id"` + Name string `json:"name"` + PicURL interface{} `json:"picUrl"` + Alias []interface{} `json:"alias"` + AlbumSize int `json:"albumSize"` + PicID int `json:"picId"` + Img1V1URL string `json:"img1v1Url"` + Img1V1 int `json:"img1v1"` + Trans interface{} `json:"trans"` + } `json:"artists"` + Album struct { + ID int `json:"id"` + Name string `json:"name"` + Artist struct { + ID int `json:"id"` + Name string `json:"name"` + PicURL interface{} `json:"picUrl"` + Alias []interface{} `json:"alias"` + AlbumSize int `json:"albumSize"` + PicID int `json:"picId"` + Img1V1URL string `json:"img1v1Url"` + Img1V1 int `json:"img1v1"` + Trans interface{} `json:"trans"` + } `json:"artist"` + PublishTime int64 `json:"publishTime"` + Size int `json:"size"` + CopyrightID int `json:"copyrightId"` + Status int `json:"status"` + PicID int64 `json:"picId"` + Mark int `json:"mark"` + } `json:"album"` + Duration int `json:"duration"` + CopyrightID int `json:"copyrightId"` + Status int `json:"status"` + Alias []interface{} `json:"alias"` + Rtype int `json:"rtype"` + Ftype int `json:"ftype"` + Mvid int `json:"mvid"` + Fee int `json:"fee"` + RURL interface{} `json:"rUrl"` + Mark int `json:"mark"` + } `json:"songs"` + HasMore bool `json:"hasMore"` + SongCount int `json:"songCount"` + } `json:"result"` + Code int `json:"code"` +} From bf4cc058af1ab1940c765b2d49b05fe967f575a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=96=B9=E6=9F=B3=E7=85=9C?= <101934327+fangliuyu@users.noreply.github.com> Date: Fri, 1 Jul 2022 22:18:42 +0800 Subject: [PATCH 10/13] =?UTF-8?q?=E4=BF=AE=E5=A4=8D-=E5=8A=A8=E6=BC=AB2?= =?UTF-8?q?=E6=97=A0=E6=B3=95=E4=B8=8B=E8=BD=BD=E6=AD=8C=E6=9B=B2=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugin/guessmusic/main.go | 39 +++++++++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/plugin/guessmusic/main.go b/plugin/guessmusic/main.go index 30d4b69b53..464ab2066d 100644 --- a/plugin/guessmusic/main.go +++ b/plugin/guessmusic/main.go @@ -440,7 +440,7 @@ func getPaugramData(musicPath string) (musicName string, err error) { artistsName := parsed.Artist musicURL := parsed.Link if name == "" || artistsName == "" { - err = errors.New("下载音乐失败") + err = errors.New("无法获API取歌曲信息") return } musicName = name + " - " + artistsName @@ -455,7 +455,7 @@ func getPaugramData(musicPath string) (musicName string, err error) { return } if file.IsNotExist(downMusic) { - data, err = web.GetData(musicURL + ".mp3") + data, err = web.GetData(musicURL) if err != nil { return } @@ -483,13 +483,36 @@ func getAnimeData(musicPath string) (musicName string, err error) { name := parsed.Res.Title artistName := parsed.Res.Author acgName := parsed.Res.AnimeInfo.Title - musicURL := parsed.Res.PlayURL + //musicURL := parsed.Res.PlayURL if name == "" || artistName == "" { - err = errors.New("下载音乐失败") + err = errors.New("无法获API取歌曲信息") return } + requestURL := "https://autumnfish.cn/search?keywords=" + url.QueryEscape(name+" "+artistName) + "&limit=1" + if artistName == "未知" { + requestURL = "https://autumnfish.cn/search?keywords=" + url.QueryEscape(acgName+" "+name) + "&limit=1" + } + data, err = web.GetData(requestURL) + if err != nil { + err = errors.Errorf("API歌曲查询失败, ERROR: %s", err) + return + } + var autumnfish autumnfishData + err = json.Unmarshal(data, &autumnfish) + if err != nil { + return + } + if autumnfish.Code != 200 { + err = errors.Errorf("下载音乐失败, Status Code: %d", autumnfish.Code) + return + } + musicID := strconv.Itoa(autumnfish.Result.Songs[0].ID) + if artistName == "未知" { + artistName = strings.ReplaceAll(autumnfish.Result.Songs[0].Artists[0].Name, " - ", "-") + } musicName = name + " - " + artistName + " - " + acgName downMusic := musicPath + "/" + musicName + ".mp3" + musicURL := "http://music.163.com/song/media/outer/url?id=" + musicID response, err := http.Head(musicURL) if err != nil { err = errors.Errorf("下载音乐失败, ERROR: %s", err) @@ -500,7 +523,7 @@ func getAnimeData(musicPath string) (musicName string, err error) { return } if file.IsNotExist(downMusic) { - data, err = web.GetData(musicURL + ".mp3") + data, err = web.GetData(musicURL) if err != nil { return } @@ -528,10 +551,14 @@ func getNetEaseData(musicPath string) (musicName string, err error) { name := parsed.Data.Name musicURL := parsed.Data.URL artistsName := parsed.Data.Artistsname + if name == "" || artistsName == "" { + err = errors.New("无法获API取歌曲信息") + return + } musicName = name + " - " + artistsName downMusic := musicPath + "/" + musicName + ".mp3" if file.IsNotExist(downMusic) { - data, err = web.GetData(musicURL + ".mp3") + data, err = web.GetData(musicURL) if err != nil { return } From ec5fe4c98a5ae43298f5b519cc918e72f9f73f59 Mon Sep 17 00:00:00 2001 From: Fox_white Date: Sat, 2 Jul 2022 19:10:04 +0800 Subject: [PATCH 11/13] :bug: Resolve Compilation error --- plugin/guessmusic/main.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin/guessmusic/main.go b/plugin/guessmusic/main.go index 464ab2066d..8924362620 100644 --- a/plugin/guessmusic/main.go +++ b/plugin/guessmusic/main.go @@ -1,4 +1,3 @@ -// Package guessmusic 基于zbp的猜歌插件 package guessmusic import ( @@ -8,6 +7,7 @@ import ( "io/ioutil" "math/rand" "net/http" + "net/url" "os" "os/exec" "strconv" From 7bb4f8782fe8cb1604a442bbb5b9c6fd696d7229 Mon Sep 17 00:00:00 2001 From: Fox_white Date: Sat, 2 Jul 2022 19:43:06 +0800 Subject: [PATCH 12/13] :bug: Resolve Lint --- plugin/guessmusic/main.go | 17 +++++++++-------- plugin/guessmusic/struct.go | 2 +- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/plugin/guessmusic/main.go b/plugin/guessmusic/main.go index 8924362620..889d86c3e4 100644 --- a/plugin/guessmusic/main.go +++ b/plugin/guessmusic/main.go @@ -1,3 +1,4 @@ +// Package guessmusic GitHub 仓库搜索 package guessmusic import ( @@ -35,7 +36,7 @@ var ( cfg = config{ // 默认 config MusicPath: file.BOTPATH + "/data/guessmusic/music/", // 绝对路径,歌库根目录,通过指令进行更改 Local: true, // 是否使用本地音乐库 - Api: true, // 是否使用 Api + API: true, // 是否使用 Api } ) @@ -122,7 +123,7 @@ func init() { // 插件主体 ctx.SendChain(message.Text("ERROR:", err)) return } - cfg.Api = choice + cfg.API = choice } err = saveConfig(cfgFile) if err == nil { @@ -360,11 +361,11 @@ func musicLottery(mode, musicPath string) (musicName, pathOfMusic string, err er return } - if cfg.Local && cfg.Api { + if cfg.Local && cfg.API { switch { case len(files) == 0: // 如果没有任何本地就下载歌曲 - musicName, err = getApiMusic(mode, pathOfMusic) + musicName, err = getAPIMusic(mode, pathOfMusic) if err != nil { err = errors.Errorf("[本地数据为0,歌曲下载错误]ERROR:%s", err) return @@ -373,7 +374,7 @@ func musicLottery(mode, musicPath string) (musicName, pathOfMusic string, err er // [0,1)只会取到0,rand不允许的 musicName = getLocalMusic(files) default: - musicName, err = getApiMusic(mode, pathOfMusic) + musicName, err = getAPIMusic(mode, pathOfMusic) if err != nil { // 如果下载失败就从本地抽一个歌曲 musicName = getLocalMusic(files) @@ -390,8 +391,8 @@ func musicLottery(mode, musicPath string) (musicName, pathOfMusic string, err er musicName = getLocalMusic(files) return } - if cfg.Api { - musicName, err = getApiMusic(mode, pathOfMusic) + if cfg.API { + musicName, err = getAPIMusic(mode, pathOfMusic) if err != nil { err = errors.Errorf("[获取API失败,未开启本地数据] ERROR:%s", err) return @@ -402,7 +403,7 @@ func musicLottery(mode, musicPath string) (musicName, pathOfMusic string, err er return } -func getApiMusic(mode string, musicPath string) (musicName string, err error) { +func getAPIMusic(mode string, musicPath string) (musicName string, err error) { switch mode { case "-动漫": musicName, err = getPaugramData(musicPath) diff --git a/plugin/guessmusic/struct.go b/plugin/guessmusic/struct.go index 8a0bf94c97..dbad4bf493 100644 --- a/plugin/guessmusic/struct.go +++ b/plugin/guessmusic/struct.go @@ -3,7 +3,7 @@ package guessmusic type config struct { MusicPath string `json:"musicPath"` Local bool `json:"local"` - Api bool `json:"api"` + API bool `json:"api"` } type paugramData struct { From 40e37b655f41f941fe1f7e4952c0e80d912bfba8 Mon Sep 17 00:00:00 2001 From: Fox_white Date: Sat, 2 Jul 2022 19:43:53 +0800 Subject: [PATCH 13/13] :bug: Resolve Lint --- plugin/guessmusic/main.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin/guessmusic/main.go b/plugin/guessmusic/main.go index 889d86c3e4..b51d4655f4 100644 --- a/plugin/guessmusic/main.go +++ b/plugin/guessmusic/main.go @@ -1,4 +1,4 @@ -// Package guessmusic GitHub 仓库搜索 +// Package guessmusic 基于zbp的猜歌插件 package guessmusic import (