Compare commits

...

9 Commits

Author SHA1 Message Date
7f4945fc34 更新帮助
优化说明
2022-03-30 17:57:50 +08:00
3958c2a385 更新使用说明 2022-03-30 17:46:12 +08:00
646a340171 更新到v1.1.0
支持执行引用的代码(含pastebin网址)
执行引用的代码时,参数可包含输入
2022-03-30 17:28:19 +08:00
f374a446ee 更新到v1.0
弃用pastebin粘贴
增加pastebin运行支持
增加pastebin运行时增加输入
更新依赖
2022-03-30 11:19:59 +08:00
筱傑
8c3c316d5d 移除 第三方Json解析库,使用Mirai自带库
增加 获取代码模板功能
2021-08-02 22:51:22 +08:00
筱傑
17a8893fe8 Merge remote-tracking branch 'origin/master' 2021-08-02 13:25:45 +08:00
筱傑
5bbc3637be 修改 Glot接口增加代码模板文件的获取 2021-08-02 13:25:31 +08:00
608214a7b6
Create README.md 2021-08-01 22:50:41 +08:00
c91d715b5c
Create LICENSE 2021-08-01 15:39:08 +08:00
12 changed files with 335 additions and 217 deletions

143
LICENSE
View File

@ -1,5 +1,5 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
@ -7,17 +7,15 @@
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
@ -26,44 +24,34 @@ them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
@ -72,7 +60,7 @@ modification follow.
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
@ -549,35 +537,45 @@ to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
@ -635,40 +633,29 @@ the "copyright" line and a pointer to where the full notice is found.
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
GNU Affero General Public License for more details.
You should have received a copy of the GNU General Public License
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

55
README.md Normal file
View File

@ -0,0 +1,55 @@
# JCC - J Compiler Collection
## 基于Glot接口的mirai-console在线编译器插件
## `run`命令原型
- `run <language> <code>`
- `run <language> <pastebinUrl> [stdin]`
- `引用消息: run <language> [stdin]`
### 参数说明
| 参数 | 说明 | 示例 | 备注 |
| ---- | ---- | --- | --- |
| `language` | 编程语言 | `python` | 用`/jcc list`列出所有支持的语言 |
| `code` | 代码 | `print("Hello world")` | 要运行的代码,支持换行 |
| `pastebinUrl` | pastebin地址 | `https://pastebin.ubuntu.com/p/KhBB7ZjVbD/` | 需要在 [pastebin](https://pastebin.ubuntu.com/) 上传代码 |
| `stdin` | 标准输入 | `1 2 3 4 5` | 可选 用于`scanf`之类 |
## 使用示例
### 直接使用
`run python print("Hello world")`
### 从 [pastebinUrl](https://pastebin.ubuntu.com/) 运行代码:
`run c https://pastebin.ubuntu.com/p/KhBB7ZjVbD/`
### 从 引用 执行代码:
> 引用: print("Hello world")
`run python`
### 支持运行程序带输入:
#### 例1
`run c https://pastebin.ubuntu.com/p/S2PyvRqJNf/ 1 2 3 4 5`
#### 例2
> 引用: https://pastebin.ubuntu.com/p/S2PyvRqJNf/
`run c 1 2 3 4 5`
## 其他指令
- /jcc help # 帮助
- /jcc list # 列出所有支持的编程语言
- /jcc template <language> # 获取指定语言的模板
---
## 插件使用方法
本插件基于[Mirai-Console](https://github.com/mamoe/mirai-console)运行,您可以通过阅读[Mirai用户手册](https://docs.mirai.mamoe.net/UserManual.html)来了解如何安装、启动机器人。
`MiraiConsole`成功启动后,只需要将本项目[发布](https://github.com/jie65535/mirai-console-jcc-plugin/releases)的`.jar`文件放入`.\plugins\`目录下即可加载插件。
## 发布地址
本插件在[Mirai论坛](https://mirai.mamoe.net/)发布,[点击这里](https://mirai.mamoe.net/topic/463/jcc-%E5%9F%BA%E4%BA%8Emirai-console%E7%9A%84%E5%9C%A8%E7%BA%BF%E7%BC%96%E8%AF%91%E6%8F%92%E4%BB%B6)查看
## 反馈
如使用或安装插件过程中遇到非本插件功能问题,您首先应该在[Mirai论坛](https://mirai.mamoe.net/)中搜索解决方案,若未解决,可以在[本项目的主题贴](https://mirai.mamoe.net/topic/463/jcc-%E5%9F%BA%E4%BA%8Emirai-console%E7%9A%84%E5%9C%A8%E7%BA%BF%E7%BC%96%E8%AF%91%E6%8F%92%E4%BB%B6)中回帖提问。
如果是插件本身的问题或漏洞,您可以向我提交一个[issue](https://github.com/jie65535/mirai-console-jcc-plugin/issues)。若您有能力且愿意帮助我修复这些问题,请提交[Pull request](https://github.com/jie65535/mirai-console-jcc-plugin/pulls)。

View File

@ -1,13 +1,13 @@
plugins {
val kotlinVersion = "1.5.10"
val kotlinVersion = "1.6.10"
kotlin("jvm") version kotlinVersion
kotlin("plugin.serialization") version kotlinVersion
id("net.mamoe.mirai-console") version "2.6.7"
id("net.mamoe.mirai-console") version "2.10.0"
}
group = "me.jie65535"
version = "0.1"
group = "top.jie65535"
version = "1.1.0"
repositories {
maven("https://maven.aliyun.com/repository/public")
@ -16,5 +16,4 @@ repositories {
dependencies{
implementation("org.jsoup:jsoup:1.13.1")
implementation("com.beust:klaxon:5.5")
}

View File

@ -1 +1 @@
rootProject.name = "jcc"
rootProject.name = "mirai-console-jcc-plugin"

View File

@ -1,6 +1,5 @@
import com.beust.klaxon.Json
import com.beust.klaxon.Klaxon
import java.security.InvalidKeyException
import kotlinx.serialization.*
import kotlinx.serialization.json.*
/**
* # glot.io api 封装
@ -8,9 +7,8 @@ import java.security.InvalidKeyException
* 它提供了免费API供外界使用API文档见 [https://github.com/glotcode/glot/blob/master/api_docs]
* 本类是对该API文档的封装
* 通过 [listLanguages] 获取支持在线运行的编程语言列表
* ~~通过 [getVersion] 获取对应语言的最新版本请求地址~~
* 通过 [getSupport] 判断指定编程语言是否支持
* 通过 [getFilename] 来获取指定编程语言的文件runCode需要
* 通过 [getTemplateFile] 来获取指定编程语言的模板文件runCode需要
* 以上接口均有缓存仅首次获取不同数据时会发起请求因此首次运行可能较慢
* 通过 [runCode] 运行代码
* 若觉得原版 [runCode] 使用复杂还可以使用另一个更简单的重载 [runCode]
@ -22,19 +20,21 @@ object GlotAPI {
private const val URL_NEW = "https://glot.io/new/"
private const val URL_API = URL + "api/"
private const val URL_LIST_LANGUAGES = URL_API + "run"
// 运行代码需要api token这是的我号申请的,可以在[https://glot.io/auth/page/simple/register]注册帐号
// 运行代码需要api token这是的我号申请的,可以在[https://glot.io/auth/page/simple/register]注册帐号
private const val API_TOKEN = "074ef4a7-7a94-47f2-9891-85511ef1fb52"
@Serializable
data class Language(val name: String, val url: String)
@Serializable
data class CodeFile(val name: String, val content: String)
data class RunCodeRequest(@Json(serializeNull = false) val stdin: String?,
@Json(serializeNull = false) val command: String?,
@Serializable
data class RunCodeRequest(val stdin: String? = null,
val command: String? = null,
val files: List<CodeFile>)
@Serializable
data class RunResult(val stdout: String, val stderr: String, val error: String)
private var languages: List<Language>? = null
private val filenames: MutableMap<String, String> = mutableMapOf()
// val fileExtensions: Map<String, String> = mapOf("assembly" to "asm", "ats" to "dats", "bash" to "sh", "c" to "c", "clojure" to "clj", "cobol" to "cob", "coffeescript" to "coffee", "cpp" to "cpp", "crystal" to "cr", "csharp" to "cs", "d" to "d", "elixir" to "ex", "elm" to "elm", "erlang" to "erl", "fsharp" to "fs", "go" to "go", "groovy" to "groovy", "haskell" to "hs", "idris" to "idr", "java" to "java", "javascript" to "js", "julia" to "jl", "kotlin" to "kt", "lua" to "lua", "mercury" to "m", "nim" to "nim", "nix" to "nix", "ocaml" to "ml", "perl" to "pl", "php" to "php", "python" to "py", "raku" to "raku", "ruby" to "rb", "rust" to "rs", "scala" to "scala", "swift" to "swift", "typescript" to "ts", "plaintext" to "txt", )
/**
@ -54,10 +54,10 @@ object GlotAPI {
* ```
*/
fun listLanguages(): List<Language> {
if (languages == null) {
languages = Klaxon().parseArray(HttpUtil.get(URL_LIST_LANGUAGES)) ?: throw Exception("未获取到任何数据")
if (JccPluginData.languages.isEmpty()) {
JccPluginData.languages = Json.decodeFromString(HttpUtil.get(URL_LIST_LANGUAGES)) ?: throw Exception("未获取到任何数据")
}
return languages!!
return JccPluginData.languages
}
/**
@ -71,24 +71,24 @@ object GlotAPI {
* 获取编程语言请求地址若不支持将会抛出异常
* @param language 编程语言名字忽略大小写
* @return 返回语言请求地址
* @exception InvalidKeyException 不支持的语言
* @exception Exception 不支持的语言
*/
fun getSupport(language: String): Language =
listLanguages().find { it.name.equals(language, true) } ?: throw InvalidKeyException("不支持的语言")
listLanguages().find { it.name.equals(language, true) } ?: throw Exception("不支持的语言")
/**
* 获取指定编程语言文件名缓存
* @exception Exception 若不支持或无法获取将抛出异常
* @return 建议文件名通常是main.c之类的java比较特殊是Main.java所以需要请求避免硬编码
* 获取指定编程语言的模板文件缓存
*/
fun getFilename(language: String): String {
fun getTemplateFile(language: String): CodeFile {
val lang = getSupport(language)
if (filenames.containsKey(lang.name))
return filenames[lang.name]!!
if (JccPluginData.templateFiles.containsKey(lang.name))
return JccPluginData.templateFiles[lang.name]!!
val document = HttpUtil.getDocument(URL_NEW + lang.name)
val filename = HttpUtil.documentSelect(document, ".filename").firstOrNull()?.text() ?: throw Exception("无法获取文件名")
filenames[lang.name] = filename
return filename
val fileContent = HttpUtil.documentSelect(document, "#editor-1").text() ?: throw Exception("无法获取模板文件内容")
val templateFile = CodeFile(filename, fileContent)
JccPluginData.templateFiles[lang.name] = templateFile
return templateFile
}
/**
@ -164,8 +164,8 @@ object GlotAPI {
* 导致程序无法在限定时间内返回将会报告超时异常
*/
fun runCode(language: Language, requestData: RunCodeRequest): RunResult {
val response = HttpUtil.post(language.url + "/latest", Klaxon().toJsonString(requestData), mapOf("Authorization" to API_TOKEN))
return Klaxon().parse(response) ?: throw Exception("未获取到任何数据")
val response = HttpUtil.post(language.url + "/latest", Json.encodeToString(requestData), mapOf("Authorization" to API_TOKEN))
return Json.decodeFromString(response) ?: throw Exception("未获取到任何数据")
}
@ -179,5 +179,5 @@ object GlotAPI {
* 导致程序无法在限定时间内返回将会报告超时异常
*/
fun runCode(language: String, code: String, stdin: String? = null): RunResult =
runCode(getSupport(language), RunCodeRequest(stdin, null, listOf(CodeFile(getFilename(language), code))))
runCode(getSupport(language), RunCodeRequest(stdin, null, listOf(CodeFile(getTemplateFile(language).name, code))))
}

View File

@ -2,7 +2,6 @@ import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import org.jsoup.Jsoup
import org.jsoup.nodes.Document

View File

@ -1,99 +0,0 @@
import net.mamoe.mirai.console.command.CommandManager.INSTANCE.register
import net.mamoe.mirai.console.command.CommandManager.INSTANCE.unregister
import net.mamoe.mirai.console.command.parse.CommandCallParser
import net.mamoe.mirai.console.plugin.jvm.JvmPluginDescription
import net.mamoe.mirai.console.plugin.jvm.KotlinPlugin
import net.mamoe.mirai.contact.Group
import net.mamoe.mirai.contact.isBotMuted
import net.mamoe.mirai.event.globalEventChannel
import net.mamoe.mirai.event.subscribeMessages
import net.mamoe.mirai.message.data.At
import net.mamoe.mirai.message.data.MessageChainBuilder
import net.mamoe.mirai.utils.info
import okhttp3.internal.indexOfNonWhitespace
object JCC : KotlinPlugin(
JvmPluginDescription(
id = "me.jie65535.jcc",
name = "J Compiler Collection",
version = "0.1",
) {
author("jie65535")
info("""在线编译器集合""")
}
) {
const val CMD_PREFIX = "jcc"
override fun onEnable() {
logger.info { "Plugin loaded" }
JccCommand.register()
globalEventChannel().subscribeMessages {
startsWith(CMD_PREFIX, false) reply {
if (subject is Group && (subject as Group).isBotMuted)
return@reply null
val msg = it.substring(CMD_PREFIX.length).trim()
if (msg.isNotEmpty()) {
val index = msg.indexOfFirst(Char::isWhitespace)
if (index >= 0)
{
val language = msg.substring(0, index)
val code = msg.substring(index).trim()
if (!GlotAPI.checkSupport(language))
return@reply "不支持这种编程语言\n/jcc list #列出所有支持的编程语言"
if (code.isEmpty())
return@reply "请输入要运行的代码"
try {
// subject.sendMessage("正在执行,请稍等...")
logger.info("请求执行代码")
val result = GlotAPI.runCode(language, code)
val builder = MessageChainBuilder()
var c = 0
if (result.stdout.isNotEmpty()) c++
if (result.stderr.isNotEmpty()) c++
if (result.error.isNotEmpty()) c++
val title = c >= 2
var msgLength = 0
if (subject is Group) {
builder.add(At(sender))
builder.add("\n")
}
if (result.error.isNotEmpty()) {
builder.add("error:\n")
builder.add(result.error)
msgLength += result.error.length + 7
}
if (result.stdout.isNotEmpty()) {
if (title) builder.add("\nstdout:\n")
builder.add(result.stdout)
msgLength += result.stdout.length
}
if (result.stderr.isNotEmpty()) {
if (title) builder.add("\nstderr:\n")
builder.add(result.stderr)
msgLength += result.stderr.length
}
val messageChain = builder.build()
if (msgLength > 500) {
val messageContent = messageChain.contentToString()
return@reply "消息内容过长已贴到Pastebin\n" + UbuntuPastebinHelper.paste(messageContent)
} else {
return@reply messageChain
}
} catch (e: Exception) {
logger.warning(e)
return@reply "执行失败\n原因:${e.message}"
}
}
}
return@reply "请输入正确的命令!例如:\n$CMD_PREFIX python print(\"Hello world\")"
}
}
}
override fun onDisable() {
JccCommand.unregister()
}
}

View File

@ -0,0 +1,136 @@
import net.mamoe.mirai.console.command.CommandManager.INSTANCE.register
import net.mamoe.mirai.console.command.CommandManager.INSTANCE.unregister
import net.mamoe.mirai.console.plugin.PluginManager.INSTANCE.load
import net.mamoe.mirai.console.plugin.jvm.JvmPluginDescription
import net.mamoe.mirai.console.plugin.jvm.KotlinPlugin
import net.mamoe.mirai.contact.Group
import net.mamoe.mirai.contact.isBotMuted
import net.mamoe.mirai.event.events.GroupMessageEvent
import net.mamoe.mirai.event.events.MessageEvent
import net.mamoe.mirai.event.globalEventChannel
import net.mamoe.mirai.event.subscribeMessages
import net.mamoe.mirai.message.MessageReceipt
import net.mamoe.mirai.message.data.*
import net.mamoe.mirai.utils.info
object JCompilerCollection : KotlinPlugin(
JvmPluginDescription(
id = "top.jie65535.mirai-console-jcc-plugin",
name = "J Compiler Collection",
version = "1.1.0",
) {
author("jie65535")
info("""在线编译器集合""")
}
) {
const val CMD_PREFIX = "run"
private const val MSG_MAX_LENGTH = 550
override fun onEnable() {
logger.info { "Plugin loaded" }
JccCommand.register()
JccPluginData.reload()
globalEventChannel()
.parentScope(this)
.subscribeMessages {
content {
message.firstIsInstanceOrNull<PlainText>()?.content?.trimStart()?.startsWith(CMD_PREFIX) == true
} reply {
val msg = message.firstIsInstance<PlainText>().content.trimStart().removePrefix(CMD_PREFIX).trim()
if (msg.isBlank()) {
return@reply "请输入正确的命令!例如:\n$CMD_PREFIX python print(\"Hello world\")"
}
val index = msg.indexOfFirst(Char::isWhitespace)
val language = if (index >= 0) msg.substring(0, index) else msg
if (!GlotAPI.checkSupport(language))
return@reply "不支持这种编程语言\n/jcc list #列出所有支持的编程语言"
try {
// 检查命令的引用
val quote = message[QuoteReply]
var input: String? = null
// 支持运行引用的消息的代码
var code = if (quote != null) {
// run c [input]
if (index >= 0) {
input = msg.substring(index).trim()
}
quote.source.originalMessage.content
} else if (index >= 0) {
msg.substring(index).trim()
} else {
return@reply "$CMD_PREFIX $language\n" + GlotAPI.getTemplateFile(language).content
}
// 如果是引用消息,则不再从原消息中分析。否则,还要从消息中判断是否存在输入参数
val si = if (quote != null) 0 else code.indexOfFirst(Char::isWhitespace)
// 尝试得到url
val url = if (si > 0) {
code.substring(0, si)
} else {
code
}
// 如果参数是一个ubuntu pastebin的链接则去获取具体代码
if (UbuntuPastebinHelper.checkUrl(url)) {
if (si > 0) {
// 如果确实是一个链接,则链接后面跟的内容就是输入内容
input = code.substring(si+1)
}
logger.info("$url 中获取代码")
code = UbuntuPastebinHelper.get(url)
if (code.isBlank()) {
return@reply "未获取到有效代码"
}
}
// subject.sendMessage("正在执行,请稍等...")
logger.info("请求执行代码\n$code")
val result = GlotAPI.runCode(language, code, input)
val builder = MessageChainBuilder()
var c = 0
if (result.stdout.isNotEmpty()) c++
if (result.stderr.isNotEmpty()) c++
if (result.error.isNotEmpty()) c++
val title = c >= 2
if (subject is Group) {
builder.add(At(sender))
builder.add("\n")
}
if (c == 0) {
builder.add("没有任何结果呢~")
} else {
val sb = StringBuilder()
if (result.error.isNotEmpty()) {
sb.appendLine("error:")
sb.append(result.error)
}
if (result.stdout.isNotEmpty()) {
if (title) sb.appendLine("\nstdout:")
sb.append(result.stdout)
}
if (result.stderr.isNotEmpty()) {
if (title) sb.appendLine("\nstderr:")
sb.append(result.stderr)
}
if (sb.length > MSG_MAX_LENGTH) {
sb.deleteRange(MSG_MAX_LENGTH, sb.length)
sb.append("\n消息内容过长,已截断")
}
builder.append(sb.toString())
}
return@reply builder.build()
} catch (e: Exception) {
logger.warning(e)
return@reply "执行失败\n原因:${e.message}"
}
}
}
}
override fun onDisable() {
JccCommand.unregister()
}
}

View File

@ -1,8 +1,9 @@
import JCompilerCollection.CMD_PREFIX
import net.mamoe.mirai.console.command.CommandSender
import net.mamoe.mirai.console.command.CompositeCommand
object JccCommand : CompositeCommand(
JCC, "jcc",
JCompilerCollection, "jcc",
description = "在线编译器集合"
) {
@SubCommand
@ -12,13 +13,32 @@ object JccCommand : CompositeCommand(
sendMessage(GlotAPI.listLanguages().joinToString { it.name })
} catch (e: Exception) {
sendMessage("执行失败\n${e.message}")
JCC.logger.warning(e)
JCompilerCollection.logger.warning(e)
}
}
@SubCommand
@Description("帮助")
suspend fun CommandSender.help() {
sendMessage("直接调用jcc即可运行代码\n例如jcc python print(\"Hello world\")\n其它指令:\n$usage")
sendMessage(
"在线运行代码指令:\n" +
"$CMD_PREFIX <language> <code>\n" +
"$CMD_PREFIX <language> <pastebinUrl> [stdin]\n" +
"引用消息: $CMD_PREFIX <language> [stdin]\n" +
"仓库地址https://github.com/jie65535/mirai-console-jcc-plugin\n" +
"其它指令:\n" +
usage
)
}
@SubCommand
@Description("获取指定语言的模板")
suspend fun CommandSender.template(language: String) {
if (!GlotAPI.checkSupport(language)) {
sendMessage("不支持该语言,请使用/jcc list列出所有支持的编程语言")
return
}
val file = GlotAPI.getTemplateFile(language)
sendMessage("$CMD_PREFIX $language\n" + file.content)
}
}

View File

@ -0,0 +1,15 @@
import net.mamoe.mirai.console.data.AutoSavePluginData
import net.mamoe.mirai.console.data.value
object JccPluginData: AutoSavePluginData("GlotCache") {
/**
* 支持的语言
*/
var languages: List<GlotAPI.Language> by value()
/**
* 模板文件
*/
val templateFiles: MutableMap<String, GlotAPI.CodeFile> by value()
}

View File

@ -21,6 +21,7 @@ object UbuntuPastebinHelper {
* 获取支持的语法列表缓存
* @return 返回一个map其中key是给人看的value是作为参数传递的
*/
@Deprecated("paste.ubuntu.com 现在需要登录 首页不再显示符号列表,因此该方法弃用")
fun getSyntaxList(): Map<String, String> {
if (syntaxList != null)
return syntaxList!!
@ -33,16 +34,20 @@ object UbuntuPastebinHelper {
return map
}
fun checkUrl(url: String): Boolean {
return url.startsWith("https://pastebin.ubuntu.com/p/") && url.endsWith('/') && url.length < 45
}
/**
* 获取内容
* @param url pastebin地址https://paste.ubuntu.com/p/nmn8yKMtND/
* @return 返回链接中贴的内容
*/
fun get(url: String): String {
if (url.isEmpty() || !url.startsWith("https://paste.ubuntu.com/p/"))
if (!checkUrl(url))
throw Exception("非法的url")
val document = HttpUtil.getDocument(url)
return HttpUtil.documentSelect(document, ".paste > pre").text()
return HttpUtil.documentSelect(document, "#hidden-content").text()
}
/**
@ -53,7 +58,8 @@ object UbuntuPastebinHelper {
* @param expiration 过期时间(empty)/day/week/month/year 默认值"day"
* @return 返回访问地址https://paste.ubuntu.com/p/nmn8yKMtND/
*/
fun paste(content: String, syntax: String = "text", poster: String = "temp", expiration: String = "day"): String? {
@Deprecated("paste.ubuntu.com 现在需要登录,因此不能再粘贴")
fun paste(content: String, syntax: String = "text", poster: String = "temp", expiration: String = "day"): String {
if (poster.length > 30)
throw Exception("poster length too long!")
if (content.isEmpty())