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

The following examples show how to use net.dv8tion.jda.api.entities.Message. 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: DiscordBotServer.java    From MtgDesktopCompanion with GNU General Public License v3.0 6 votes vote down vote up
public ReactionListener(JDA jda, Message message, boolean oneTimeUse, long expireTimeout) {
	this.jda = jda;
	this.message = message;
	this.oneTimeUse = oneTimeUse;
	this.actionMap = new HashMap<>();
	this.expireTimeout = expireTimeout;
	this.expireTimer = new Timer();
	this.startTime = System.currentTimeMillis();
	enable();

	// Force disable after max life expiry
	new Timer().schedule(new TimerTask() {
		@Override
		public void run() {
			disable();
		}
	}, MAX_LIFE);
}
 
Example #2
Source File: CustomCommandHandler.java    From MantaroBot with GNU General Public License v3.0 6 votes vote down vote up
public void handle(boolean preview) {
    if (!processResponse())
        return;
    if (specialHandling())
        return;

    if (response.startsWith("v3:")) {
        CCv3.process(prefixUsed, ctx, new Parser(response.substring(3)).parse(), preview);
        return;
    }

    MessageBuilder builder = new MessageBuilder().setContent(filtered1.matcher(response).replaceAll("-filtered regex-"));
    if (preview) {
        builder.append("\n\n")
                .append(EmoteReference.WARNING)
                .append("**This is a preview of how a CC with this content would look like, ALL MENTIONS ARE DISABLED ON THIS MODE.**\n")
                .append("`Command preview requested by: ")
                .append(ctx.getAuthor().getAsTag())
                .append("`");
    }

    builder.denyMentions(Message.MentionType.ROLE, Message.MentionType.USER, Message.MentionType.EVERYONE, Message.MentionType.HERE);
    ctx.send(builder.build());
}
 
Example #3
Source File: BotControllerManager.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
private void registerControllerMethod(Class<?> controllerClass, Method method, BotCommandHandler annotation) {
  String commandName = annotation.name().isEmpty() ? method.getName().toLowerCase() : annotation.name();
  String usage = annotation.usage().isEmpty() ? null : annotation.usage();

  Parameter[] methodParameters = method.getParameters();
  if (methodParameters.length == 0 || !methodParameters[0].getType().isAssignableFrom(Message.class)) {
    return;
  }

  method.setAccessible(true);

  List<Class<?>> parameters = new ArrayList<>();
  for (int i = 1; i < methodParameters.length; i++) {
    parameters.add(methodParameters[i].getType());
  }

  Command command = new Command(commandName, usage, parameters, controllerClass, method);
  commands.put(command.name, command);
}
 
Example #4
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 #5
Source File: InviteCommand.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
private String extractCode(String value) {
    Matcher matcher = Message.INVITE_PATTERN.matcher(value);
    if (matcher.find()) {
        return matcher.group(1);
    }
    matcher = INVITE_CODE_PATTERN.matcher(value);
    if (matcher.find()) {
        return matcher.group(0);
    }
    return null;
}
 
Example #6
Source File: ReactionOperations.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
public static Future<Void> create(Message message, long timeoutSeconds, ReactionOperation operation, String... defaultReactions) {
    if (!message.getAuthor().equals(message.getJDA().getSelfUser()))
        throw new IllegalArgumentException("Must provide a message sent by the bot");

    Future<Void> f = create(message.getIdLong(), timeoutSeconds, operation);
    if(f == null) return null;

    if (defaultReactions.length > 0) {
        AtomicInteger index = new AtomicInteger();
        AtomicReference<Consumer<Void>> c = new AtomicReference<>();
        Consumer<Throwable> ignore = (t) -> {
        };

        c.set(ignored -> {
            //Ignore this if we already cancelled this operation.
            if (f.isCancelled())
                return;

            int i = index.incrementAndGet();
            if (i < defaultReactions.length) {
                message.addReaction(reaction(defaultReactions[i])).queue(c.get(), ignore);
            }
        });

        message.addReaction(reaction(defaultReactions[0])).queue(c.get(), ignore);
    }

    return f;
}
 
Example #7
Source File: SelfUserImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
public long getAllowedFileSize()
{
    if (this.nitro) // by directly accessing the field we don't need to check the account type
        return Message.MAX_FILE_SIZE_NITRO;
    else
        return Message.MAX_FILE_SIZE;
}
 
Example #8
Source File: MessageController.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
public MessageController(ApplicationContext context, Message message) {
    this.jda = message.getJDA();
    this.messageId = message.getIdLong();
    this.channelId = message.getTextChannel().getIdLong();
    this.guildId = message.getGuild().getIdLong();
    this.reactionsListener = context.getBean(ReactionsListener.class);
    this.playerService = context.getBean(PlayerService.class);
    this.messageManager = context.getBean(AudioMessageManager.class);
    this.contextService = context.getBean(ContextService.class);
    this.commandsService = context.getBean(InternalCommandsService.class);
    this.messageService = context.getBean(MessageService.class);
    init(message);
}
 
Example #9
Source File: DiscordUtils.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
public static Future<Void> list(GuildMessageReceivedEvent event, int timeoutSeconds, boolean canEveryoneUse, List<String> parts) {
    if (parts.size() == 0)
        return null;

    if (parts.size() == 1) {
        event.getChannel().sendMessage(parts.get(0)).queue();
        return null;
    }

    AtomicInteger index = new AtomicInteger();
    Message m = event.getChannel().sendMessage(parts.get(0)).complete();

    return ReactionOperations.create(m, timeoutSeconds, (e) -> {
        if (!canEveryoneUse && e.getUser().getIdLong() != event.getAuthor().getIdLong())
            return Operation.IGNORED;

        switch (e.getReactionEmote().getName()) {
            //left arrow
            case "\u2b05" -> {
                if (index.get() == 0) break;
                m.editMessage(String.format("%s\n**Page: %d**", parts.get(index.decrementAndGet()), index.get() + 1)).queue();
            }
            //right arrow
            case "\u27a1" -> {
                if (index.get() + 1 >= parts.size())
                    break;
                m.editMessage(String.format("%s\n**Page: %d**", parts.get(index.incrementAndGet()), index.get() + 1)).queue();
            }
            case "\u274c" -> m.delete().queue();
        }

        if (event.getGuild().getSelfMember().hasPermission(e.getTextChannel(), Permission.MESSAGE_MANAGE)) {
            e.getReaction().removeReaction(e.getUser()).queue();
        }

        return Operation.IGNORED;
    }, "\u2b05", "\u27a1", "\u274c");
}
 
Example #10
Source File: TagCommand.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
private void sendTagRaw(CommandContext ctx, String tagName) {
    if (!this.tagStore.containsKey(tagName)) {
        sendMsg(ctx, "That tag does not exist");

        return;
    }

    final Message message = new MessageBuilder()
        .appendCodeBlock(this.tagStore.get(tagName).content, "").build();

    sendMsg(ctx, message);
}
 
Example #11
Source File: WolframAlphaCommand.java    From SkyBot with GNU Affero General Public License v3.0 5 votes vote down vote up
private void editMsg(AtomicReference<Message> ref, TextChannel channel, Message message) {
    final Message fromRef = ref.get();

    if (fromRef == null) {
        channel.sendMessage(message).queue();

        return;
    }

    fromRef.editMessage(message).override(true).queue();
}
 
Example #12
Source File: DiscordUtils.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
public static Future<Void> listText(GuildMessageReceivedEvent event, int timeoutSeconds, boolean canEveryoneUse, List<String> parts) {
    if (parts.size() == 0)
        return null;

    if (parts.size() == 1) {
        event.getChannel().sendMessage(parts.get(0)).queue();
        return null;
    }

    AtomicInteger index = new AtomicInteger();
    Message m = event.getChannel().sendMessage(parts.get(0)).complete();

    return InteractiveOperations.create(event.getChannel(), event.getAuthor().getIdLong(), timeoutSeconds, e -> {
        if (!canEveryoneUse && e.getAuthor().getIdLong() != event.getAuthor().getIdLong())
            return Operation.IGNORED;

        String contentRaw = e.getMessage().getContentRaw();

        if (contentRaw.equals("&p <<") || contentRaw.equals("&page <<")) {
            if (index.get() == 0) return Operation.IGNORED;

            m.editMessage(String.format("%s\n**Page: %d**", parts.get(index.decrementAndGet()), index.get() + 1)).queue();
        } else if (contentRaw.equals("&p >>") || contentRaw.equals("&page >>")) {
            if (index.get() + 1 >= parts.size()) return Operation.IGNORED;

            m.editMessage(String.format("%s\n**Page: %d**", parts.get(index.incrementAndGet()), index.get() + 1)).queue();
        }

        if (contentRaw.equals("&cancel")) {
            m.delete().queue();
            return Operation.COMPLETED;
        }

        return Operation.IGNORED;
    });
}
 
Example #13
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 #14
Source File: EndPointMessage.java    From Yui with Apache License 2.0 5 votes vote down vote up
public void setDiscordMessage(Message discordMessage)
{
    String parsedMessage = discordMessage.getContentDisplay();
    for (Message.Attachment attach : discordMessage.getAttachments())
    {
        parsedMessage += "\n" + attach.getUrl();
    }

    this.message = parsedMessage;
    this.discordMessage = discordMessage;
}
 
Example #15
Source File: ChoiceStateHandler.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
protected void pinMessage(MafiaInstance instance, Message message) {
    instance.putAttribute(ATTR_MESSAGE_ID + instance.getState().name(), message.getId());
    if (message.getTextChannel().getGuild().getSelfMember().hasPermission(message.getTextChannel(),
            Permission.MESSAGE_MANAGE)) {
        message.getTextChannel().pinMessageById(message.getId()).queue();
    }
}
 
Example #16
Source File: ConsoleMessageQueueWorker.java    From DiscordSRV with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void run() {
    while (true) {
        try {
            // don't process, if we get disconnected, another measure to prevent UnknownHostException spam
            if (DiscordUtil.getJda().getStatus() != JDA.Status.CONNECTED) {
                Thread.sleep(3000);
                continue;
            }

            StringBuilder message = new StringBuilder();
            String line = DiscordSRV.getPlugin().getConsoleMessageQueue().poll();
            while (line != null) {
                if (message.length() + line.length() + 1 > Message.MAX_CONTENT_LENGTH) {
                    DiscordUtil.sendMessage(DiscordSRV.getPlugin().getConsoleChannel(), message.toString());
                    message = new StringBuilder();
                }
                message.append(line).append("\n");

                line = DiscordSRV.getPlugin().getConsoleMessageQueue().poll();
            }

            if (StringUtils.isNotBlank(message.toString().replace("\n", "")))
                DiscordUtil.sendMessage(DiscordSRV.getPlugin().getConsoleChannel(), message.toString());

            // make sure rate isn't less than every second because of rate limitations
            // even then, a console channel update /every second/ is pushing it
            int sleepTime = DiscordSRV.config().getInt("DiscordConsoleChannelLogRefreshRateInSeconds") * 1000;
            if (sleepTime < 1000) sleepTime = 1000;

            Thread.sleep(sleepTime);
        } catch (InterruptedException e) {
            DiscordSRV.debug("Broke from Console Message Queue Worker thread: sleep interrupted");
            return;
        }
    }
}
 
Example #17
Source File: MessageServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public <T> void sendTempMessageSilent(Function<T, RestAction<Message>> action, T embed, int sec) {
    sendMessageSilentQueue(action, embed, message -> {
        JDA jda = message.getJDA();
        long messageId = message.getIdLong();
        long channelId = message.getChannel().getIdLong();
        ChannelType type = message.getChannelType();
        scheduler.schedule(() -> {
            MessageChannel channel = DiscordUtils.getChannel(jda, type, channelId);
            if (channel != null) {
                channel.retrieveMessageById(messageId).queue(this::delete);
            }
        }, new DateTime().plusSeconds(sec).toDate());
    });
}
 
Example #18
Source File: MessageServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public <T> void sendMessageSilentQueue(Function<T, RestAction<Message>> action, T embed,
                                       Consumer<Message> messageConsumer) {
    try {
        action.apply(embed).queue(messageConsumer);
    } catch (PermissionException e) {
        // we don't care about it, this is why it is silent
    }
}
 
Example #19
Source File: MessageServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void delete(Message message) {
    if (message != null) {
        actionsHolderService.markAsDeleted(message);
        message.delete().queue();
    }
}
 
Example #20
Source File: MessageServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void delete(Message message, long delayMs) {
    if (message != null) {
        actionsHolderService.markAsDeleted(message);
        message.delete().queueAfter(delayMs, TimeUnit.MILLISECONDS);
    }
}
 
Example #21
Source File: Command.java    From Yui with Apache License 2.0 5 votes vote down vote up
protected Message sendMessage(MessageReceivedEvent e, Message message)
{
    if(e.isFromType(ChannelType.PRIVATE))
        return e.getPrivateChannel().sendMessage(message).complete();
    else
        return e.getTextChannel().sendMessage(message).complete();
}
 
Example #22
Source File: HistoryServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
@Transactional
public void onMessageUpdate(Message message) {
    if (isDisabled(message.getGuild())) {
        return;
    }
    MessageHistory history = historyRepository.findByMessageId(message.getId());
    if (history == null) {
        history = createHistory(message);
        historyRepository.save(history);
        return;
    }
    TextChannel channel = message.getTextChannel();
    String oldContent = decrypt(channel, history);
    String newContent = DiscordUtils.getContent(message);
    if (Objects.equals(oldContent, newContent)) {
        return;
    }
    history.setMessage(encrypt(channel, message.getId(), newContent));
    history.setUpdateDate(new Date());
    historyRepository.save(history);

    auditService.log(message.getGuild(), AuditActionType.MESSAGE_EDIT)
            .withUser(message.getMember())
            .withChannel(channel)
            .withAttribute(MESSAGE_ID, message.getId())
            .withAttribute(OLD_CONTENT, oldContent)
            .withAttribute(NEW_CONTENT, newContent)
            .save();
}
 
Example #23
Source File: IrcConnection.java    From Yui with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(GenericEvent event)
{
    Message msg;
    if (event instanceof GuildMessageReceivedEvent)
    {
        msg = ((GuildMessageReceivedEvent) event).getMessage();
    }
    else if (event instanceof GuildMessageUpdateEvent)
    {
        msg = ((GuildMessageUpdateEvent) event).getMessage();
    }
    else
    {
        return;
    }

    //Basically: If we are the ones that sent the message, don't send it to IRC.
    if (event.getJDA().getSelfUser().equals(msg.getAuthor()))
        return;

    //If this returns null, then this EndPoint isn't part of a bridge.
    EndPoint endPoint = BridgeManager.getInstance().getOtherEndPoint(EndPointInfo.createFromDiscordChannel(msg.getTextChannel()));
    if (endPoint != null)
    {
        EndPointMessage message = EndPointMessage.createFromDiscordEvent(msg);
        endPoint.sendMessage(message);
    }
}
 
Example #24
Source File: MusicController.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@BotCommandHandler
private void provider(Message message) {
  forPlayingTrack(track -> {
    RemoteNode node = manager.getRemoteNodeRegistry().getNodeUsedForTrack(track);

    if (node != null) {
      message.getChannel().sendMessage("Node " + node.getAddress()).queue();
    } else {
      message.getChannel().sendMessage("Not played by a remote node.").queue();
    }
  });
}
 
Example #25
Source File: EndPointMessage.java    From Yui with Apache License 2.0 5 votes vote down vote up
public static EndPointMessage createFromDiscordEvent(Message msg)
{
    EndPointMessage message = new EndPointMessage();
    message.messageType = EndPointType.DISCORD;
    message.setDiscordMessage(msg);
    message.senderName = msg.getAuthor().getName();
    message.discordUser = msg.getAuthor();
    return message;
}
 
Example #26
Source File: MessageCmds.java    From MantaroBot with GNU General Public License v3.0 5 votes vote down vote up
private void prune(Context ctx, List<Message> messageHistory) {
    messageHistory = messageHistory.stream().filter(message -> !message.getTimeCreated()
            .isBefore(OffsetDateTime.now().minusWeeks(2)))
            .collect(Collectors.toList());

    if (messageHistory.isEmpty()) {
        ctx.sendLocalized("commands.prune.messages_too_old", EmoteReference.ERROR);
        return;
    }

    final int size = messageHistory.size();

    if (messageHistory.size() < 3) {
        ctx.sendLocalized("commands.prune.too_few_messages", EmoteReference.ERROR);
        return;
    }

    ctx.getChannel().deleteMessages(messageHistory).queue(
            success -> {
                ctx.sendLocalized("commands.prune.success", EmoteReference.PENCIL, size);

                DBGuild db = ctx.getDBGuild();
                db.getData().setCases(db.getData().getCases() + 1);
                db.saveAsync();
                ModLog.log(ctx.getMember(), null, "Pruned Messages",
                        ctx.getChannel().getName(), ModLog.ModAction.PRUNE, db.getData().getCases(), size
                );
            },
            error -> {
                if (error instanceof PermissionException) {
                    PermissionException pe = (PermissionException) error;
                    ctx.sendLocalized("commands.prune.lack_perms", EmoteReference.ERROR, pe.getPermission());
                } else {
                    ctx.sendLocalized("commands.prune.error_deleting", EmoteReference.ERROR, error.getClass().getSimpleName(), error.getMessage());
                    error.printStackTrace();
                }
            }
    );
}
 
Example #27
Source File: MessageReceivedEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
public MessageReceivedEvent(@Nonnull JDA api, long responseNumber, @Nonnull Message message)
{
    super(api, responseNumber, message.getIdLong(), message.getChannel());
    this.message = message;
}
 
Example #28
Source File: MusicController.java    From lavaplayer with Apache License 2.0 4 votes vote down vote up
@BotCommandHandler
private void seek(Message message, long position) {
  forPlayingTrack(track -> {
    track.setPosition(position);
  });
}
 
Example #29
Source File: MusicController.java    From lavaplayer with Apache License 2.0 4 votes vote down vote up
@BotCommandHandler
private void pos(Message message) {
  forPlayingTrack(track -> {
    message.getChannel().sendMessage("Position is " + track.getPosition()).queue();
  });
}
 
Example #30
Source File: Poll.java    From MantaroBot with GNU General Public License v3.0 4 votes vote down vote up
private Future<Void> createPoll(Message message, I18nContext languageContext) {
    runningPoll = ReactionOperations.create(message, TimeUnit.MILLISECONDS.toSeconds(timeout), new ReactionOperation() {
        @Override
        public int add(MessageReactionAddEvent e) {
            int i = e.getReactionEmote().getName().charAt(0) - '\u0030';
            return Operation.IGNORED; //always return false anyway lul
        }

        @Override
        public void onExpire() {
            if (getChannel() == null)
                return;

            EmbedBuilder embedBuilder = new EmbedBuilder()
                    .setTitle(languageContext.get("commands.poll.result_header"))
                    .setDescription(String.format(languageContext.get("commands.poll.result_screen"),
                            MantaroBot.getInstance().getShardManager().getUserById(owner).getName(), name))
                    .setFooter(languageContext.get("commands.poll.thank_note"), null);

            AtomicInteger react = new AtomicInteger(0);
            AtomicInteger counter = new AtomicInteger(0);

            getChannel().retrieveMessageById(message.getIdLong()).queue(message -> {
                String votes = message.getReactions().stream()
                        .filter(r -> react.getAndIncrement() <= options.length)
                        .map(r -> String.format(languageContext.get("commands.poll.vote_results"), r.getCount() - 1, options[counter.getAndIncrement()]))
                        .collect(Collectors.joining("\n"));

                embedBuilder.addField(languageContext.get("commands.poll.results"), "```diff\n" + votes + "```", false);
                getChannel().sendMessage(embedBuilder.build()).queue();
            });

            getRunningPolls().remove(getChannel().getId());
        }

        @Override
        public void onCancel() {
            getChannel().sendMessageFormat(languageContext.get("commands.poll.cancelled"), EmoteReference.CORRECT).queue();
            onExpire();
        }

    }, reactions(options.length));

    return runningPoll;
}