Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
mirai-console-permission-service-example

mirai-console-permission-service-example

import kotlin.Lazy;
import kotlin.LazyKt;
import net.mamoe.mirai.console.permission.*;
import net.mamoe.mirai.console.plugin.jvm.JavaPlugin;
import net.mamoe.mirai.console.plugin.jvm.JvmPluginDescriptionBuilder;
import net.mamoe.mirai.contact.Member;
import net.mamoe.mirai.contact.User;
class JPlugin extends JavaPlugin {
public static final JPlugin INSTANCE = new JPlugin();
private JPlugin() {
super(new JvmPluginDescriptionBuilder("org.example.ps-example", "0.0.0").build());
}
private final Lazy<Permission> myCustomPermission = LazyKt.lazy(() -> { // Lazy: Lazy 是必须的, console 不允许提前访问权限系统
// 注册一条权限节点 org.example.ps-example:my-permission
// 并以 org.example.ps-example:* 为父节点
// @param: parent: 父权限
// 在 Console 内置权限系统中, 如果某人拥有父权限
// 那么意味着此人也拥有该权限 (io.github.karlatemp.ps-example:my-permission)
// @func: PermissionIdNamespace.permissionId: 根据插件 id 确定一条权限 id
try {
return PermissionService.getInstance().register(
permissionId("my-permission"),
"一条自定义权限",
getParentPermission()
);
} catch (PermissionRegistryConflictException e) {
throw new RuntimeException(e);
}
});
public boolean hasCustomPermission(User usr) {
PermitteeId pid;
if (usr instanceof Member) {
pid = new AbstractPermitteeId.ExactMember(((Member) usr).getGroup().getId(), usr.getId());
} else {
pid = new AbstractPermitteeId.ExactUser(usr.getId());
}
return PermissionService.hasPermission(pid, myCustomPermission.getValue());
}
}
import net.mamoe.mirai.console.permission.AbstractPermitteeId
import net.mamoe.mirai.console.permission.PermissionService
import net.mamoe.mirai.console.permission.PermissionService.Companion.hasPermission
import net.mamoe.mirai.console.plugin.jvm.JvmPluginDescription
import net.mamoe.mirai.console.plugin.jvm.KotlinPlugin
import net.mamoe.mirai.contact.Member
import net.mamoe.mirai.contact.User
object KtPlugin : KotlinPlugin(
JvmPluginDescription(id = "org.example.ps-example", version = "0.0.0")
) {
private val myCustomPermission by lazy { // Lazy: Lazy 是必须的, console 不允许提前访问权限系统
// 注册一条权限节点 org.example.ps-example:my-permission
// 并以 org.example.ps-example:* 为父节点
// @param: parent: 父权限
// 在 Console 内置权限系统中, 如果某人拥有父权限
// 那么意味着此人也拥有该权限 (org.example.ps-example:my-permission)
// @func: PermissionIdNamespace.permissionId: 根据插件 id 确定一条权限 id
PermissionService.INSTANCE.register(permissionId("my-permission"), "一条自定义权限", parentPermission)
}
public fun hasCustomPermission(sender: User): Boolean {
return when (sender) {
is Member -> AbstractPermitteeId.ExactMember(sender.group.id, sender.id)
else -> AbstractPermitteeId.ExactUser(sender.id)
}.hasPermission(myCustomPermission)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment