discord4j.core.object.entity.Message Java Examples
The following examples show how to use
discord4j.core.object.entity.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: PrefixCommand.java From KaellyBot with GNU General Public License v3.0 | 6 votes |
@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 #2
Source File: InviteCommand.java From KaellyBot with GNU General Public License v3.0 | 6 votes |
@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 #3
Source File: CalendarCreator.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 6 votes |
/** * Initiates the CalendarCreator for the guild involved in the event. * * @param e The event received upon creation start. * @param calendarName The name of the calendar to create. * @return The PreCalendar object created. */ public PreCalendar init(MessageCreateEvent e, String calendarName, GuildSettings settings, boolean handleCreatorMessage) { if (!hasPreCalendar(settings.getGuildID())) { PreCalendar calendar = new PreCalendar(settings.getGuildID(), calendarName); if (handleCreatorMessage) { if (PermissionChecker.botHasMessageManagePerms(e)) { Message msg = MessageManager.sendMessageSync(MessageManager.getMessage("Creator.Calendar.Create.Init", settings), CalendarMessageFormatter.getPreCalendarEmbed(calendar, settings), e); calendar.setCreatorMessage(msg); } else { MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Notif.MANAGE_MESSAGES", settings), e); } } calendars.add(calendar); return calendar; } return getPreCalendar(settings.getGuildID()); }
Example #4
Source File: TutorialCommand.java From KaellyBot with GNU General Public License v3.0 | 6 votes |
@Override public void request(Message message, Matcher m, Language lg) { String normalName = Normalizer.normalize(m.group(1).trim(), Normalizer.Form.NFD) .replaceAll("\\p{InCombiningDiacriticalMarks}+", "").toLowerCase(); String editedName = removeUselessWords(normalName); BestMatcher matcher = new BestMatcher(normalName); try { matcher.evaluateAll(getListTutoFrom(getSearchURL(editedName), message)); if (matcher.isUnique())// We have found it ! message.getChannel().flatMap(chan -> chan .createMessage(Translator.getLabel(lg, "tutorial.request") + " " + Constants.dofusPourLesNoobURL + matcher.getBest().getUrl())) .subscribe(); else if (! matcher.isEmpty()) // Too much tutos tooMuchTutos.throwException(message, this, lg, matcher.getBests()); else // empty notFoundTuto.throwException(message, this, lg); } catch(IOException e){ ExceptionManager.manageIOException(e, message, this, lg, notFoundTuto); } }
Example #5
Source File: DiscordUtils.java From Shadbot with GNU General Public License v3.0 | 6 votes |
public static Mono<Member> extractMemberOrAuthor(Guild guild, Message message) { final String[] args = message.getContent().split(" "); if (args.length == 1) { return message.getAuthorAsMember(); } if (args.length > 2) { return Mono.error(new CommandException("You can't specify more than one user.")); } return message.getUserMentions() .switchIfEmpty(DiscordUtils.extractMembers(guild, message.getContent())) .next() .flatMap(user -> user.asMember(guild.getId())) .switchIfEmpty(Mono.error(new CommandException(String.format("User **%s** not found.", args[1])))); }
Example #6
Source File: GuildDeleteListener.java From Shadbot with GNU General Public License v3.0 | 6 votes |
@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 #7
Source File: EventCreator.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 6 votes |
/** * Initiates the EventCreator for a specific guild. * * @param e The event received upon initialization. * @return The PreEvent for the guild. */ public PreEvent init(MessageCreateEvent e, GuildSettings settings, boolean handleMessage) { if (!hasPreEvent(settings.getGuildID())) { PreEvent event = new PreEvent(settings.getGuildID()); try { //TODO: Handle multiple calendars... String calId = DatabaseManager.getManager().getMainCalendar(settings.getGuildID()).getCalendarAddress(); event.setTimeZone(CalendarAuth.getCalendarService(settings).calendars().get(calId).execute().getTimeZone()); } catch (Exception exc) { //Failed to get timezone, ignore safely. } if (handleMessage) { if (PermissionChecker.botHasMessageManagePerms(e)) { Message message = MessageManager.sendMessageSync(MessageManager.getMessage("Creator.Event.Create.Init", settings), EventMessageFormatter.getPreEventEmbed(event, settings), e); event.setCreatorMessage(message); MessageManager.deleteMessage(e); } else { MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Notif.MANAGE_MESSAGES", settings), e); } } events.add(event); return event; } return getPreEvent(settings.getGuildID()); }
Example #8
Source File: AnnouncementCreator.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 6 votes |
public Announcement init(MessageCreateEvent e, String announcementId, GuildSettings settings) { if (!hasAnnouncement(settings.getGuildID()) && AnnouncementUtils.announcementExists(announcementId, settings.getGuildID())) { Announcement toCopy = DatabaseManager.getManager().getAnnouncement(UUID.fromString(announcementId), settings.getGuildID()); //Copy Announcement a = new Announcement(toCopy); if (PermissionChecker.botHasMessageManagePerms(e)) { Message msg = MessageManager.sendMessageSync(MessageManager.getMessage("Creator.Announcement.Copy.Success", settings), AnnouncementMessageFormatter.getFormatAnnouncementEmbed(a, settings), e); a.setCreatorMessage(msg); } else { MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Notif.MANAGE_MESSAGES", settings), e); } announcements.add(a); return a; } return getAnnouncement(settings.getGuildID()); }
Example #9
Source File: UpdatableMessage.java From Shadbot with GNU General Public License v3.0 | 6 votes |
/** * Delete the previous message sent, if present, then send a message with the provided content and embed. * * @param content The content to send, may be null. * @param embed The embed to send, may be null. */ private Mono<Message> send(@Nullable String content, @Nullable Consumer<EmbedCreateSpec> embed) { final Consumer<MessageCreateSpec> consumer = spec -> { if (content != null) { spec.setContent(content); } if (embed != null) { spec.setEmbed(embed); } }; return this.deleteMessage() .then(this.gateway.getChannelById(this.channelId)) .cast(MessageChannel.class) .flatMap(channel -> DiscordUtils.sendMessage(consumer, channel, embed != null)) .doOnNext(message -> this.messageId.set(message.getId().asLong())); }
Example #10
Source File: Main.java From lavaplayer with Apache License 2.0 | 6 votes |
private void onMessageReceived(MessageCreateEvent event) { Message message = event.getMessage(); message.getContent().ifPresent(it -> { MessageChannel channel = message.getChannel().block(); if (channel instanceof TextChannel) { String[] command = it.split(" ", 2); if ("~play".equals(command[0]) && command.length == 2) { loadAndPlay((TextChannel) channel, command[1]); } else if ("~skip".equals(command[0])) { skipTrack((TextChannel) channel); } } }); }
Example #11
Source File: EventCommand.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 6 votes |
private void moduleCancel(MessageCreateEvent event, GuildSettings settings) { Message msg = null; if (EventCreator.getCreator().hasCreatorMessage(settings.getGuildID())) msg = EventCreator.getCreator().getCreatorMessage(settings.getGuildID()); if (EventCreator.getCreator().terminate(settings.getGuildID())) { if (msg != null) { MessageManager.deleteMessage(event); MessageManager.deleteMessage(msg); MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Event.Cancel.Success", settings), event); } else { MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Event.Cancel.Success", settings), event); } } else { MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Event.NotInit", settings), event); } }
Example #12
Source File: EventCommand.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 6 votes |
private void moduleRestart(String[] args, MessageCreateEvent event, CalendarData calendarData, GuildSettings settings) { Message msg = null; boolean editing = false; if (EventCreator.getCreator().hasPreEvent(settings.getGuildID())) editing = EventCreator.getCreator().getPreEvent(settings.getGuildID()).isEditing(); if (EventCreator.getCreator().hasCreatorMessage(settings.getGuildID())) msg = EventCreator.getCreator().getCreatorMessage(settings.getGuildID()); if (EventCreator.getCreator().terminate(settings.getGuildID())) { if (msg != null) { MessageManager.deleteMessage(msg); MessageManager.deleteMessage(event); } if (!editing) moduleCreate(args, event, calendarData, settings); else moduleEdit(args, event, calendarData, settings); } else { MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Event.NotInit", settings), event); } }
Example #13
Source File: EventCommand.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 6 votes |
private void moduleCancel(MessageCreateEvent event, GuildSettings settings) { Message msg = null; if (EventCreator.getCreator().hasCreatorMessage(settings.getGuildID())) msg = EventCreator.getCreator().getCreatorMessage(settings.getGuildID()); if (EventCreator.getCreator().terminate(settings.getGuildID())) { if (msg != null) { MessageManager.deleteMessage(event); MessageManager.deleteMessage(msg); MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Event.Cancel.Success", settings), event); } else { MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Event.Cancel.Success", settings), event); } } else { MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Event.NotInit", settings), event); } }
Example #14
Source File: PollManager.java From Shadbot with GNU General Public License v3.0 | 6 votes |
private Mono<Void> show() { final StringBuilder representation = new StringBuilder(); for (int i = 0; i < this.spec.getChoices().size(); i++) { representation.append(String.format("%n\t**%d.** %s", i + 1, this.spec.getChoices().keySet().toArray()[i])); } final Consumer<EmbedCreateSpec> embedConsumer = ShadbotUtils.getDefaultEmbed() .andThen(embed -> embed.setAuthor(String.format("Poll by %s", this.context.getUsername()), null, this.context.getAvatarUrl()) .setDescription(String.format("Vote by clicking on the corresponding number.%n%n__**%s**__%s", this.spec.getQuestion(), representation)) .setFooter(String.format("You have %s to vote. Use %spoll cancel to cancel.", FormatUtils.formatDuration(this.spec.getDuration()), this.context.getPrefix()), "https://i.imgur.com/jcrUDLY.png")); return this.voteMessage.send(embedConsumer) .flatMap(message -> Mono.delay(this.spec.getDuration(), Schedulers.boundedElastic()) .thenReturn(message.getId())) .flatMap(messageId -> this.context.getClient() .getMessageById(this.context.getChannelId(), messageId)) .onErrorResume(ClientException.isStatusCode(HttpResponseStatus.FORBIDDEN.code()), err -> Mono.empty()) .map(Message::getReactions) .flatMap(this::sendResults) .then(); }
Example #15
Source File: EventCreator.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 6 votes |
/** * Initiates the EventCreator for a specific guild. * * @param e The event received upon initialization. * @return The PreEvent for the guild. */ public PreEvent init(MessageCreateEvent e, GuildSettings settings, boolean handleMessage) { if (!hasPreEvent(settings.getGuildID())) { PreEvent event = new PreEvent(settings.getGuildID()); try { //TODO: Handle multiple calendars... String calId = DatabaseManager.getManager().getMainCalendar(settings.getGuildID()).getCalendarAddress(); event.setTimeZone(CalendarAuth.getCalendarService(settings).calendars().get(calId).execute().getTimeZone()); } catch (Exception exc) { //Failed to get timezone, ignore safely. } if (handleMessage) { if (PermissionChecker.botHasMessageManagePerms(e)) { Message message = MessageManager.sendMessageSync(MessageManager.getMessage("Creator.Event.Create.Init", settings), EventMessageFormatter.getPreEventEmbed(event, settings), e); event.setCreatorMessage(message); MessageManager.deleteMessage(e); } else { MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Notif.MANAGE_MESSAGES", settings), e); } } events.add(event); return event; } return getPreEvent(settings.getGuildID()); }
Example #16
Source File: AnnouncementCreator.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 6 votes |
/** * Initiates the creator for the guild involved. * * @param e The event received upon init. * @return A new Announcement. */ public Announcement init(MessageCreateEvent e, GuildSettings settings) { if (!hasAnnouncement(settings.getGuildID())) { Announcement a = new Announcement(settings.getGuildID()); a.setAnnouncementChannelId(e.getMessage().getChannel().block().getId().asString()); if (PermissionChecker.botHasMessageManagePerms(e)) { Message msg = MessageManager.sendMessageSync(MessageManager.getMessage("Creator.Announcement.Create.Init", settings), AnnouncementMessageFormatter.getFormatAnnouncementEmbed(a, settings), e); a.setCreatorMessage(msg); } else { MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Notif.MANAGE_MESSAGES", settings), e); } announcements.add(a); return a; } return getAnnouncement(settings.getGuildID()); }
Example #17
Source File: Translator.java From KaellyBot with GNU General Public License v3.0 | 6 votes |
/** * Génère une liste de source formatée à partir d'un salon textuel * @param channel Salon d'origine * @return Liste de message éligibles à une reconnaissance de langue */ private static List<String> getReformatedMessages(MessageChannel channel){ List<String> result = new ArrayList<>(); if (channel != null) { try { List<Message> messages = channel.getMessagesBefore(Snowflake.of(Instant.now())) .take(MAX_MESSAGES_READ).collectList().blockOptional().orElse(Collections.emptyList()); for (Message message : messages) { String content = message.getContent() .map(s -> s.replaceAll(":\\w+:", "").trim()).orElse(""); if (content.length() > MAX_CHARACTER_ACCEPTANCE) result.add(content); } } catch (Exception e){ LOG.warn("Impossible to gather data from " + channel.getId().asString()); } } return result; }
Example #18
Source File: SendNudeCommand.java From KaellyBot with GNU General Public License v3.0 | 6 votes |
@Override public void request(Message message, Matcher m, Language lg) { if (message.getChannel().blockOptional().map(chan -> chan instanceof PrivateChannel).orElse(false) || message.getChannel().blockOptional().map(chan -> ((TextChannel) chan).isNsfw()).orElse(false)){ message.getChannel().flatMap(chan -> chan.createEmbed(spec -> { spec.setTitle(Translator.getLabel(lg, "sendnude.title")) .setColor(PINK_COLOR) .setFooter(Translator.getLabel(lg, "sendnude.author") .replace("{author}", Nude.MOAM.getAuthor()) .replace("{position}", "1") .replace("{number}", "1"), null) .setImage(Nude.MOAM.getImage()); })).subscribe(); } else // Exception NSFW BasicDiscordException.NO_NSFW_CHANNEL.throwException(message, this, lg); }
Example #19
Source File: AlmanaxAutoCommand.java From KaellyBot with GNU General Public License v3.0 | 5 votes |
@Override public void request(Message message, Matcher m, Language lg) { if (isUserHasEnoughRights(message)) { String guildId = message.getGuild().blockOptional() .map(Guild::getId).map(Snowflake::asString).orElse(""); String channelId = message.getChannel().blockOptional() .map(MessageChannel::getId).map(Snowflake::asString).orElse(""); if (m.group(1).matches("\\s+true") || m.group(1).matches("\\s+0") || m.group(1).matches("\\s+on")) if (!AlmanaxCalendar.getAlmanaxCalendars().containsKey(channelId)) { new AlmanaxCalendar(guildId, channelId).addToDatabase(); message.getChannel().flatMap(chan -> chan .createMessage(Translator.getLabel(lg, "almanax-auto.request.1"))) .subscribe(); } else message.getChannel().flatMap(chan -> chan .createMessage(Translator.getLabel(lg, "almanax-auto.request.2"))) .subscribe(); else if (m.group(1).matches("\\s+false") || m.group(1).matches("\\s+1") || m.group(1).matches("\\s+off")) if (AlmanaxCalendar.getAlmanaxCalendars().containsKey(channelId)) { AlmanaxCalendar.getAlmanaxCalendars().get(channelId).removeToDatabase(); message.getChannel().flatMap(chan -> chan .createMessage(Translator.getLabel(lg, "almanax-auto.request.3"))) .subscribe(); } else message.getChannel().flatMap(chan -> chan .createMessage(Translator.getLabel(lg, "almanax-auto.request.4"))) .subscribe(); } else BasicDiscordException.NO_ENOUGH_RIGHTS.throwException(message, this, lg); }
Example #20
Source File: EventCreator.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 5 votes |
public PreEvent init(MessageCreateEvent e, GuildSettings settings, String summary, boolean handleMessage) { if (!hasPreEvent(settings.getGuildID())) { PreEvent event = new PreEvent(settings.getGuildID()); event.setSummary(summary); try { //TODO: Handle multiple calendars... String calId = DatabaseManager.getManager().getMainCalendar(settings.getGuildID()).getCalendarAddress(); event.setTimeZone(CalendarAuth.getCalendarService(settings).calendars().get(calId).execute().getTimeZone()); } catch (Exception exc) { //Failed to get timezone, ignore safely. } if (handleMessage) { if (PermissionChecker.botHasMessageManagePerms(e)) { Message message = MessageManager.sendMessageSync(MessageManager.getMessage("Creator.Event.Create.Init", settings), EventMessageFormatter.getPreEventEmbed(event, settings), e); event.setCreatorMessage(message); MessageManager.deleteMessage(e); } else { MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Notif.MANAGE_MESSAGES", settings), e); } } events.add(event); return event; } return getPreEvent(settings.getGuildID()); }
Example #21
Source File: SetCommand.java From KaellyBot with GNU General Public License v3.0 | 5 votes |
@Override public void request(Message message, Matcher m, Language lg) { if (isChannelHasExternalEmojisPermission(message)) { String normalName = Normalizer.normalize(m.group(2).trim(), Normalizer.Form.NFD) .replaceAll("\\p{InCombiningDiacriticalMarks}+", "").toLowerCase(); String editedName = removeUselessWords(lg, normalName); BestMatcher matcher = new BestMatcher(normalName); try { matcher.evaluateAll(getListRequestableFrom(getSearchURL(lg, editedName), message, notFoundSet)); if (matcher.isUnique()) { // We have found it ! Embedded set = SetDofus.getSet(lg, Translator.getLabel(lg, "game.url") + matcher.getBest().getUrl()); if (m.group(1) != null) message.getChannel().flatMap(chan -> chan .createEmbed(spec -> set.decorateMoreEmbedObject(spec, lg))) .subscribe(); else message.getChannel().flatMap(chan -> chan .createEmbed(spec -> set.decorateEmbedObject(spec, lg))) .subscribe(); } else if (!matcher.isEmpty()) // Too much sets tooMuchSets.throwException(message, this, lg, matcher.getBests()); else // empty notFoundSet.throwException(message, this, lg); } catch (IOException e) { ExceptionManager.manageIOException(e, message, this, lg, notFoundSet); } } else BasicDiscordException.NO_EXTERNAL_EMOJI_PERMISSION.throwException(message, this, lg); }
Example #22
Source File: StatCommand.java From KaellyBot with GNU General Public License v3.0 | 5 votes |
@Override public void request(Message message, Matcher m, Language lg) { if (m.group(1) == null || m.group(1).replaceAll("^\\s+", "").isEmpty()){ long totalGuild = ClientConfig.DISCORD() .flatMap(DiscordClient::getGuilds).distinct() .count().blockOptional().orElse(0L); int totalUser = ClientConfig.DISCORD() .flatMap(DiscordClient::getGuilds).distinct() .map(Guild::getMemberCount) .map(count -> count.orElse(0)) .collect(Collectors.summingInt(Integer::intValue)) .blockOptional().orElse(0); String answer = Translator.getLabel(lg, "stat.request") .replace("{guilds.size}", String.valueOf(totalGuild)) .replace("{users_max.size}", String.valueOf(totalUser)); message.getChannel().flatMap(chan -> chan.createMessage(answer)).subscribe(); } else if (m.group(1).matches("\\s+-g(\\s+\\d+)?")){ int limit = GULD_LIMIT; if (m.group(2) != null) limit = Integer.parseInt(m.group(2).trim()); StringBuilder st = new StringBuilder(); List<discord4j.core.object.entity.Guild> guilds = getBiggestGuilds(limit); int ladder = 1; for(discord4j.core.object.entity.Guild guild : guilds) st.append(ladder++).append(" : **").append(guild.getName()).append("**, ") .append(guild.getMemberCount().orElse(0)).append(" users\n"); message.getChannel().flatMap(chan -> chan.createMessage(st.toString())).subscribe(); } else if (m.group(1).matches("\\s+-hist")) message.getChannel().flatMap(chan -> chan.createMessage(spec -> decorateImageMessage(spec, getJoinTimeGuildsGraph()))) .subscribe(); }
Example #23
Source File: MessageProcessor.java From Shadbot with GNU General Public License v3.0 | 5 votes |
private static Mono<Void> processPrivateMessage(MessageCreateEvent event) { if (event.getMessage().getContent().startsWith(String.format("%shelp", Config.DEFAULT_PREFIX))) { return CommandManager.getInstance().getCommand("help") .execute(new Context(event, Config.DEFAULT_PREFIX)); } return event.getMessage() .getChannel() .filterWhen(channel -> BooleanUtils.not(channel.getMessagesBefore(Snowflake.of(Instant.now())) .take(20) .map(Message::getContent) .any(DM_TEXT::equals))) .flatMap(channel -> DiscordUtils.sendMessage(DM_TEXT, channel)) .then(); }
Example #24
Source File: ReactionListener.java From Shadbot with GNU General Public License v3.0 | 5 votes |
private static Mono<Void> execute(Message message, Member member, Action action) { return DatabaseManager.getGuilds() .getDBGuild(member.getGuildId()) .map(DBGuild::getSettings) .flatMapIterable(Settings::getIam) .filter(iam -> iam.getMessageId().equals(message.getId())) // If the bot can manage the role .filterWhen(iam -> ReactionListener.canManageRole(message, iam.getRoleId())) .flatMap(iam -> action == Action.ADD ? member.addRole(iam.getRoleId()) : member.removeRole(iam.getRoleId())) .then(); }
Example #25
Source File: EventCreator.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 5 votes |
public PreEvent init(MessageCreateEvent e, String eventId, GuildSettings settings, boolean handleMessage) { if (!hasPreEvent(settings.getGuildID())) { //TODO: Handle multiple calendars... try { String calId = DatabaseManager.getManager().getMainCalendar(settings.getGuildID()).getCalendarAddress(); Calendar service = CalendarAuth.getCalendarService(settings); Event calEvent = service.events().get(calId, eventId).execute(); PreEvent event = EventUtils.copyEvent(settings.getGuildID(), calEvent); try { event.setTimeZone(service.calendars().get(calId).execute().getTimeZone()); } catch (IOException e1) { //Failed to get tz, ignore safely. } if (handleMessage) { if (PermissionChecker.botHasMessageManagePerms(e)) { Message message = MessageManager.sendMessageSync(MessageManager.getMessage("Creator.Event.Copy.Init", settings), EventMessageFormatter.getPreEventEmbed(event, settings), e); event.setCreatorMessage(message); MessageManager.deleteMessage(e); } else { MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Notif.MANAGE_MESSAGES", settings), e); } } events.add(event); return event; } catch (Exception exc) { //Something failed... } return null; } return getPreEvent(settings.getGuildID()); }
Example #26
Source File: CalendarCommand.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 5 votes |
private void moduleCancel(MessageCreateEvent event, CalendarData calendarData, GuildSettings settings) { if (CalendarCreator.getCreator().hasPreCalendar(settings.getGuildID())) { Message message = CalendarCreator.getCreator().getPreCalendar(settings.getGuildID()).getCreatorMessage(); boolean editing = CalendarCreator.getCreator().getPreCalendar(settings.getGuildID()).isEditing(); if (CalendarCreator.getCreator().terminate(settings.getGuildID())) { if (message != null) { if (!editing) { MessageManager.deleteMessage(event); MessageManager.deleteMessage(CalendarCreator.getCreator().getCreatorMessage(settings.getGuildID())); } else { MessageManager.deleteMessage(event); MessageManager.deleteMessage(CalendarCreator.getCreator().getCreatorMessage(settings.getGuildID())); CalendarCreator.getCreator().setCreatorMessage(MessageManager.sendMessageSync(MessageManager.getMessage("Creator.Calendar.Cancel.Edit.Success", settings), event)); } } else { if (!editing) MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Calendar.Cancel.Success", settings), event); else MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Calendar.Cancel.Edit.Success", settings), event); } } else { MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Calendar.Cancel.Failure", settings), event); MessageManager.deleteMessage(event); } } else { if (calendarData.getCalendarId().equalsIgnoreCase("primary")) MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Calendar.NotInit", settings), event); else MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Calendar.HasCalendar", settings), event); } }
Example #27
Source File: RSSCommand.java From KaellyBot with GNU General Public License v3.0 | 5 votes |
@Override public void request(Message message, Matcher m, Language lg) { //On check si la personne a bien les droits pour exécuter cette commande if (isUserHasEnoughRights(message)) { String value = m.group(1); String guildId = message.getGuild().blockOptional() .map(Guild::getId).map(Snowflake::asString).orElse(""); String channelId = message.getChannel().blockOptional() .map(MessageChannel::getId).map(Snowflake::asString).orElse(""); if (value.matches("\\s+true") || value.matches("\\s+0") || value.matches("\\s+on")){ if (!RSSFinder.getRSSFinders().containsKey(channelId)) { new RSSFinder(guildId, channelId).addToDatabase(); message.getChannel().flatMap(chan -> chan .createMessage(Translator.getLabel(lg, "rss.request.1") .replace("{game.url}", Translator.getLabel(lg, "game.url")))) .subscribe(); } else rssFound.throwException(message, this, lg); } else if (value.matches("\\s+false") || value.matches("\\s+1") || value.matches("\\s+off")) if (RSSFinder.getRSSFinders().containsKey(channelId)){ RSSFinder.getRSSFinders().get(channelId).removeToDatabase(); message.getChannel().flatMap(chan -> chan .createMessage(Translator.getLabel(lg, "rss.request.2") .replace("{game.url}", Translator.getLabel(lg, "game.url")))) .subscribe(); } else rssNotFound.throwException(message, this, lg); else badUse.throwException(message, this, lg); } else BasicDiscordException.NO_ENOUGH_RIGHTS.throwException(message, this, lg); }
Example #28
Source File: NotFoundDiscordException.java From KaellyBot with GNU General Public License v3.0 | 5 votes |
@Override public void throwException(Message message, Command command, Language lg, Object... arguments) { AnkamaBug bug = null; if (command instanceof WhoisCommand) bug = AnkamaBug.CHARACTER_NOT_FOUND; else if (command instanceof GuildCommand) bug = AnkamaBug.GUILD_NOT_FOUND; else if (command instanceof AllianceCommand) bug = AnkamaBug.ALLY_NOT_FOUND; else if (command instanceof ItemCommand) if (message.getContent().map(content -> content.contains("'")).orElse(false)) bug = AnkamaBug.ITEM_NOT_FOUND_APOSTROPHE; else if (message.getContent().orElse("").toLowerCase() .contains(Translator.getLabel(lg, "equip.muldo").toLowerCase()) || message.getContent().orElse("").toLowerCase() .contains(Translator.getLabel(lg, "equip.volkorne").toLowerCase())) bug = AnkamaBug.ITEM_PAGE_MULDO_VOLKORNE_NOT_FOUND; String gender = Translator.getLabel(lg, "exception.object." + objectKey + ".gender"); String text = Translator.getLabel(lg, "exception.notfound.not." + gender) + " " + Translator.getLabel(lg, "exception.object." + objectKey + ".singular") + " " + Translator.getLabel(lg, "exception.notfound.found." + gender) + "."; if (bug != null){ final AnkamaBug BUG = bug; message.getChannel().flatMap(channel -> channel .createEmbed(spec -> BUG.decorateEmbed(spec, text, lg))) .subscribe(); } else message.getChannel().flatMap(channel -> channel .createMessage(text)) .subscribe(); }
Example #29
Source File: CalendarCommand.java From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 | 5 votes |
private void moduleCancel(MessageCreateEvent event, CalendarData calendarData, GuildSettings settings) { if (CalendarCreator.getCreator().hasPreCalendar(settings.getGuildID())) { Message message = CalendarCreator.getCreator().getPreCalendar(settings.getGuildID()).getCreatorMessage(); boolean editing = CalendarCreator.getCreator().getPreCalendar(settings.getGuildID()).isEditing(); if (CalendarCreator.getCreator().terminate(settings.getGuildID())) { if (message != null) { if (!editing) { MessageManager.deleteMessage(event); MessageManager.deleteMessage(CalendarCreator.getCreator().getCreatorMessage(settings.getGuildID())); } else { MessageManager.deleteMessage(event); MessageManager.deleteMessage(CalendarCreator.getCreator().getCreatorMessage(settings.getGuildID())); CalendarCreator.getCreator().setCreatorMessage(MessageManager.sendMessageSync(MessageManager.getMessage("Creator.Calendar.Cancel.Edit.Success", settings), event)); } } else { if (!editing) MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Calendar.Cancel.Success", settings), event); else MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Calendar.Cancel.Edit.Success", settings), event); } } else { MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Calendar.Cancel.Failure", settings), event); MessageManager.deleteMessage(event); } } else { if (calendarData.getCalendarId().equalsIgnoreCase("primary")) MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Calendar.NotInit", settings), event); else MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Calendar.HasCalendar", settings), event); } }
Example #30
Source File: MemberJoinListener.java From Shadbot with GNU General Public License v3.0 | 5 votes |
@Override public Mono<Void> execute(MemberJoinEvent event) { // Send an automatic join message if one was configured final Mono<Message> sendWelcomeMessage = DatabaseManager.getGuilds() .getDBGuild(event.getGuildId()) .map(DBGuild::getSettings) .flatMap(settings -> Mono.zip( Mono.justOrEmpty(settings.getMessageChannelId()), Mono.justOrEmpty(settings.getJoinMessage()))) .flatMap(TupleUtils.function((messageChannelId, joinMessage) -> MemberJoinListener.sendAutoMessage(event.getClient(), event.getMember(), messageChannelId, joinMessage))); // Add auto-roles when a user joins if they are configured final Flux<Void> addAutoRoles = event.getGuild() .flatMap(Guild::getSelfMember) .flatMapMany(self -> self.getBasePermissions() .filter(permissions -> permissions.contains(Permission.MANAGE_ROLES)) .flatMap(ignored -> DatabaseManager.getGuilds() .getDBGuild(event.getGuildId()) .map(DBGuild::getSettings)) .flatMapMany(settings -> Flux.fromIterable(settings.getAutoRoleIds()) .flatMap(roleId -> event.getClient().getRoleById(event.getGuildId(), roleId)) .filterWhen(role -> self.hasHigherRoles(Set.of(role.getId()))) .flatMap(role -> event.getMember().addRole(role.getId())))); return sendWelcomeMessage.and(addAutoRoles); }