How to create a private channel in a Discord server (not a user/bot DM) using JDA: Java Discord API

二次信任 提交于 2021-02-05 11:44:25

问题


I'm trying to get the bot to create a private channel in the guild but can't find anything in the JDA documentation that allows that to happen. The ChannelAction that gets returned when you call createTextChannel() has text as the channel type explicitly in the return (return new ChannelAction(route, name, guild, ChannelType.TEXT);).

Currently I have it working to just create a text channel with:

guild.getController().createTextChannel(channelName).complete();

but I need it to be a private channel. I've experimented a bit with trying to write my own createPrivateChannel() method, but it always comes back to needing some implementation of it already in the JDA GuildController.java. I also have looked at the openPrivateChannel() but that's for DMs between the user and the bot, and I need a private channel in the server/guild.

Any ideas? Do I just need to go the long route and create the text channel and then mess with the permissions to make it visible to the correct users?


回答1:


You can create a "private" channel by using permission overrides. For this you first need to create that channel using createTextChannel(name) which will return a ChannelAction<TextChannel>.

This interface allows you to do some additional configuration such as permission overrides (we need this). You need to deny the VIEW_CHANNEL permission for the public role @everyone and allow it for the specific role/member that you want to give access to.

public static void createTextChannel(Member member, String name) {
    Guild guild = member.getGuild();
    guild.createTextChannel(name)
         .addPermissionOverride(member, EnumSet.of(Permission.VIEW_CHANNEL), null)
         .addPermissionOverride(guild.getPublicRole(), null, EnumSet.of(Permission.VIEW_CHANNEL))
         .queue(); // this actually sends the request to discord.
}

In JDA 3.X you need to use guild.getController().createTextChannel() but that version is no longer supported and you should be using JDA 4.X now. For more information on how to migrate see the migration guide.



来源:https://stackoverflow.com/questions/60088401/how-to-create-a-private-channel-in-a-discord-server-not-a-user-bot-dm-using-jd

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!