use of net.dv8tion.jda.api.entities.GuildChannel in project Bean by Xirado.
the class InteractionCommandHandler method handleSlashCommand.
public void handleSlashCommand(@NotNull SlashCommandInteractionEvent event, @Nullable Member member) {
Runnable r = () -> {
try {
if (!event.isFromGuild())
return;
Guild guild = event.getGuild();
SlashCommand command = null;
long guildId = event.getGuild().getIdLong();
if (registeredGuildCommands.containsKey(guildId)) {
List<SlashCommand> guildCommands = registeredGuildCommands.get(guildId).stream().filter(cmd -> cmd instanceof SlashCommand).map(cmd -> (SlashCommand) cmd).toList();
SlashCommand guildCommand = guildCommands.stream().filter(cmd -> cmd.getCommandName().equalsIgnoreCase(event.getName())).findFirst().orElse(null);
if (guildCommand != null)
command = guildCommand;
}
if (command == null) {
SlashCommand globalCommand = getRegisteredSlashCommands().stream().filter(cmd -> cmd.getCommandName().equalsIgnoreCase(event.getName())).findFirst().orElse(null);
if (globalCommand != null)
command = globalCommand;
}
if (command != null) {
SlashCommandContext ctx = new SlashCommandContext(event);
List<Permission> neededPermissions = command.getRequiredUserPermissions();
List<Permission> neededBotPermissions = command.getRequiredBotPermissions();
if (neededPermissions != null && !member.hasPermission((GuildChannel) event.getChannel(), neededPermissions)) {
event.reply(LocaleLoader.ofGuild(guild).get("general.no_perms", String.class)).queue();
return;
}
if (neededBotPermissions != null && !event.getGuild().getSelfMember().hasPermission((GuildChannel) event.getChannel(), neededBotPermissions)) {
event.reply(LocaleLoader.ofGuild(guild).get("general.no_bot_perms1", String.class)).queue();
return;
}
if (command.getCommandFlags().contains(CommandFlag.DJ_ONLY)) {
if (!ctx.getGuildData().isDJ(member)) {
event.replyEmbeds(EmbedUtil.errorEmbed("You need to be a DJ to do this!")).queue();
return;
}
}
if (command.getCommandFlags().contains(CommandFlag.MUST_BE_IN_VC)) {
GuildVoiceState guildVoiceState = member.getVoiceState();
if (guildVoiceState == null || !guildVoiceState.inAudioChannel()) {
event.replyEmbeds(EmbedUtil.errorEmbed("You are not connected to a voice-channel!")).queue();
return;
}
}
if (command.getCommandFlags().contains(CommandFlag.MUST_BE_IN_SAME_VC)) {
GuildVoiceState voiceState = member.getVoiceState();
AudioManager manager = event.getGuild().getAudioManager();
if (manager.isConnected()) {
if (!manager.getConnectedChannel().equals(voiceState.getChannel())) {
event.replyEmbeds(EmbedUtil.errorEmbed("You must be listening in " + manager.getConnectedChannel().getAsMention() + "to do this!")).setEphemeral(true).queue();
return;
}
}
}
if (command.getCommandFlags().contains(CommandFlag.REQUIRES_LAVALINK_NODE)) {
if (!ctx.isLavalinkNodeAvailable()) {
event.replyEmbeds(EmbedUtil.errorEmbed("There are currently no voice nodes available!\nIf the issue persists, please leave a message on our support server!")).addActionRow(Util.getSupportButton()).queue();
return;
}
}
command.executeCommand(event, ctx);
Metrics.COMMANDS.labels("success").inc();
}
} catch (Exception e) {
Metrics.COMMANDS.labels("failed").inc();
LinkedDataObject translation = event.getGuild() == null ? LocaleLoader.getForLanguage("en_US") : LocaleLoader.ofGuild(event.getGuild());
if (event.isAcknowledged())
event.getHook().sendMessageEmbeds(EmbedUtil.errorEmbed(translation.getString("general.unknown_error_occured"))).setEphemeral(true).queue(s -> {
}, ex -> {
});
else
event.replyEmbeds(EmbedUtil.errorEmbed(translation.getString("general.unknown_error_occured"))).setEphemeral(true).queue(s -> {
}, ex -> {
});
LOGGER.error("Could not execute slash-command", e);
StringBuilder path = new StringBuilder("/" + event.getCommandPath().replace("/", " "));
for (OptionMapping option : event.getOptions()) {
path.append(" *").append(option.getName()).append("* : ").append("`").append(option.getAsString()).append("`");
}
EmbedBuilder builder = new EmbedBuilder().setTitle("An error occurred while executing a slash-command!").addField("Guild", event.getGuild() == null ? "None (Direct message)" : event.getGuild().getIdLong() + " (" + event.getGuild().getName() + ")", true).addField("Channel", event.getGuild() == null ? "None (Direct message)" : event.getChannel().getName(), true).addField("User", event.getUser().getAsMention() + " (" + event.getUser().getAsTag() + ")", true).addField("Command", path.toString(), false).setColor(EmbedUtil.ERROR_COLOR);
event.getJDA().openPrivateChannelById(Bean.OWNER_ID).flatMap(c -> c.sendMessageEmbeds(builder.build()).content("```fix\n" + ExceptionUtils.getStackTrace(e) + "\n```")).queue();
}
};
Bean.getInstance().getCommandExecutor().execute(r);
}
use of net.dv8tion.jda.api.entities.GuildChannel in project mc-discord-bridge by Selicre.
the class DiscordBotImpl method updateChannels.
private void updateChannels() {
nextTopicUpdateTime = Instant.now().plus(TIME_BETWEEN_TOPIC_UPDATES);
topicNeedsUpdating = false;
TextChannel chatChannel = discord.getTextChannelById(config.channelId);
if (chatChannel != null && config.updateTopic) {
String topic = config.getTopicName(getPlayerNames());
chatChannel.getManager().setTopic(topic).queue(null, new ErrorHandler().handle(ErrorResponse.MISSING_PERMISSIONS, c -> {
LogManager.getLogger().warn("Missing permissions to change channel info!");
// Don't try again
config.updateTopic = false;
}));
}
GuildChannel renameChannel = discord.getGuildChannelById(config.renameChannelId);
int playerCount = server.getCurrentPlayerCount();
if (renameChannel != null) {
renameChannel.getManager().setName(config.getRenameChannelName(playerCount)).queue();
}
}
use of net.dv8tion.jda.api.entities.GuildChannel in project dDiscordBot by DenizenScript.
the class DiscordCreateChannelCommand method execute.
// <--[command]
// @Name discordcreatechannel
// @Syntax discordcreatechannel [id:<id>] [group:<group>] [name:<name>] (description:<description>) (type:<type>) (category:<category_id>) (position:<#>) (roles:<list>) (users:<list>)
// @Required 3
// @Maximum 9
// @Short Creates text channels on Discord.
// @Plugin dDiscordBot
// @Group external
//
// @Description
// Creates text channels on Discord.
//
// This functionality requires the Manage Channels permission.
//
// You can optionally specify the channel description (aka "topic") with the "description" argument.
//
// You can optionally specify the channel type. Valid types are TEXT, NEWS, CATEGORY, and VOICE.
// Only text and news channels can have a description.
// Categories cannot have a parent category.
//
// You can optionally specify the channel's parent category with the "category" argument.
// By default, the channel will not be attached to any category.
//
// You can optionally specify the channel's position in the list as an integer with the "position" argument.
//
// You can optionally specify the roles or users that are able to view the channel.
// The "roles" argument takes a list of DiscordRoleTags, and the "users" argument takes a list of DiscordUserTags.
// Specifying either of these arguments will create a private channel (hidden for anyone not in the lists).
//
// The command should usually be ~waited for. See <@link language ~waitable>.
//
// @Tags
// <entry[saveName].channel> returns the DiscordChannelTag of a channel upon creation when the command is ~waited for.
//
// @Usage
// Use to create a channel in a category.
// - ~discordcreatechannel id:mybot group:1234 name:my-channel category:5678
//
// @Usage
// Use to create a voice channel and log its name upon creation.
// - ~discordcreatechannel id:mybot group:1234 name:very-important-channel type:voice save:stuff
// - debug log "Created channel '<entry[stuff].channel.name>'"
//
// -->
@Override
public void execute(ScriptEntry scriptEntry) {
DiscordBotTag bot = scriptEntry.requiredArgForPrefix("id", DiscordBotTag.class);
DiscordGroupTag group = scriptEntry.requiredArgForPrefix("group", DiscordGroupTag.class);
ElementTag name = scriptEntry.requiredArgForPrefixAsElement("name");
ElementTag description = scriptEntry.argForPrefixAsElement("description", null);
ElementTag type = scriptEntry.argForPrefixAsElement("type", null);
ElementTag category = scriptEntry.argForPrefixAsElement("category", null);
ElementTag position = scriptEntry.argForPrefixAsElement("position", null);
List<DiscordRoleTag> roles = scriptEntry.argForPrefixList("roles", DiscordRoleTag.class, true);
List<DiscordUserTag> users = scriptEntry.argForPrefixList("users", DiscordUserTag.class, true);
if (scriptEntry.dbCallShouldDebug()) {
Debug.report(scriptEntry, getName(), bot, group, name, description, category);
}
if (group != null && group.bot == null) {
group.bot = bot.bot;
}
Runnable runner = () -> {
try {
ChannelAction<? extends GuildChannel> action;
ChannelType typeEnum = type != null ? ChannelType.valueOf(type.asString().toUpperCase()) : ChannelType.TEXT;
switch(typeEnum) {
case NEWS:
case TEXT:
{
action = group.getGuild().createTextChannel(name.asString()).setType(typeEnum);
break;
}
case CATEGORY:
{
action = group.getGuild().createCategory(name.asString());
break;
}
case VOICE:
{
action = group.getGuild().createVoiceChannel(name.asString());
break;
}
default:
{
handleError(scriptEntry, "Invalid channel type!");
return;
}
}
if (description != null) {
if (typeEnum != ChannelType.TEXT && typeEnum != ChannelType.NEWS) {
handleError(scriptEntry, "Only text and news channels can have descriptions!");
return;
}
action = action.setTopic(description.asString());
}
if (category != null) {
if (typeEnum == ChannelType.CATEGORY) {
handleError(scriptEntry, "A category cannot have a parent category!");
return;
}
Category resultCategory = group.getGuild().getCategoryById(category.asString());
if (resultCategory == null) {
handleError(scriptEntry, "Invalid category!");
return;
}
action = action.setParent(resultCategory);
}
if (position != null) {
action = action.setPosition(position.asInt());
}
Set<Permission> permissions = Collections.singleton(Permission.VIEW_CHANNEL);
if (roles != null || users != null) {
action = action.addRolePermissionOverride(group.guild_id, null, permissions);
}
if (roles != null) {
for (DiscordRoleTag role : roles) {
action = action.addRolePermissionOverride(role.role_id, permissions, null);
}
}
if (users != null) {
for (DiscordUserTag user : users) {
action = action.addMemberPermissionOverride(user.user_id, permissions, null);
}
}
GuildChannel resultChannel = action.complete();
scriptEntry.addObject("channel", new DiscordChannelTag(bot.bot, resultChannel));
} catch (Exception ex) {
handleError(scriptEntry, ex);
}
};
Bukkit.getScheduler().runTaskAsynchronously(DenizenDiscordBot.instance, () -> {
runner.run();
scriptEntry.setFinished(true);
});
}
use of net.dv8tion.jda.api.entities.GuildChannel in project Emolga by TecToast.
the class ResetRevolutionCommand method process.
@Override
public void process(GuildCommandEvent e) {
Guild g = e.getGuild();
e.getChannel().sendMessage("Die **Diktatur** ist zu Ende D:").queue();
JSONObject o = getEmolgaJSON().getJSONObject("revolutionreset").getJSONObject(g.getId());
for (String s : o.keySet()) {
g.retrieveMemberById(s).submit().thenCompose(mem -> mem.modifyNickname(o.getString(s)).submit());
}
for (GuildChannel gc : g.getChannels()) {
gc.getManager().setName(gc.getName().replaceFirst("(.*)-", "")).queue();
}
g.getSelfMember().modifyNickname("Emolga").queue();
JSONArray arr = getEmolgaJSON().getJSONArray("activerevolutions");
arr.remove(arr.toList().indexOf(g.getIdLong()));
saveEmolgaJSON();
}
use of net.dv8tion.jda.api.entities.GuildChannel in project Emolga by TecToast.
the class RevolutionCommand method process.
@Override
public void process(GuildCommandEvent e) {
if (e.getArgsLength() == 0) {
e.reply("Du musst einen Revolution-Namen angeben!");
return;
}
String name = e.getArg(0);
Guild g = e.getGuild();
JSONArray arr = getEmolgaJSON().getJSONArray("activerevolutions");
boolean isRevo = arr.toList().contains(g.getIdLong());
JSONObject o = new JSONObject();
e.getChannel().sendMessage("Möge die **" + name + "-Revolution** beginnen! :D").queue();
g.loadMembers().onSuccess(list -> {
for (Member member : list) {
if (member.isOwner())
continue;
if (member.getId().equals(e.getJDA().getSelfUser().getId()))
member.modifyNickname(name + "leader").queue();
if (!g.getSelfMember().canInteract(member))
continue;
if (!isRevo)
o.put(member.getId(), member.getEffectiveName());
member.modifyNickname(name).queue();
}
for (GuildChannel gc : g.getChannels()) {
gc.getManager().setName((gc.getType() == ChannelType.TEXT ? name.toLowerCase() : name) + "-" + gc.getName()).queue();
}
if (!isRevo) {
getEmolgaJSON().getJSONObject("revolutionreset").put(g.getId(), o);
arr.put(g.getIdLong());
}
saveEmolgaJSON();
});
}
Aggregations