discord4j.core.object.entity.User Java Examples

The following examples show how to use discord4j.core.object.entity.User. 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: DispatchHandlers.java    From Discord4J with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static Mono<InviteCreateEvent> inviteCreate(DispatchContext<InviteCreate> context) {
    long guildId = Snowflake.asLong(context.getDispatch().guildId());
    long channelId = Snowflake.asLong(context.getDispatch().channelId());
    String code = context.getDispatch().code();
    Instant createdAt = DateTimeFormatter.ISO_OFFSET_DATE_TIME
            .parse(context.getDispatch().createdAt(), Instant::from);
    int uses = context.getDispatch().uses();
    int maxUses = context.getDispatch().maxUses();
    int maxAge = context.getDispatch().maxAge();
    boolean temporary = context.getDispatch().temporary();

    User current = context.getDispatch().inviter().toOptional()
            .map(userData -> new User(context.getGateway(), userData))
            .orElse(null);

    return Mono.just(new InviteCreateEvent(context.getGateway(), context.getShardInfo(), guildId, channelId, code,
            current, createdAt, uses, maxUses, maxAge, temporary));
}
 
Example #2
Source File: AudioLoadResultListener.java    From Shadbot with GNU General Public License v3.0 6 votes vote down vote up
private void onSearchResult(AudioPlaylist playlist) {
    Mono.justOrEmpty(MusicManager.getInstance().getGuildMusic(this.guildId))
            .flatMapMany(guildMusic -> {
                this.resultTracks = playlist.getTracks()
                        .subList(0, Math.min(Config.MUSIC_SEARCHES, playlist.getTracks().size()));

                guildMusic.setDjId(this.djId);
                guildMusic.setWaitingForChoice(true);

                return guildMusic.getGateway()
                        .getUserById(guildMusic.getDjId())
                        .map(User::getAvatarUrl)
                        .flatMap(avatarUrl -> this.getPlaylistEmbed(playlist, avatarUrl))
                        .flatMap(embed -> guildMusic.getMessageChannel()
                                .flatMap(channel -> DiscordUtils.sendMessage(embed, channel)))
                        .flatMapMany(ignored ->
                                AudioLoadResultInputs.create(guildMusic.getGateway(), Duration.ofSeconds(30),
                                        guildMusic.getMessageChannelId(), this)
                                        .waitForInputs()
                                        .then(Mono.fromRunnable(() -> guildMusic.setWaitingForChoice(false))));
            })
            .then(this.terminate())
            .subscribeOn(Schedulers.boundedElastic())
            .subscribe(null, ExceptionHandler::handleUnknownError);
}
 
Example #3
Source File: FeedbackCmd.java    From Shadbot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Mono<Void> execute(Context context) {
    final String arg = context.requireArg();

    return context.getClient()
            .getUserById(Shadbot.getOwnerId())
            .flatMap(User::getPrivateChannel)
            .cast(MessageChannel.class)
            .flatMap(channel -> DiscordUtils.sendMessage(
                    String.format(Emoji.SPEECH + " Feedback from **%s** (User ID: %d, Guild ID: %d):%n%s",
                            context.getUsername(), context.getAuthorId().asLong(), context.getGuildId().asLong(), arg), channel))
            .then(context.getChannel())
            .flatMap(channel -> DiscordUtils.sendMessage(
                    String.format(Emoji.INFO + " (**%s**) Feedback sent, thank you!", context.getUsername()), channel))
            .then();
}
 
Example #4
Source File: Game.java    From Shadbot with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param message The {@link Message} to check.
 * @return A {@link Mono} that returns {@code true} if the {@link Message} is a valid
 * cancel command, {@code false} otherwise.
 */
public Mono<Boolean> isCancelMessage(Message message) {
    if (message.getContent().isEmpty() || message.getAuthor().isEmpty()) {
        return Mono.just(false);
    }

    final String content = message.getContent();
    final User author = message.getAuthor().orElseThrow();
    if (content.equals(String.format("%scancel", this.context.getPrefix()))) {
        return message.getChannel()
                .flatMap(channel -> DiscordUtils.hasPermission(channel, author.getId(), Permission.ADMINISTRATOR))
                // The author is the author of the game or he is an administrator
                .map(isAdmin -> this.context.getAuthorId().equals(author.getId()) || isAdmin);
    }

    return Mono.just(false);
}
 
Example #5
Source File: ExampleAllowedMentions.java    From Discord4J with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static Mono<Message> sendAllowedMentionsMessage(MessageCreateEvent event) {
    final User author = event.getMessage().getAuthor().get();
    return event.getMessage().getChannel()
            .flatMap(channel ->
                    channel.createMessage(spec -> {
                        spec.setContent("Hello " + author.getMention() + ", get pinged!");
                        spec.setAllowedMentions(AllowedMentions.builder()
                                .allowUser(author.getId())
                                .build());
                    }).thenReturn(channel))
            .flatMap(channel ->
                    channel.createMessage(spec -> {
                        spec.setContent("Hello " + author.getMention() + ", get (not) pinged!");
                        spec.setAllowedMentions(AllowedMentions.builder().build());
                    }).thenReturn(channel))
            .flatMap(channel ->
                    channel.createMessage(spec -> {
                        spec.setContent("This is invalid")
                                .setAllowedMentions(AllowedMentions.builder()
                                        .parseType(AllowedMentions.Type.USER)
                                        .allowUser(author.getId())
                                        .build());
                    }));
}
 
Example #6
Source File: InviteCommand.java    From KaellyBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void request(Message message, Matcher m, Language lg) {
    Optional<ApplicationInfo> appInfo = message.getClient().getApplicationInfo().blockOptional();

    if (appInfo.isPresent()) {
        Optional<User> author = appInfo.get().getOwner().blockOptional();

        message.getChannel().flatMap(chan -> chan
                .createEmbed(spec -> spec.setTitle(Translator.getLabel(lg, "about.title")
                        .replace("{name}", Constants.name)
                        .replace("{version}", Constants.version))
                        .setColor(Color.GRAY)
                        .setThumbnail(appInfo.get().getIcon(Image.Format.PNG).orElse(null))
                        .setAuthor(author.map(User::getUsername).orElse(authorName), null,
                                author.map(User::getAvatarUrl).orElse(authorAvatar))
                        .addField(Translator.getLabel(lg, "about.invite.title"),
                                Translator.getLabel(lg, "about.invite.desc")
                                        .replace("{name}", Constants.name)
                                        .replace("{invite}", Constants.invite), true)
                        .addField(Translator.getLabel(lg, "about.support.title"),
                                Translator.getLabel(lg, "about.support.desc")
                                        .replace("{name}", Constants.name)
                                        .replace("{discordInvite}", Constants.discordInvite), true)))
                .subscribe();
    }
}
 
Example #7
Source File: PrefixCommand.java    From KaellyBot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void request(Message message, Matcher m, Language lg) {
    if (isUserHasEnoughRights(message)) {
        String newPrefix = m.group(1).trim();
        Optional<discord4j.core.object.entity.Guild> guildOptional = message.getGuild().blockOptional();
        if (newPrefix.length() >= 1 && newPrefix.length() <= Constants.prefixeLimit && guildOptional.isPresent()) {
            Guild.getGuild(guildOptional.get()).setPrefix(newPrefix);
            message.getChannel().flatMap(chan -> chan
                    .createMessage(Translator.getLabel(lg, "prefix.request.1")
                            .replace("{prefix}", getPrefixMdEscaped(message))))
                    .subscribe();

            guildOptional.get().getOwner().flatMap(User::getPrivateChannel)
                    .flatMap(chan -> chan.createMessage(Translator.getLabel(lg, "prefix.request.2")
                            .replace("{prefix}", getPrefixMdEscaped(message))
                            .replace("{guild.name}", guildOptional.get().getName())))
                    .subscribe();
        }
        else
            prefixeOutOfBounds.throwException(message, this, lg);
    }
    else
        BasicDiscordException.NO_ENOUGH_RIGHTS.throwException(message, this, lg);
}
 
Example #8
Source File: GuildDeleteListener.java    From Shadbot with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Mono<Void> execute(GuildDeleteEvent event) {
    DEFAULT_LOGGER.info("{Guild ID: {}} Disconnected", event.getGuildId().asLong());

    final Mono<Void> deleteGuild = DatabaseManager.getGuilds()
            .getDBGuild(event.getGuildId())
            .flatMap(DBGuild::delete);

    final Mono<Message> sendMessage = Mono.defer(() ->
            Mono.justOrEmpty(
                    CacheManager.getInstance().getGuildOwnersCache().delete(event.getGuildId())))
            .flatMap(event.getClient()::getUserById)
            .flatMap(User::getPrivateChannel)
            .flatMap(channel -> DiscordUtils.sendMessage(TEXT, channel))
            .onErrorResume(ClientException.class, err -> Mono.empty());

    return MusicManager.getInstance().destroyConnection(event.getGuildId())
            .and(deleteGuild)
            .and(sendMessage);
}
 
Example #9
Source File: LifecycleDispatchHandlers.java    From Discord4J with GNU Lesser General Public License v3.0 6 votes vote down vote up
static Mono<ReadyEvent> ready(DispatchContext<Ready> context) {
    GatewayDiscordClient gateway = context.getGateway();
    Ready dispatch = context.getDispatch();
    UserData userData = dispatch.user();
    long userId = Snowflake.asLong(userData.id());

    User self = new User(gateway, userData);
    Set<ReadyEvent.Guild> guilds = dispatch.guilds()
            .stream()
            .map(g -> new ReadyEvent.Guild(Snowflake.asLong(g.id()), !g.unavailable().get()))
            .collect(Collectors.toSet());

    Mono<Void> saveUser = context.getStateHolder().getUserStore()
            .save(userId, userData);

    return saveUser
            .thenReturn(new ReadyEvent(gateway, context.getShardInfo(), dispatch.v(), self, guilds,
                    dispatch.sessionId(), dispatch.trace()));
}
 
Example #10
Source File: Reporter.java    From KaellyBot with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Rejette une exception dans un salon discord. Politique du "posté uniquement une fois"
 * @param exception Exception à rejeter
 * @param guild Guilde d'origine de l'erreur
 * @param channel Salon d'origine de l'erreur
 * @param user Auteur du message d'origine de l'erreur
 * @param message Contenu du message à l'origine de l'erreur
 */
public void send(Exception exception, Guild guild, Channel channel, User user, discord4j.core.object.entity.Message message){
    try {
        Sentry.getContext().clearTags();
        if (guild != null)
            Sentry.getContext().addTag(GUILD, guild.getId().asString() + " - " + guild.getName());
        if (channel != null)
            Sentry.getContext().addTag(CHANNEL, channel.getId().asString() + " - " + channel.getId());
        if (user != null)
            Sentry.getContext().addTag(USER, user.getId().asString() + " - " + user.getUsername());
        if (message != null)
            Sentry.getContext().addTag(MESSAGE, message.getContent().orElse(""));

        Sentry.capture(exception);

    } catch(Exception e){
        Sentry.capture(exception);
        LOG.error("report", exception);
        Sentry.capture(e);
        LOG.error("report", e);
    }
}
 
Example #11
Source File: LeaderboardCmd.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Mono<Void> execute(Context context) {
    return DatabaseManager.getGuilds()
            .getDBGuild(context.getGuildId())
            .flatMapIterable(DBGuild::getMembers)
            .filter(dbMember -> dbMember.getCoins() > 0)
            .sort(Comparator.comparingLong(DBMember::getCoins).reversed())
            .take(USER_COUNT)
            .flatMapSequential(dbMember -> Mono.zip(
                    context.getClient().getUserById(dbMember.getId()).map(User::getUsername),
                    Mono.just(dbMember.getCoins())))
            .collectList()
            .map(list -> {
                if (list.isEmpty()) {
                    return "\nEveryone is poor here.";
                }
                return FormatUtils.numberedList(USER_COUNT, list.size(),
                        count -> {
                            final Tuple2<String, Long> tuple = list.get(count - 1);
                            return String.format("%d. **%s** - %s",
                                    count, tuple.getT1(), FormatUtils.coins(tuple.getT2()));
                        });
            })
            .map(description -> ShadbotUtils.getDefaultEmbed()
                    .andThen(embed -> embed.setAuthor("Leaderboard", null, context.getAvatarUrl())
                            .setDescription(description)))
            .flatMap(embed -> context.getChannel()
                    .flatMap(channel -> DiscordUtils.sendMessage(embed, channel)))
            .then();
}
 
Example #12
Source File: PlayCmd.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
private Mono<Void> play(Context context, MessageChannel channel, GuildMusic guildMusic, String identifier) {
    // Someone is already selecting a music...
    if (guildMusic.isWaitingForChoice()) {
        if (guildMusic.getDjId().equals(context.getAuthorId())) {
            return Mono.error(new CommandException(String.format("You're already selecting a music. "
                    + "Enter a number or use `%scancel` to cancel the selection.", context.getPrefix())));
        }

        if (identifier.startsWith(AudioLoadResultListener.SC_SEARCH) || identifier.startsWith(AudioLoadResultListener.YT_SEARCH)) {
            return context.getClient()
                    .getUserById(guildMusic.getDjId())
                    .map(User::getUsername)
                    .flatMap(djName -> DiscordUtils.sendMessage(String.format(Emoji.HOURGLASS + " (**%s**) **%s** is "
                                    + "already selecting a music, please wait for him to finish.",
                            context.getUsername(), djName), channel))
                    .then();
        }
    }

    return DatabaseManager.getPremium()
            .isPremium(context.getGuildId(), context.getAuthorId())
            .filter(isPremium -> guildMusic.getTrackScheduler().getPlaylist().size() < Config.PLAYLIST_SIZE - 1 || isPremium)
            .doOnNext(ignored -> {
                final boolean insertFirst = context.getCommandName().endsWith("first");
                final AudioLoadResultListener resultListener = new AudioLoadResultListener(
                        context.getGuildId(), context.getAuthorId(), identifier, insertFirst);

                guildMusic.setMessageChannelId(context.getChannelId());
                guildMusic.addAudioLoadResultListener(resultListener, identifier);
            })
            .switchIfEmpty(DiscordUtils.sendMessage(ShadbotUtils.PLAYLIST_LIMIT_REACHED, channel)
                    .then(Mono.empty()))
            .then();
}
 
Example #13
Source File: InfoCmd.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
private String getShadbotSection(Context context, User owner) {
    final String uptime = FormatUtils.formatDurationWords(
            Duration.ofMillis(TimeUtils.getMillisUntil(Shadbot.getLaunchTime())));

    return String.format("%n%n-= Shadbot =-")
            + String.format("%nUptime: %s", uptime)
            + String.format("%nDeveloper: %s", owner.getTag())
            + String.format("%nShard: %d/%d", context.getShardIndex() + 1, context.getShardCount())
            + String.format("%nServers: %s", FormatUtils.number(CacheManager.getInstance().getGuildOwnersCache().count()))
            + String.format("%nVoice Channels: %s", FormatUtils.number(VoiceStateUpdateListener.VOICE_COUNT_GAUGE.get()));
}
 
Example #14
Source File: MemberJoinListener.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
public static Mono<Message> sendAutoMessage(GatewayDiscordClient gateway, User user, Snowflake channelId, String message) {
    return gateway.getChannelById(channelId)
            .cast(MessageChannel.class)
            .flatMap(channel -> DiscordUtils.sendMessage(message
                    .replace("{username}", user.getUsername())
                    .replace("{userId}", user.getId().asString())
                    .replace("{mention}", user.getMention()), channel));
}
 
Example #15
Source File: ReactionListener.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
private static Mono<Void> iam(Message message, Snowflake userId, ReactionEmoji emoji, Action action) {
    // If this is the correct reaction
    if (!emoji.equals(IamCmd.REACTION)) {
        return Mono.empty();
    }

    return Mono.just(message.getClient().getSelfId())
            // It wasn't the bot that reacted
            .filter(selfId -> !userId.equals(selfId))
            // If the bot is not the author of the message, this is not an Iam message
            .filter(selfId -> message.getAuthor().map(User::getId).map(selfId::equals).orElse(false))
            .flatMap(ignored -> message.getGuild().flatMap(guild -> guild.getMemberById(userId)))
            .flatMap(member -> ReactionListener.execute(message, member, action));
}
 
Example #16
Source File: DispatchHandlers.java    From Discord4J with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static Mono<UserUpdateEvent> userUpdate(DispatchContext<UserUpdate> context) {
    GatewayDiscordClient gateway = context.getGateway();
    UserData userData = context.getDispatch().user();
    long userId = Snowflake.asLong(userData.id());
    User current = new User(gateway, userData);

    Mono<Void> saveNew = context.getStateHolder().getUserStore().save(userId, userData);

    return context.getStateHolder().getUserStore()
            .find(userId)
            .flatMap(saveNew::thenReturn)
            .map(old -> new UserUpdateEvent(gateway, context.getShardInfo(), current, new User(gateway, old)))
            .switchIfEmpty(saveNew.thenReturn(new UserUpdateEvent(gateway, context.getShardInfo(), current, null)));
}
 
Example #17
Source File: ReadyEvent.java    From Discord4J with GNU Lesser General Public License v3.0 5 votes vote down vote up
public ReadyEvent(GatewayDiscordClient gateway, ShardInfo shardInfo, int gatewayVersion, User self,
                  Set<Guild> guilds, String sessionId, List<String> trace) {
    super(gateway, shardInfo);
    this.gatewayVersion = gatewayVersion;
    this.self = self;
    this.guilds = guilds;
    this.sessionId = sessionId;
    this.trace = trace;
}
 
Example #18
Source File: BotSupport.java    From Discord4J with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static Mono<Void> commandHandler(GatewayDiscordClient client) {
    Mono<Long> ownerId = client.rest().getApplicationInfo()
            .map(ApplicationInfoData::owner)
            .map(user -> Snowflake.asLong(user.id()))
            .cache();

    List<EventHandler> eventHandlers = new ArrayList<>();
    eventHandlers.add(new Echo());
    eventHandlers.add(new Status());
    eventHandlers.add(new StatusEmbed());
    eventHandlers.add(new Exit());
    eventHandlers.add(new RequestMembers());
    eventHandlers.add(new GetMembers());

    return client.on(MessageCreateEvent.class,
            event -> ownerId.filter(
                    owner -> {
                        Long author = event.getMessage().getAuthor()
                                .map(User::getId)
                                .map(Snowflake::asLong)
                                .orElse(null);
                        return owner.equals(author);
                    })
                    .flatMap(id -> Mono.when(eventHandlers.stream()
                            .map(handler -> handler.onMessageCreate(event))
                            .collect(Collectors.toList()))
                    ))
            .then();
}
 
Example #19
Source File: ConfirmInputs.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Mono<Boolean> isValidEvent(MessageCreateEvent event) {
    return Mono.justOrEmpty(event.getMessage().getAuthor())
            .map(User::getId)
            .filter(Shadbot.getOwnerId()::equals)
            .map(ignored -> event.getMessage().getContent())
            .map(content -> {
                if ("n".equalsIgnoreCase(content) || "no".equalsIgnoreCase(content)) {
                    this.isCancelled.set(true);
                }
                return "y".equalsIgnoreCase(content) || "yes".equalsIgnoreCase(content);
            });
}
 
Example #20
Source File: PresenceUpdateEvent.java    From Discord4J with GNU Lesser General Public License v3.0 5 votes vote down vote up
public PresenceUpdateEvent(GatewayDiscordClient gateway, ShardInfo shardInfo, long guildId, @Nullable User oldUser,
                           PartialUserData user, Presence current, @Nullable Presence old) {
    super(gateway, shardInfo);
    this.guildId = guildId;
    this.oldUser = oldUser;
    this.user = user;
    this.current = current;
    this.old = old;
}
 
Example #21
Source File: InviteCreateEvent.java    From Discord4J with GNU Lesser General Public License v3.0 5 votes vote down vote up
public InviteCreateEvent(GatewayDiscordClient client, ShardInfo shardInfo, Long guildId, long channelId,
                         String code, @Nullable User inviter, Instant createdAt, int uses, int maxUses, int maxAge,
                         boolean temporary) {
    super(client, shardInfo);
    this.guildId = guildId;
    this.channelId = channelId;
    this.code = code;
    this.inviter = inviter;
    this.createdAt = createdAt;
    this.uses = uses;
    this.maxAge = maxAge;
    this.maxUses = maxUses;
    this.temporary = temporary;
}
 
Example #22
Source File: MessageProcessor.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
public static Mono<Void> processEvent(MessageCreateEvent event) {
    // The message is a webhook or a bot, ignore
    if (event.getMessage().getAuthor().map(User::isBot).orElse(true)) {
        return Mono.empty();
    }

    return Mono.justOrEmpty(event.getGuildId())
            // This is a private channel, there is no guild ID
            .switchIfEmpty(MessageProcessor.processPrivateMessage(event).then(Mono.empty()))
            .flatMap(guildId -> MessageProcessor.processGuildMessage(guildId, event));
}
 
Example #23
Source File: MemberLeaveEvent.java    From Discord4J with GNU Lesser General Public License v3.0 4 votes vote down vote up
public MemberLeaveEvent(GatewayDiscordClient gateway, ShardInfo shardInfo, User user, long guildId, @Nullable Member member) {
    super(gateway, shardInfo);
    this.user = user;
    this.guildId = guildId;
    this.member = member;
}
 
Example #24
Source File: BanEvent.java    From Discord4J with GNU Lesser General Public License v3.0 4 votes vote down vote up
public BanEvent(GatewayDiscordClient gateway, ShardInfo shardInfo, User user, long guildId) {
    super(gateway, shardInfo);
    this.user = user;
    this.guildId = guildId;
}
 
Example #25
Source File: UnbanEvent.java    From Discord4J with GNU Lesser General Public License v3.0 4 votes vote down vote up
public UnbanEvent(GatewayDiscordClient gateway, ShardInfo shardInfo, User user, long guildId) {
    super(gateway, shardInfo);
    this.user = user;
    this.guildId = guildId;
}
 
Example #26
Source File: FallbackEntityRetriever.java    From Discord4J with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public Mono<User> getSelf() {
    return first.getSelf().switchIfEmpty(fallback.getSelf());
}
 
Example #27
Source File: PruneCmd.java    From Shadbot with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Mono<Void> execute(Context context) {
    final UpdatableMessage updatableMsg = new UpdatableMessage(context.getClient(), context.getChannelId());

    return updatableMsg.setContent(String.format(Emoji.HOURGLASS + " (**%s**) Loading messages to prune...",
            context.getUsername()))
            .send()
            .then(context.getChannel())
            .flatMap(channel -> DiscordUtils.requirePermissions(channel,
                    Permission.MANAGE_MESSAGES, Permission.READ_MESSAGE_HISTORY)
                    .then(context.getMessage().getUserMentions().collectList())
                    .flatMapMany(mentions -> {
                        final String arg = context.getArg().orElse("");
                        final List<String> quotedElements = StringUtils.getQuotedElements(arg);

                        if (arg.contains("\"") && quotedElements.isEmpty() || quotedElements.size() > 1) {
                            return Flux.error(new CommandException("You have forgotten a quote or have specified " +
                                    "several quotes in quotation marks."));
                        }

                        final String words = quotedElements.isEmpty() ? null : quotedElements.get(0);

                        // Remove everything from argument (users mentioned and quoted words) to keep only count if specified
                        final String argCleaned = StringUtils.remove(arg,
                                FormatUtils.format(mentions, User::getMention, " "),
                                String.format("\"%s\"", words))
                                .trim();

                        Integer count = NumberUtils.toPositiveIntOrNull(argCleaned);
                        if (!argCleaned.isEmpty() && count == null) {
                            return Flux.error(new CommandException(String.format("`%s` is not a valid number. " +
                                            "If you want to specify a word or a sentence, please include them " +
                                            "in quotation marks. See `%shelp %s` for more information.",
                                    argCleaned, context.getPrefix(), this.getName())));
                        }

                        // The count is incremented by MESSAGES_OFFSET to take into account the command
                        count = count == null ? MAX_MESSAGES : Math.min(MAX_MESSAGES, count + MESSAGES_OFFSET);

                        final List<Snowflake> mentionIds = mentions.stream().map(User::getId).collect(Collectors.toList());

                        return channel.getMessagesBefore(Snowflake.of(Instant.now()))
                                .take(count)
                                .filter(message -> mentions.isEmpty()
                                        || message.getAuthor().map(User::getId).map(mentionIds::contains).orElse(false))
                                .filter(message -> words == null
                                        || message.getContent().contains(words)
                                        || this.getEmbedContent(message).contains(words));
                    })
                    .map(Message::getId)
                    .collectList()
                    .flatMap(messageIds -> ((GuildMessageChannel) channel).bulkDelete(Flux.fromIterable(messageIds))
                            .count()
                            .map(messagesNotDeleted -> messageIds.size() - messagesNotDeleted))
                    .map(deletedMessages -> String.format(Emoji.CHECK_MARK + " (Requested by **%s**) %s deleted.",
                            context.getUsername(),
                            StringUtils.pluralOf(deletedMessages - MESSAGES_OFFSET, "message"))))
            .map(updatableMsg::setContent)
            .flatMap(UpdatableMessage::send)
            .onErrorResume(err -> updatableMsg.deleteMessage().then(Mono.error(err)))
            .then();
}
 
Example #28
Source File: Logger.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void debug(@Nullable User author, String message, @Nullable String info, boolean postWebhook, Class clazz) {
	String timeStamp = new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss").format(Calendar.getInstance().getTime());
	//ALWAYS LOG TO FILE!
	try {
		FileWriter file = new FileWriter(debugFile, true);
		file.write("DEBUG --- " + timeStamp + " ---" + GlobalConst.lineBreak);
		if (author != null)
			file.write("user: " + author.getUsername() + "#" + author.getDiscriminator() + GlobalConst.lineBreak);

		if (message != null)
			file.write("message: " + message + GlobalConst.lineBreak);

		if (info != null)
			file.write("info: " + info + GlobalConst.lineBreak);

		file.write("Class: " + clazz.getName() + GlobalConst.lineBreak);

		file.close();
	} catch (IOException io) {
		io.printStackTrace();
	}

	//Post to webhook if wanted.
	if (BotSettings.USE_WEBHOOKS.get().equalsIgnoreCase("true") && postWebhook) {
		WebhookEmbedBuilder builder = new WebhookEmbedBuilder()
			.setTitle(new WebhookEmbed.EmbedTitle("Debug", null))
			.addField(new WebhookEmbed
				.EmbedField(true, "Shard Index", BotSettings.SHARD_INDEX.get()))
			.setDescription(message)
			.setColor(GlobalConst.discalColor.getRGB())
			.setTimestamp(Instant.now());

		if (author != null) {
			builder.setAuthor(new WebhookEmbed
				.EmbedAuthor(author.getUsername(), author.getAvatarUrl(), null));
		}
		if (info != null) {
			builder.addField(new WebhookEmbed.EmbedField(false, "Info", info));
		}

		debugClient.send(builder.build());
	}
}
 
Example #29
Source File: Logger.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void exception(@Nullable User author, @Nullable String message, Exception e, boolean postWebhook, Class clazz) {
	String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime());
	StringWriter sw = new StringWriter();
	PrintWriter pw = new PrintWriter(sw);
	e.printStackTrace(pw);
	String error = sw.toString(); // stack trace as a string
	pw.close();
	try {
		sw.close();
	} catch (IOException e1) {
		//Can ignore silently...
	}

	//ALWAYS LOG TO FILE!
	try {
		FileWriter exceptions = new FileWriter(exceptionsFile, true);
		exceptions.write("ERROR --- " + timeStamp + " ---" + GlobalConst.lineBreak);
		if (author != null)
			exceptions.write("user: " + author.getUsername() + "#" + author.getDiscriminator() + GlobalConst.lineBreak);

		if (message != null)
			exceptions.write("message: " + message + GlobalConst.lineBreak);

		exceptions.write("Class:" + clazz.getName() + GlobalConst.lineBreak);

		exceptions.write(error + GlobalConst.lineBreak);
		exceptions.close();
	} catch (IOException io) {
		io.printStackTrace();
	}

	//Post to webhook if wanted.
	if (BotSettings.USE_WEBHOOKS.get().equalsIgnoreCase("true") && postWebhook) {
		//Shorten error message...
		if (error.length() > 1500)
			error = error.substring(0, 1500);

		WebhookEmbedBuilder builder = new WebhookEmbedBuilder()
			.setTitle(new WebhookEmbed.EmbedTitle("Exception", null))
			.addField(new WebhookEmbed
				.EmbedField(true, "Shard Index", BotSettings.SHARD_INDEX.get()))
			.addField(new WebhookEmbed
				.EmbedField(false, "Class", clazz.getName()))
			.setDescription(error)
			.setColor(GlobalConst.discalColor.getRGB())
			.setTimestamp(Instant.now());

		if (author != null) {
			builder.setAuthor(new WebhookEmbed
				.EmbedAuthor(author.getUsername(), author.getAvatarUrl(), null));
		}
		if (message != null) {
			builder.addField(new WebhookEmbed.EmbedField(false, "Message", message));
		}

		exceptionClient.send(builder.build());
	}
}
 
Example #30
Source File: Poll.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 4 votes vote down vote up
public User getUser() {
	return user;
}