diff --git a/chat/program b/chat/program new file mode 100644 index 00000000..95834099 --- /dev/null +++ b/chat/program @@ -0,0 +1,102 @@ +package program + +import ( + "encoding/json" + "fmt" + zero "github.com/wdvxdr1123/ZeroBot" + "io/ioutil" + "net/http" + "net/url" + "strings" + "time" +) + +func init() { + runTypes := map[string][2]string{ + "Go": {"6","go"}, + "C": {"7","c"}, + "C++": {"7","cpp"}, + "Java": {"8","java"}, + "C#": {"10","cs"}, + "Python": {"15","py3"}, + "Lua": {"17","lua"}, + } + + zero.OnCommand("runList").Handle(func(ctx *zero.Ctx) { + ctx.Send("Run 语种<<<\n代码块\n>>>\n支持语种: Go || Python || Java || C/C++ || C# || Lua") + }) + + zero.OnRegex("(?is:Run (.+?)<<<(.+?)>>>)").Handle(func(ctx *zero.Ctx) { + getType := ctx.State["regex_matched"].([]string)[1] + if runType,exist:=runTypes[getType];exist{ + println("正在尝试执行",getType,"代码块") + getCode := ctx.State["regex_matched"].([]string)[2] + getCode = strings.Replace(getCode,"[","[",-1) + getCode = strings.Replace(getCode,"]","]",-1) + + res := runCode(getCode,runType) + if res["errors"] == "\n\n"{ + ctx.Send(fmt.Sprintf( + "[CQ:at,qq=%d]本次%s语言代码执行结果如下:\n%s", + ctx.Event.UserID, + getType, + res["output"][:len(res["output"])-1], + )) + }else { + ctx.Send(fmt.Sprintf( + "[CQ:at,qq=%d]本次%s语言代码执行失败:%s", + ctx.Event.UserID, + getType, + res["errors"], + )) + } + }else { + ctx.Send(fmt.Sprintf( + "[CQ:at,qq=%d][%s]语言不是受支持的编程语种呢~", + ctx.Event.UserID, + getType, + )) + } + }) +} + +func runCode(code string,runType [2]string) map[string]string { + //对菜鸟api发送数据并返回结果 + result := map[string]string{} + api := "https://tool.runoob.com/compile2.php" + headers := map[string]string{ + "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", + "Referer": "https://c.runoob.com/", + "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:87.0) Gecko/20100101 Firefox/87.0", + } + data := map[string]string{ + "code": code, + "token": "4381fe197827ec87cbac9552f14ec62a", + "stdin": "", + "language": runType[0], + "fileext": runType[1], + } + json.Unmarshal(netPost(api,data,headers),&result) + return result +} + +func netPost(api string,data map[string]string,headers map[string]string) []byte { + //发送POST请求获取返回数据 + client := &http.Client{ + Timeout: time.Duration(6 * time.Second), + } + + param := url.Values{} + for key,value := range data{ + param.Set(key,value) + } + + request,_ := http.NewRequest("POST",api,strings.NewReader(param.Encode())) + for key,value := range headers{ + request.Header.Add(key,value) + } + res,_ := client.Do(request) + defer res.Body.Close() + result,_ := ioutil.ReadAll(res.Body) + return result +}