|
| 1 | +package baidubaike |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "net/http" |
| 8 | + "regexp" |
| 9 | + |
| 10 | + "github.com/yqchilde/pkgs/log" |
| 11 | + |
| 12 | + "github.com/yqchilde/wxbot/engine" |
| 13 | + "github.com/yqchilde/wxbot/engine/robot" |
| 14 | +) |
| 15 | + |
| 16 | +type BaiDuBaiKe struct{ engine.PluginMagic } |
| 17 | + |
| 18 | +var ( |
| 19 | + pluginInfo = &BaiDuBaiKe{ |
| 20 | + engine.PluginMagic{ |
| 21 | + Desc: "🚀 输入 {百度百科 XX} => 获取百度百科解释,Ps:百度百科 okr", |
| 22 | + Commands: []string{"^百度百科 ?(.*?)$"}, |
| 23 | + }, |
| 24 | + } |
| 25 | + _ = engine.InstallPlugin(pluginInfo) |
| 26 | +) |
| 27 | + |
| 28 | +func (p *BaiDuBaiKe) OnRegister() {} |
| 29 | + |
| 30 | +func (p *BaiDuBaiKe) OnEvent(msg *robot.Message) { |
| 31 | + if msg != nil { |
| 32 | + if msg.MatchRegexCommand(pluginInfo.Commands) { |
| 33 | + var re = regexp.MustCompile(`(?m)^百度百科 ?(.*?)$`) |
| 34 | + match := re.FindAllStringSubmatch(msg.Content, -1) |
| 35 | + if len(match) > 0 && len(match[0]) > 1 { |
| 36 | + if data, err := getBaiKe(match[0][1]); err == nil { |
| 37 | + if data == nil { |
| 38 | + msg.ReplyText("没查到该百科含义") |
| 39 | + } else { |
| 40 | + msg.ReplyText("🏷️ " + match[0][1] + ": " + fmt.Sprintf("%s\n🔎 摘要: %s\n© 版权: %s", data.Desc, data.Abstract, data.Copyrights)) |
| 41 | + } |
| 42 | + } else { |
| 43 | + msg.ReplyText("查询失败,这一定不是bug🤔") |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +func getBaiKe(keyword string) (*ApiResponse, error) { |
| 51 | + api := "https://baike.baidu.com/api/openapi/BaikeLemmaCardApi?appid=379020&bk_length=600&bk_key=" + keyword |
| 52 | + resp, err := http.Get(api) |
| 53 | + if err != nil { |
| 54 | + log.Errorf("failed to get baike api, err: %v", err) |
| 55 | + return nil, err |
| 56 | + } |
| 57 | + readAll, err := io.ReadAll(resp.Body) |
| 58 | + if err != nil { |
| 59 | + log.Errorf("failed to read resp body, err: %v", err) |
| 60 | + return nil, err |
| 61 | + } |
| 62 | + var data ApiResponse |
| 63 | + if err := json.Unmarshal(readAll, &data); err != nil { |
| 64 | + log.Errorf("failed to unmarshal api response, err: %v", err) |
| 65 | + return nil, err |
| 66 | + } |
| 67 | + return &data, nil |
| 68 | +} |
0 commit comments