net.dv8tion.jda.api.entities.TextChannel Java Examples

The following examples show how to use net.dv8tion.jda.api.entities.TextChannel. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HistoryServiceImpl.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
private StringEncryptor getEncryptor(TextChannel channel, String iv) {
    StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
    encryptor.setAlgorithm("PBEWithHMACSHA512AndAES_256");
    encryptor.setPassword(String.format("%s:%s", channel.getGuild().getId(), channel.getId()));
    encryptor.setIvGenerator(new StringFixedIvGenerator(iv));
    return encryptor;
}
 
Example #2
Source File: InvestigateCmd.java    From MantaroBot with GNU General Public License v3.0 6 votes vote down vote up
private static void investigateChannel(GuildMessageReceivedEvent event, TextChannel channel, boolean file) {
    if (channel == null) {
        event.getChannel().sendMessage("Unknown channel").queue();
        return;
    }
    Investigation investigation = new Investigation(file);
    channel.getIterableHistory().takeAsync(200)
            .thenAccept(messages -> {
                List<InvestigatedMessage> res = investigation.get(channel);
                messages.forEach(m -> res.add(0, InvestigatedMessage.from(m)));
            })
            .thenRun(() -> investigation.result(channel.getGuild(), event))
            .exceptionally(e -> {
                e.printStackTrace();
                event.getChannel().sendMessage("Unable to execute: " + e).queue();
                return null;
            });
}
 
Example #3
Source File: MessageController.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
public void doForMessage(Consumer<? super Message> success, Consumer<? super Throwable> error) {
    TextChannel channel = jda.getTextChannelById(channelId);
    if (channel != null) {
        channel.retrieveMessageById(messageId).queue(
                m -> contextService.withContext(guildId, () -> {
                    if (success != null) {
                        success.accept(m);
                    }
                }),
                t -> contextService.withContext(guildId, () -> {
                    if (error != null) {
                        error.accept(t);
                    }
                }));
    }
}
 
Example #4
Source File: PurgeChannelCommand.java    From SkyBot with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void execute(@Nonnull CommandContext ctx) {
    final List<TextChannel> channels = FinderUtil.findTextChannels(ctx.getArgsRaw(), ctx.getGuild());

    if (channels.isEmpty()) {
        this.sendUsageInstructions(ctx);
        return;
    }

    final TextChannel toPurge = channels.get(0);

    if (toPurge.equals(ctx.getChannel())) {
        sendMsg(ctx, "For security reasons you can not use this command in the channel that you want to purge");
        return;
    }

    toPurge.createCopy()
        .setPosition(toPurge.getPosition())
        .queue(
            (success) -> {
                toPurge.delete().queue();
                sendSuccess(ctx.getMessage());
            },
            (error) -> sendError(ctx.getMessage())
        );
}
 
Example #5
Source File: CheckOwnerQueueListener.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@RabbitListener(queues = RabbitConfiguration.QUEUE_CHECK_OWNER_REQUEST)
public boolean isAdministrator(CheckOwnerRequest request) {
    Guild guild = null;
    switch (request.getType()) {
        case TEXT:
            TextChannel textChannel = discordService.getTextChannelById(request.getChannelId());
            if (textChannel != null) {
                guild = textChannel.getGuild();
            }
            break;
        case VOICE:
            VoiceChannel voiceChannel = discordService.getVoiceChannelById(request.getChannelId());
            if (voiceChannel != null) {
                guild = voiceChannel.getGuild();
            }
            break;
    }
    if (guild == null) {
        return true;
    }
    Member member = guild.getMemberById(request.getUserId());
    if (member == null) {
        return false;
    }
    return member.isOwner() || member.hasPermission(Permission.ADMINISTRATOR);
}
 
Example #6
Source File: MusicController.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
@BotCommandHandler
private void deserialize(Message message, String content) throws IOException {
  outputChannel.set((TextChannel) message.getChannel());
  connectToFirstVoiceChannel(guild.getAudioManager());

  byte[] bytes = Base64.decode(content);

  MessageInput inputStream = new MessageInput(new ByteArrayInputStream(bytes));
  DecodedTrackHolder holder;

  while ((holder = manager.decodeTrack(inputStream)) != null) {
    if (holder.decodedTrack != null) {
      scheduler.addToQueue(holder.decodedTrack);
    }
  }
}
 
Example #7
Source File: SlowModeCommand.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean doCommand(GuildMessageReceivedEvent event, BotContext context, String query) {
    TextChannel channel = event.getChannel();
    if (!StringUtils.isNumeric(query)) {
        return showHelp(channel, context);
    }

    int seconds;
    try {
        seconds = Integer.parseInt(query);
    } catch (NumberFormatException e) {
        return showHelp(channel, context);
    }
    if (seconds < 0 || seconds > 120) {
        return showHelp(channel, context);
    }

    channel.sendTyping().queue();
    channel.getManager().setSlowmode(seconds).queue(e -> contextService.withContext(channel.getGuild(), () -> {
        if (seconds > 0) {
            String secPlurals = messageService.getCountPlural(seconds, "discord.plurals.second");
            messageService.onEmbedMessage(channel, "discord.command.mod.slow.enabled", seconds,
                    secPlurals);
        } else {
            messageService.onEmbedMessage(channel, "discord.command.mod.slow.disabled");
        }
    }));
    return true;
}
 
Example #8
Source File: CommandList.java    From Arraybot with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the list as a string.
 * @param input The entries.
 * @param channel The text channel.
 * @return The string.
 */
@Override
public String asString(List<Object> input, TextChannel channel) {
    long guild = channel.getGuild().getIdLong();
    GuildEntry entry = (GuildEntry) Category.GUILD.getEntry();
    String prefix = entry.fetch(entry.getField(GuildEntry.Fields.PREFIX), guild, null);
    StringBuilder builder = new StringBuilder();
    for(Object command : input) {
        String syntax;
        String description;
        if(command instanceof DefaultCommand) {
            String language = entry.fetch(entry.getField(GuildEntry.Fields.LANGUAGE), guild, null);
            syntax = prefix + ((DefaultCommand) command).getSyntax(language);
            description = ((DefaultCommand) command).getDescription(language);
        } else if(command instanceof CustomCommand) {
            syntax = prefix + ((CustomCommand) command).getName();
            if(((CustomCommand) command).getSyntax() == CustomCommandSyntax.STARTSWITH) {
                syntax += " " + Message.CUSTOM_ARGUMENT.getContent(channel);
            }
            description = ((CustomCommand) command).getDescription();
        } else {
            continue;
        }
        builder.append("`")
                .append(syntax)
                .append("`")
                .append("\n    **-** ")
                .append(description)
                .append("\n\n");
    }
    return builder.toString();
}
 
Example #9
Source File: ChoiceStateHandler.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
protected void outPlayer(MafiaInstance instance, MafiaPlayer player) {
    player.out();
    TextChannel goonChannel = instance.getGoonChannel();
    if (player.getRole() == MafiaRole.GOON && goonChannel != null) {
        Member member = player.getMember();
        if (member != null) {
            PermissionOverride override = goonChannel.getPermissionOverride(player.getMember());
            override.delete().queue();
        }
    }
}
 
Example #10
Source File: ModLog.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
public static void log(Member author, User target, String reason, String channel, ModAction action, long caseNumber, int messagesDeleted) {
    DBGuild guildDB = db.getGuild(author.getGuild());
    Player player = db.getPlayer(author);
    PlayerData playerData = player.getData();
    EmbedBuilder embedBuilder = new EmbedBuilder();

    embedBuilder.addField("Responsible Moderator", author.getEffectiveName(), true);

    if (target != null) {
        embedBuilder.addField("Member", target.getName(), true);
        embedBuilder.setThumbnail(target.getEffectiveAvatarUrl());
    } else {
        embedBuilder.setThumbnail(author.getUser().getEffectiveAvatarUrl());
    }

    embedBuilder.addField("Reason", reason, false);
    embedBuilder.addField("Channel", channel, true);

    if (action == ModAction.PRUNE) {
        embedBuilder.addField("Messages Deleted", String.valueOf(messagesDeleted), true);
    }

    //Why was this a giant switch statement?
    embedBuilder.setAuthor(String.format("%s | Case #%s", Utils.capitalize(action.name()), caseNumber),
            null, author.getUser().getEffectiveAvatarUrl());

    if (!playerData.hasBadge(Badge.POWER_USER)) {
        playerData.addBadgeIfAbsent(Badge.POWER_USER);
        player.saveAsync();
    }

    if (guildDB.getData().getGuildLogChannel() != null) {
        TextChannel logChannel = MantaroBot.getInstance().getShardManager().getTextChannelById(guildDB.getData().getGuildLogChannel());
        if (logChannel != null) {
            logChannel.sendMessage(embedBuilder.build()).queue();
        }
    }
}
 
Example #11
Source File: EmergencyServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void error(String message) {
    Long emergencyChannelId = workerProperties.getSupport().getEmergencyChannelId();
    if (emergencyChannelId == null || !discordService.isConnected(workerProperties.getSupport().getGuildId())) {
        return;
    }
    TextChannel channel = discordService.getShardManager().getTextChannelById(emergencyChannelId);
    if (channel == null) {
        return;
    }
    messageService.sendMessageSilent(channel::sendMessage, "@here " + message);
}
 
Example #12
Source File: UnMuteJob.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void execute(JobExecutionContext jobExecutionContext) {
    ShardManager shardManager = discordService.getShardManager();
    if (shardManager == null || !discordService.isConnected()) {
        reschedule(jobExecutionContext, TimeUnit.MINUTES, 1);
        return;
    }

    JobDataMap data = jobExecutionContext.getJobDetail().getJobDataMap();

    String userId = data.getString(ATTR_USER_ID);
    String guildId = data.getString(ATTR_GUILD_ID);
    String channelId = data.getString(ATTR_CHANNEL_ID);

    if (guildId != null && userId != null && channelId != null) {
        muteService.clearState(Long.parseLong(guildId), userId, channelId);
    }

    if (StringUtils.isEmpty(guildId)) {
        return;
    }

    Guild guild = shardManager.getGuildById(guildId);
    if (guild != null) {
        if (!guild.isAvailable()) {
            reschedule(jobExecutionContext, TimeUnit.MINUTES, 1);
            return;
        }
        Member member = guild.getMemberById(userId);
        if (member != null) {
            TextChannel channel = StringUtils.isNotBlank(channelId) ? guild.getTextChannelById(channelId) : null;
            muteService.unmute(null, channel, member);
        }
    }
}
 
Example #13
Source File: MafiaInstance.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
public MafiaInstance(@NonNull TextChannel channel, Locale locale, String prefix) {
    this.jda = channel.getJDA();
    this.channelId = channel.getIdLong();
    this.guildId = channel.getGuild().getIdLong();
    this.locale = locale;
    this.prefix = prefix;
    tick();
}
 
Example #14
Source File: MafiaService.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
public boolean start(User user, TextChannel guild) {
    if (instances.containsKey(guild.getIdLong())) {
        return false;
    }
    MafiaInstance instance = getInstance(guild);
    return !choosingHandler.onStart(user, instance);
}
 
Example #15
Source File: Main.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private void loadAndPlay(final TextChannel channel, final String trackUrl) {
  GuildMusicManager musicManager = getGuildAudioPlayer(channel.getGuild());

  playerManager.loadItemOrdered(musicManager, trackUrl, new AudioLoadResultHandler() {
    @Override
    public void trackLoaded(AudioTrack track) {
      channel.sendMessage("Adding to queue " + track.getInfo().title).queue();

      play(channel.getGuild(), musicManager, track);
    }

    @Override
    public void playlistLoaded(AudioPlaylist playlist) {
      AudioTrack firstTrack = playlist.getSelectedTrack();

      if (firstTrack == null) {
        firstTrack = playlist.getTracks().get(0);
      }

      channel.sendMessage("Adding to queue " + firstTrack.getInfo().title + " (first track of playlist " + playlist.getName() + ")").queue();

      play(channel.getGuild(), musicManager, firstTrack);
    }

    @Override
    public void noMatches() {
      channel.sendMessage("Nothing found by " + trackUrl).queue();
    }

    @Override
    public void loadFailed(FriendlyException exception) {
      channel.sendMessage("Could not play: " + exception.getMessage()).queue();
    }
  });
}
 
Example #16
Source File: UnMuteJob.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
public static JobKey getKey(Member member, TextChannel channel) {
    String identity = String.format("%s-%s-%s-%s",
            GROUP,
            member.getGuild().getId(),
            member.getUser().getId(),
            channel.getId());
    return new JobKey(identity, GROUP);
}
 
Example #17
Source File: CommandManager.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
public void dispatchCommand(@Nonnull ICommand cmd, String invoke, List<String> args, GuildMessageReceivedEvent event) {
    this.commandThread.submit(() -> {
        MDC.put("command.invoke", invoke);
        MDC.put("command.args", args.toString());
        MDC.put("user.tag", event.getAuthor().getAsTag());
        MDC.put("user.id", event.getAuthor().getId());
        MDC.put("guild", event.getGuild().toString());
        setJDAContext(event.getJDA());

        final TextChannel channel = event.getChannel();

        if (!channel.canTalk()) {
            return;
        }

        // Suppress errors from when we can't type in the channel
        channel.sendTyping().queue(null, (t) -> {});

        try {
            if (!cmd.isCustom()) {
                runNormalCommand(cmd, invoke, args, event);
            } else {
                runCustomCommand(cmd, invoke, args, event);
            }
        }
        catch (Throwable ex) {
            Sentry.capture(ex);
            ex.printStackTrace();
            sendMsg(event, "Something went wrong whilst executing the command, my developers have been informed of this\n" + ex.getMessage());
        }
    });
}
 
Example #18
Source File: CleanupCommand.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
private void removeMessage(TextChannel channel, CompletableFuture<Message> hack) {
    try {
        final Message hacked = hack.get();

        if (hacked != null) {
            channel.deleteMessageById(hacked.getIdLong()).queue();
        }
    }
    catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
}
 
Example #19
Source File: ChoiceStateHandler.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
public void unpinMessage(MafiaInstance instance) {
    String messageId = (String) instance.removeAttribute(ATTR_MESSAGE_ID + instance.getState().name());
    if (messageId == null) {
        return;
    }
    TextChannel channel = instance.getState() == MafiaState.DAY ? instance.getChannel() : instance.getGoonChannel();
    if (channel != null && channel.getGuild().getSelfMember().hasPermission(channel, Permission.MESSAGE_MANAGE)) {
        channel.unpinMessageById(messageId).queue();
    }
}
 
Example #20
Source File: AimlServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
private Request createRequest(GuildMessageReceivedEvent event, String input) {
    Request.RequestBuilder builder = Request.builder()
            .input(input)
            .attribute("dMessageEvent", event)
            .attribute("dAuthorName", event.getAuthor().getName())
            .attribute("dAuthorMention", event.getAuthor().getAsMention())
            .attribute("dAuthorAvatarUrl", event.getAuthor().getEffectiveAvatarUrl());

    if (event.getMember() != null) {
        Member member = event.getMember();
        builder
                .attribute("dAuthorName", member.getEffectiveName())
                .attribute("dAuthorMention", member.getAsMention());
    }

    if (event.getGuild() != null) {
        Guild guild = event.getGuild();
        builder
                .attribute("dGuildName", guild.getName())
                .attribute("dGuildOwnerName", guild.getOwner().getEffectiveName());
    }

    if (event.getChannel() != null) {
        TextChannel channel = event.getChannel();
        builder.attribute("dChannelName", channel.getName());
    }
    return builder.build();
}
 
Example #21
Source File: SettingsBase.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
@Nullable
protected TextChannel findTextChannel(@Nonnull CommandContext ctx) {
    final List<TextChannel> foundChannels = FinderUtil.findTextChannels(ctx.getArgsRaw(), ctx.getGuild());

    if (foundChannels.isEmpty()) {
        return null;
    }

    return foundChannels.stream()
        .filter(TextChannel::canTalk)
        .findFirst()
        .orElse(null);
}
 
Example #22
Source File: MafiaService.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
public boolean stop(Member requestedBy, TextChannel channel) {
    MafiaInstance instance = getRelatedInstance(channel.getIdLong());
    if (instance == null || !(instance.getState().equals(MafiaState.CHOOSING)
            || instance.isPlayer(requestedBy)
            || moderationService.isModerator(requestedBy))) {
        return false;
    }
    stop(instance);
    return true;
}
 
Example #23
Source File: MafiaService.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
public boolean done(User user, TextChannel guild) {
    MafiaInstance instance = getRelatedInstance(guild.getIdLong());
    if (instance == null || !instance.isPlayer(user)) {
        return false;
    }
    if (instance.done(user)) {
        stop(instance);
    }
    return true;
}
 
Example #24
Source File: IndividualHandler.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean onStart(User user, MafiaInstance instance) {
    MafiaPlayer individual = instance.getPlayerByRole(individualRole);
    if (individual == null) {
        return getNextHandler().onStart(user, instance);
    }
    MafiaState oldState = instance.updateState(state);
    StringBuilder messageBuilder = new StringBuilder();
    if (oldState.getTransitionEnd() != null) {
        messageBuilder.append(messageService.getMessage(oldState.getTransitionEnd())).append(" ");
    }
    if (state.getTransitionStart() != null) {
        messageBuilder.append(messageService.getMessage(state.getTransitionStart()));
    }
    if (messageBuilder.length() > 0) {
        EmbedBuilder builder = getBaseEmbed();
        builder.setDescription(messageBuilder.toString());

        TextChannel channel = instance.getChannel();
        if (channel == null) {
            return true; // end for non existent channel instantly
        }
        channel.sendMessage(builder.build()).queue();
    }
    if (!sendChoiceMessage(instance, individualRole.getChoiceMessage())) {
        instance.setEndReason(messageService.getMessage("mafia.end.reason.couldNotDM",
                individual.getName()));
        return true;
    }
    return scheduleEnd(instance, INDIVIDUAL_DELAY);
}
 
Example #25
Source File: WebHookServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
private void checkWebhookChannel(Webhook webhook, String channelId) {
    Guild guild = webhook.getGuild();
    if (!channelId.equals(webhook.getChannel().getId())) {
        TextChannel channel = guild.getTextChannelById(channelId);
        if (channel == null) {
            throw new IllegalStateException("Tried to set non-existent channel");
        }
        if (guild.getSelfMember().hasPermission(channel, Permission.MANAGE_WEBHOOKS)) {
            webhook.getManager().setChannel(channel).queue();
        }
    }
}
 
Example #26
Source File: WebHookServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean updateWebHook(long id, long guildId, String channelId, String name, String iconUrl) {
    if (discordService.isConnected(guildId)) {
        Guild guild = discordService.getShardManager().getGuildById(guildId);
        if (guild != null && channelId != null) {
            Webhook webhook = getWebHook(id, guild);
            if (webhook != null) {
                checkWebhookChannel(webhook, channelId);
                return true;
            }
            TextChannel channel = guild.getTextChannelById(channelId);
            if (channel != null && guild.getSelfMember().hasPermission(channel, Permission.MANAGE_WEBHOOKS)) {
                channel.createWebhook(CommonUtils.trimTo(name, 2, 32))
                        .setAvatar(DiscordUtils.createIcon(iconUrl))
                        .queue(e -> {
                            checkWebhookChannel(e, channelId);
                            WebHook webHook = repository.findById(id).orElse(null);
                            if (webHook != null) {
                                webHook.setHookId(e.getIdLong());
                                webHook.setToken(e.getToken());
                                repository.save(webHook);
                            }
                        });
                webHooks.invalidate(guild);
            }
            return true;
        }
    }
    return false;
}
 
Example #27
Source File: GenericGuildMessageReactionEvent.java    From JDA with Apache License 2.0 5 votes vote down vote up
public GenericGuildMessageReactionEvent(@Nonnull JDA api, long responseNumber, @Nullable Member user, @Nonnull MessageReaction reaction, long userId)
{
    super(api, responseNumber, reaction.getMessageIdLong(), (TextChannel) reaction.getChannel());
    this.issuer = user;
    this.reaction = reaction;
    this.userId = userId;
}
 
Example #28
Source File: GenericTextChannelUpdateEvent.java    From JDA with Apache License 2.0 5 votes vote down vote up
public GenericTextChannelUpdateEvent(
    @Nonnull JDA api, long responseNumber, @Nonnull TextChannel channel,
    @Nullable T previous, @Nullable T next, @Nonnull String identifier)
{
    super(api, responseNumber, channel);
    this.previous = previous;
    this.next = next;
    this.identifier = identifier;
}
 
Example #29
Source File: MusicController.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public void sendMessage(String message) {
  TextChannel channel = outputChannel.get();

  if (channel != null) {
    channel.sendMessage(message).queue();
  }
}
 
Example #30
Source File: MusicController.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public void sendMessage(String message, Consumer<Message> success, Consumer<Throwable> failure) {
  TextChannel channel = outputChannel.get();

  if (channel != null) {
    channel.sendMessage(message).queue(success, failure);
  }
}