Java 类net.dv8tion.jda.core.entities.TextChannel 实例源码

项目:Charrizard    文件:DiscordCommand.java   
private void checkIcons(CMessage message, String[] args) {
    TextChannel channel = message.getChannel();
    if (args.length != 3) {
        sendUsage(message, "!discord icons <guild id|this>");
        return;
    }
    String guild = args[2];
    Guild targetGuild = null;
    if (guild.equals("this")) {
        targetGuild = message.getGuild();
    } else {
        targetGuild = this.charrizard.getDiscordAPI().getGuildById(args[2]);
    }
    if (targetGuild == null) {
        sendError(message, "This guild does not exists!");
        return;
    }
    if (targetGuild.getEmotes().size() == 0) {
        sendError(message, "This server does not have any own icons!");
        return;
    }
    channel.sendMessage("**Icons**:").queue();
    targetGuild.getEmotes().forEach(icon -> channel.sendMessage(icon.getAsMention() + " - " + icon.getImageUrl()).queue());
}
项目:Charrizard    文件:CGuildManager.java   
public void createGuild(Guild guild) {
    if (guild == null) {
        return;
    }
    if (getGuild(guild) != null) {
        return;
    }
    CGuild cGuild = new CGuild(guild, charrizard);
    for (TextChannel channel : guild.getTextChannels()) {
        cGuild.createTextChannel(channel);
    }
    for (VoiceChannel voiceChannel : guild.getVoiceChannels()) {
        cGuild.createVoiceChannel(voiceChannel);
    }
    guildCache.put(guild.getId(), cGuild);
}
项目:GabrielBot    文件:Trivia.java   
public Trivia(TextChannel channel, TLongSet players, OpenTriviaDatabase.Question question) {
    super(channel, players, question.correctAnswer, (question.incorrectAnswers.size() + 1) / 2);

    List<String> options = new ArrayList<>(question.incorrectAnswers);
    options.add(question.correctAnswer);

    int triesLeft = options.size()/2;

    totalOptions = options.size();
    correctOptionIndex = options.indexOf(question.correctAnswer);

    Collections.shuffle(options);

    int[] idx = {1};
    channel.sendMessage(new EmbedBuilder()
            .setDescription("**" + question.question + "**")
            .addField("Options", options.stream().map(o->idx[0]++ + " - " + o).collect(Collectors.joining("**\n**", "**", "**")), false)
            .addField("Difficulty", question.difficulty, true)
            .addField("Category", question.category, true)
            .setFooter(triesLeft + " tries left | Answer with the option number", null)
            .build()
    ).queue();
}
项目:GabrielBot    文件:ImageCommands.java   
@Command(
        name = "doge",
        description = "Sends doge images with custom texts",
        usage = "`>>doge wow \"such doge\"`",
        permission = CommandPermission.USER,
        category = CommandCategory.IMAGE
)
public static void doge(@Argument("event") GuildMessageReceivedEvent event, @Argument("args") String[] args, @Argument("channel") TextChannel channel) {
    checkVerification(event);
    String url = "http://dogr.io/" + String.join("/", args).replace("\n", "%20").replace(" ", "%20") + ".png?split=false";
    channel.sendMessage(new EmbedBuilder()
            .setColor(Color.YELLOW)
            .setTitle("Doge", "http://dogr.io")
            .setImage(url)
            .build()).queue();
}
项目:GabrielBot    文件:GameCommands.java   
@Command(
        name = "pokemonguess",
        description = "Guess which pokemon it is",
        usage = "`>>pokemonguess`: Play pokemon guess solo\n" +
                "`>>pokemonguess @Someone @SomeoneElse ...`: Play pokemon guess with your friends (if you have any)",
        permission = CommandPermission.USER,
        category = CommandCategory.GAME
)
public static void pokemonguess(@Argument("channel") TextChannel channel, @Argument("author") User author, @Argument("message") Message message) {
    if(check(channel)) return;
    TLongSet players = new TLongHashSet();
    players.add(author.getIdLong());
    for(User u : message.getMentionedUsers()) players.add(u.getIdLong());
    EventManagerThread.current().newThread(()->{
        try {
            Thread.sleep(100);
        } catch(InterruptedException e) {
            return;
        }
        InteractiveOperations.create(channel.getIdLong(), 120, new Pokemon(channel, players));
    }, "Game Starter").start();
}
项目:Supreme-Bot    文件:ArgumentList.java   
public final TextChannel getTextChannel(int index, boolean consume) {
    if (guild == null) {
        return null;
    }
    final String temp = getRaw(index);
    if (temp == null) {
        return null;
    }
    final Matcher matcher = PATTERN_MARKDOWN_CHANNEL.matcher(temp);
    if (!matcher.matches()) {
        return null;
    }
    if (consume) {
        consumeRaw(index);
    }
    return guild.getTextChannelById(matcher.group(1));
}
项目:GabrielBot    文件:TrackScheduler.java   
public void voteskip(long userId) {
    TextChannel tc = guildMusicPlayer.textChannel;
    int votes = getRequiredVotes(guildMusicPlayer.voiceChannel);
    if(voteskips.contains(userId)) {
        voteskips.remove(userId);
        tc.sendMessage("Your vote has been removed! " + (votes-voteskips.size()) + " more to skip").queue();
    } else {
        voteskips.add(userId);
        if(voteskips.size() >= votes) {
            tc.sendMessage("Reached required number of votes, skipping song").queue();
            nextTrack();
        } else {
            tc.sendMessage("Your vote has been added! " + (votes-voteskips.size()) + " more to skip").queue();
        }
    }
}
项目:Endless    文件:ServerSettings.java   
@Override
protected void execute(CommandEvent event)
{
    if(event.getArgs().isEmpty())
        event.replyError("Please include a text channel or NONE");
    else if(event.getArgs().equalsIgnoreCase("none"))
    {
        db.setLeaveChannel(event.getGuild(), null);
        event.replySuccess("Leave channel disabled");
    }
    else
    {
        List<TextChannel> list = FinderUtil.findTextChannels(event.getArgs(), event.getGuild());
        if(list.isEmpty())
            event.replyWarning("No Text Channels found matching \""+event.getArgs()+"\"");
        else if (list.size()>1)
            event.replyWarning(FormatUtil.listOfTcChannels(list, event.getArgs()));
        else
        {
            db.setLeaveChannel(event.getGuild(), list.get(0));
            event.replySuccess("The message configured will be sent in "+list.get(0).getAsMention());
        }
    }
}
项目:Endless    文件:GuildSettingsDataManager.java   
public TextChannel getModlogChannel(Guild guild)
{
    try
    {
        Statement statement = connection.createStatement();
        statement.closeOnCompletion();
        TextChannel tc;
        try (ResultSet results = statement.executeQuery(String.format("SELECT modlog_id FROM GUILD_SETTINGS WHERE GUILD_ID = %s", guild.getId())))
        {
            if(results.next())
                tc = guild.getTextChannelById(Long.toString(results.getLong("modlog_id")));
            else tc=null;
        }
        return tc;
    }
    catch(SQLException e)
    {
        LOG.warn(e.toString());
        return null;
    }
}
项目:Endless    文件:GuildSettingsDataManager.java   
public TextChannel getServerlogChannel(Guild guild)
{
    try
    {
        Statement statement = connection.createStatement();
        statement.closeOnCompletion();
        TextChannel tc;
        try (ResultSet results = statement.executeQuery(String.format("SELECT serverlog_id FROM GUILD_SETTINGS WHERE GUILD_ID = %s", guild.getId())))
        {
            if(results.next())
                tc = guild.getTextChannelById(Long.toString(results.getLong("serverlog_id")));
            else tc=null;
        }
        return tc;
    }
    catch(SQLException e)
    {
        LOG.warn(e.toString());
        return null;
    }
}
项目:quorrabot    文件:DiscordAPI.java   
public void sendMessage(String channel, String message) {
    TextChannel textChannel = resolveChannel(channel);

    if (textChannel != null) {
        try {
            com.gmt2001.Console.out.println("[DISCORD] [#" + textChannel.getName() + "] [CHAT] " + message);
            textChannel.sendMessage(message).queue();
        } catch (NullPointerException ex) {
            com.gmt2001.Console.err.println("Failed to send a message to Discord [" + ex.getClass().getSimpleName() + "]: " + ex.getMessage());
            channelMap.clear();
            userMap.clear();
            roleMap.clear();
            users.clear();
            botId = jdaAPI.getSelfUser().getId();
            getTextChannels();
            getUserNames();
            getRoles();

            textChannel = resolveChannel(channel);
            if (textChannel != null) {
                textChannel.sendMessage(message).queue();
            }
        }
    }
}
项目:Rubicon    文件:CommandBlacklist.java   
private void blockChannel(CommandManager.ParsedCommandInvocation parsedCommandInvocation) {
    Message message = parsedCommandInvocation.getMessage();
    if (message.getMentionedChannels().isEmpty()) {
        message.getTextChannel().sendMessage(EmbedUtil.error("Unknown channel", "Please mention the textchannel that should be blacklisted").build()).queue(msg -> msg.delete().queueAfter(5, TimeUnit.SECONDS));
        return;
    }
    TextChannel channel = message.getMentionedChannels().get(0);
    if (RubiconBot.getMySQL().isBlacklisted(channel)) {
        message.getTextChannel().sendMessage(EmbedUtil.error("Blacklisted channel", "That channel is already blacklisted").build()).queue(msg -> msg.delete().queueAfter(5, TimeUnit.SECONDS));
        return;
    }
    String oldEntry = RubiconBot.getMySQL().getGuildValue(message.getGuild(), "blacklist");
    String newEntry;
    if (oldEntry.equals(""))
        newEntry = channel.getId();
    else
        newEntry = oldEntry + "," + channel.getId();
    RubiconBot.getMySQL().updateGuildValue(message.getGuild(), "blacklist", newEntry);
    message.getTextChannel().sendMessage(EmbedUtil.success("Blacklisted channel!", "Successfully added channel to blacklist").build()).queue(msg -> msg.delete().queueAfter(5, TimeUnit.SECONDS));
}
项目:Minecordbot    文件:TextChannelCmd.java   
private void addTextChannel(CommandEvent e) {
    String arg = e.getArgs();
    java.util.List<TextChannel> tcArray = mcb.getRelayChannels();
    String response;
    boolean withID = StringUtils.isNumeric(arg) && e.getJDA().getTextChannelById(arg) != null;
    TextChannel tc;
    if (withID) {
        tc = e.getJDA().getTextChannelById(arg);
    } else {
        java.util.List<TextChannel> result = FinderUtil.findTextChannel(arg, e.getGuild());
        tc = result.size() > 0 ? result.get(0) : null;
    }
    if (tc != null) {
        tcArray.add(tc);
        configsManager.getChatConfig().set("Relay_Channels", asStringList(tcArray));
        configsManager.getChatConfig().saveConfig();
    } else {
        response = Locale.getCommandsMessage("textchannel.invalid-tc").finish();
        respond(e, String.format(response, arg), ResponseLevel.LEVEL_3);
        return;
    }
    response = Locale.getCommandsMessage("textchannel.added-tc").finish();
    respond(e, String.format(response, arg), ResponseLevel.LEVEL_1);
    Logger.info("Added text channel " + arg);
}
项目:Rubicon    文件:CommandMute.java   
@Override
protected Message execute(CommandManager.ParsedCommandInvocation parsedCommandInvocation, UserPermissions userPermissions) {
    Message message = parsedCommandInvocation.getMessage();
    if (message.getMentionedUsers().isEmpty())
        return new MessageBuilder().setEmbed(EmbedUtil.info("Usage", "mute <@User>").build()).build();
    Member target = message.getGuild().getMember(message.getMentionedUsers().get(0));
    if (!message.getGuild().getSelfMember().canInteract(target))
        return new MessageBuilder().setEmbed(EmbedUtil.error("No permission", "Sorry i can't mute this user! His/her role is higher than yours.").build()).build();

    TextChannel channel = message.getTextChannel();
    if (channel.getPermissionOverride(target) == null)
        channel.createPermissionOverride(target).complete();
    if (channel.getPermissionOverride(target).getDenied().contains(Permission.MESSAGE_WRITE))
        return new MessageBuilder().setEmbed(EmbedUtil.error("Already muted", "This user is already muted.").build()).build();
    message.getGuild().getTextChannels().forEach(c -> {
        if (c.getPermissionOverride(target) == null)
            c.createPermissionOverride(target).complete();
        c.getPermissionOverride(target).getManager().deny(Permission.MESSAGE_WRITE).queue();
    });
    PrivateChannel targetch = target.getUser().openPrivateChannel().complete();
    targetch.sendMessage(EmbedUtil.info("Muted", "You got muted on `" + message.getGuild().getName() + "` by " + message.getAuthor().getAsMention()).build()).queue();
    return new MessageBuilder().setEmbed(EmbedUtil.success("Muted", "Successfully muted " + target.getAsMention()).build()).build();
}
项目:Rubicon    文件:UserJoinListener.java   
public void onGuildMemberJoin(GuildMemberJoinEvent e) {
    if (!RubiconBot.getMySQL().ifUserExist(e.getUser())) {
        RubiconBot.getMySQL().createUser(e.getUser());
    }
    try {
        String joinMessage = RubiconBot.getMySQL().getGuildValue(e.getGuild(), "joinmsg");
        if (joinMessage.equals("0")) {
            return;
        } else {
            TextChannel messageChannel = e.getJDA().getTextChannelById(RubiconBot.getMySQL().getGuildValue(e.getGuild(), "channel"));
            if (messageChannel == null)
                return;
            joinMessage = joinMessage.replace("%user%", e.getMember().getAsMention());
            joinMessage = joinMessage.replace("%guild%", e.getGuild().getName());
            messageChannel.sendMessage(joinMessage).queue();
        }
    } catch (NullPointerException ex) {
        //Channel does not exits
    }
}
项目:Rubicon    文件:ChannelDeleteListener.java   
@Override
public void onTextChannelDelete(TextChannelDeleteEvent e) {
    String portalStatus = RubiconBot.getMySQL().getGuildValue(e.getGuild(), "portal");
    if(portalStatus.equalsIgnoreCase("closed") || portalStatus.equalsIgnoreCase("waiting"))
        return;
    if(portalStatus.equalsIgnoreCase("open")) {
        TextChannel channel = e.getJDA().getTextChannelById(RubiconBot.getMySQL().getPortalValue(e.getGuild(), "channelid"));
        if(e.getChannel().getId() != channel.getId())
            return;

        Guild partnerGuild = e.getJDA().getGuildById(RubiconBot.getMySQL().getPortalValue(e.getGuild(), "partnerid"));
        RubiconBot.getMySQL().deletePortal(e.getGuild());
        RubiconBot.getMySQL().deletePortal(partnerGuild);
        RubiconBot.getMySQL().updateGuildValue(e.getGuild(), "portal", "closed");
        RubiconBot.getMySQL().updateGuildValue(partnerGuild, "portal", "closed");

        sendPortalNotification(e.getGuild(), "Portal was closed.");
        sendPortalNotification(partnerGuild, "Portal was closed on the other side.");
    }
}
项目:Rubicon    文件:ServerLogHandler.java   
@Override
public void onGuildMemberLeave(GuildMemberLeaveEvent event) {
    if (bannedUsers.contains(event.getUser().getIdLong())) {
        return;
    }
    if (!isEventEnabled(event.getGuild(), LogEventKeys.BAN))
        return;
    TextChannel textChannel = getLogChannel(event.getGuild());
    if (textChannel == null)
        return;

    EmbedBuilder embedBuilder = new EmbedBuilder();
    embedBuilder.setAuthor("A member left the server", null, event.getMember().getUser().getAvatarUrl());
    embedBuilder.setDescription("**" + event.getMember().getEffectiveName() + " (" + event.getMember().getUser().getId() + ")** left the server");
    embedBuilder.setColor(evLeaveColor);
    sendLog(textChannel, embedBuilder);
}
项目:BeamTeamDiscordBot    文件:LogSet.java   
@Override
protected void execute(CommandEvent event) {
    if (!StringUtils.isBlank(event.getArgs())) {
        String arg = event.getArgs().trim();

        List<TextChannel> textChannels = event.getJDA().getTextChannelsByName(arg, true);

        if (!textChannels.isEmpty()) {
            BTBGuild guild = GuildManager.getGuild(event.getGuild());

            guild.setLogChannelID(textChannels.get(0).getId());

            JDAManager.sendMessage(event, "Log channel has been set to %s.", arg);
        } else {
            JDAManager.sendMessage(event,
                    "I can't find the channel named %s. Please ensure it exists and that I have read & write priveleges for it.",
                    arg);
        }
    } else {
        JDAManager.sendMessage(event, "Missing arguments from command!");
    }
}
项目:GensokyoBot    文件:ReviveCommand.java   
@Override
public void onInvoke(Guild guild, TextChannel channel, Member invoker, Message message, String[] args) {
    int shardId = Integer.parseInt(args[1]);

    channel.sendMessage(TextUtils.prefaceWithName(invoker, " Reviving shard " + shardId)).queue();
    FredBoat.getInstance(shardId).revive();
}
项目:GabrielBot    文件:OwnerCommands.java   
@Command(
        name = "shutdown",
        description = "Makes me go offline :(",
        usage = "`>>shutdown`\n" +
                "`>>shutdown savemusic`",
        permission = CommandPermission.OWNER,
        category = CommandCategory.OWNER
)
public static void shutdown(@Argument("channel") TextChannel channel, @Argument("args") String[] args) {
    if (args.length > 0 && args[0].equals("savemusic")) {
        GabrielBot.getInstance().registry.commands().remove("play");
        JedisDataManager jdm = GabrielData.guilds();
        int[] i = new int[1];
        GabrielBot.getInstance().getPlayers().forEachValue(p->{
            if(p == null) return true;
            if(p.scheduler.currentTrack() == null) {
                p.leave();
                return true;
            }
            p.player.setPaused(true);
            List<Track> allTracks = new ArrayList<>();
            allTracks.add(p.scheduler.currentTrack());
            allTracks.addAll(p.scheduler.tracks());
            p.leave();
            if(p.textChannel.canTalk()) {
                p.textChannel.sendMessage("I'll be rebooting soon, but your queue has been saved and will be restored after I reboot").queue();
            }
            SerializedPlayer sp = new SerializedPlayer(allTracks.stream().map(SerializedTrack::new).collect(Collectors.toList()), allTracks.get(0).track.getPosition(), p.guildId, p.textChannel.getIdLong(), p.voiceChannel.getIdLong());
            jdm.set("p_" + p.guildId, Base64.getEncoder().encodeToString(KryoUtils.serialize(sp)));
            i[0]++;
            return true;
        });
        jdm.save();
        GabrielBot.LOGGER.info("Serialized tracks for {} guilds", i[0]);
    }
    GabrielData.save();
    channel.sendMessage("*Goes to sleep...*").complete();
    Arrays.stream(GabrielBot.getInstance().getShards()).forEach(s -> s.getJDA().shutdown());
    System.exit(0);
}
项目:TransparentDiscord    文件:UITextChat.java   
/**
 * Constructs a text channel from the given parameter
 * @param textChannel the text channel to construct this UI around
 */
public UITextChat(TextChannel textChannel) {
    super();
    this.channel = textChannel;
    this.messageHistory = textChannel.getHistory();

    //Set up gridbag to add new messages
    c = new GridBagConstraints();
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.weightx = 1;
    c.fill = GridBagConstraints.HORIZONTAL;

    //Get some message history and add it to the message list
    //Message history in order from newest to oldest
    messageHistory.retrievePast(20).queue(messages -> {
        newestGroup = oldestGroup = new UIMessageGroup(messages.get(0));
        messageList.add(oldestGroup,c,0);

        //Going from newest to oldest...
        for (int i = 1; i < messages.size(); i++) {
            if (oldestGroup.canAddMessage(messages.get(i))) {
                oldestGroup.addMessage(messages.get(i));
            }
            else {
                oldestGroup = new UIMessageGroup(messages.get(i));
                messageList.add(oldestGroup,c,0);
            }
        }

        refresh();
        scrollToBottom();
        doneLoad = true;
    });

    add(new UITitleBar("<html>" +
            textChannel.getGuild().getName() + "<br>#" +
            channel.getName() + "</html>", TransparentDiscord.chatWindow), BorderLayout.NORTH);

}
项目:TransparentDiscord    文件:UIChannelList.java   
/**
 * Add a list of TextChannels to the UI
 * @param channels the TextChannels to add
 */
public void addTextChannels(List<TextChannel> channels) {
    for (UIChannelListItem item : UIChannelListItem.loadTextChannels(channels)) {
        channelList.add(item, c, channelList.getComponentCount());
        channelItems.put(item.getID(), item);
    }
}
项目:TransparentDiscord    文件:UIChannelList.java   
public void update(Message message) {
    if (!(message.getChannel() instanceof TextChannel)) {
        UIChannelListItem item = channelItems.get(message.getChannel().getId());
        channelList.remove(item);
        channelList.add(item,c,0);
        item.updatePreview(message);
        refresh();
    }
}
项目:SafetyJim    文件:MessageStats.java   
@Override
public boolean onMessage(DiscordBot bot, DiscordShard shard, GuildMessageReceivedEvent event) {
    shard.getThreadPool().submit(() -> {
        DSLContext database = bot.getDatabase();

        Guild guild = event.getGuild();
        SettingsRecord guildSettings = DatabaseUtils.getGuildSettings(database, guild);
        if (!guildSettings.getStatistics()) {
            return;
        }

        Message message = event.getMessage();
        TextChannel channel = event.getChannel();
        String content = message.getRawContent();
        User user = event.getMember().getUser();
        int wordCount = content.split(" ").length;
        MessagesRecord record = database.newRecord(Tables.MESSAGES);

        record.setMessageid(message.getId());
        record.setUserid(user.getId());
        record.setChannelid(channel.getId());
        record.setGuildid(guild.getId());
        record.setDate(DiscordUtils.getCreationTime(message.getId()));
        record.setWordcount(wordCount);
        record.setSize(content.length());
        record.store();
    });

    return false;
}
项目:DiscordIntegrationCore    文件:Message.java   
WebhookMessage toWebhook(TextChannel channel) {
    return new WebhookMessage(
        formatText(message.webhook, channel),
        this.author,
        this.avatarUrl
    );
}
项目:GabrielBot    文件:OwnerCommands.java   
@Command(
        name = "save",
        description = "Flushes data to db",
        usage = "`>>save`",
        permission = CommandPermission.OWNER,
        category = CommandCategory.OWNER
)
public static void save(@Argument("channel") TextChannel channel) {
    GabrielData.save();
    channel.sendMessage("Successfully saved").queue();
}
项目:avaire    文件:ChannelIdCommand.java   
@Override
public boolean onCommand(Message message, String[] args) {
    TextChannel channel = message.getTextChannel();
    if (!message.getMentionedChannels().isEmpty()) {
        channel = message.getMentionedChannels().get(0);
    }

    MessageFactory.makeSuccess(message, ":user :id: of the :channel channel is `:targetChannel`")
        .set("targetChannel", channel.getId()).queue();
    return true;
}
项目:GensokyoBot    文件:LeaveCommand.java   
@Override
public void onInvoke(Guild guild, TextChannel channel, Member invoker, Message message, String[] args) {
    try {
        GuildPlayer player = PlayerRegistry.get(guild);
        player.setCurrentTC(channel);
        player.leaveVoiceChannelRequest(channel, false);
    } catch (Exception e) {
        log.error("Something caused us to not properly leave a voice channel!", e);
        guild.getAudioManager().closeAudioConnection();
    }
}
项目:NapBot    文件:CommandSay.java   
@Override
public boolean execute(User user, TextChannel channel, String command, List<String> parameters, Message message) throws Exception
{
    if (parameters.isEmpty())
        return false;
    message.delete().queue();
    channel.sendMessage(StringUtils.join(parameters, " ")).complete();
    return true;
}
项目:GiveawayBot    文件:CreateCommand.java   
private void waitForWinners(CommandEvent event, TextChannel tchan, int seconds)
{
    waiter.waitForEvent(GuildMessageReceivedEvent.class, 
            e -> e.getAuthor().equals(event.getAuthor()) && e.getChannel().equals(event.getChannel()), 
            e -> {
                if(e.getMessage().getRawContent().equalsIgnoreCase("cancel"))
                {
                    event.replyWarning("Alright, I guess we're not having a giveaway after all..."+CANCEL);
                }
                else
                {
                    try {
                        int num = Integer.parseInt(e.getMessage().getRawContent().trim());
                        if(num<1 || num>15)
                        {
                            event.replyWarning("Hey! I can only support 1 to 15 winners!"+WINNERS);
                            waitForWinners(event, tchan, seconds);
                        }
                        else
                        {
                            event.replySuccess("Ok! "+num+" winners it is! Finally, what do you want to give away?"+PRIZE);
                            waitForPrize(event, tchan, seconds, num);
                        }
                    } catch(NumberFormatException ex) {
                        event.replyWarning("Uh... that doesn't look like a valid number."+WINNERS);
                        waitForWinners(event, tchan, seconds);
                    }
                }
            }, 
            2, TimeUnit.MINUTES, () -> event.replyWarning("Uh oh! You took longer than 2 minutes to respond, "+event.getAuthor().getAsMention()+"!"+CANCEL));
}
项目:GiveawayBot    文件:CreateCommand.java   
private void waitForPrize(CommandEvent event, TextChannel tchan, int seconds, int winners)
{
    waiter.waitForEvent(GuildMessageReceivedEvent.class, 
            e -> e.getAuthor().equals(event.getAuthor()) && e.getChannel().equals(event.getChannel()), 
            e -> {
                if(e.getMessage().getRawContent().equalsIgnoreCase("cancel"))
                {
                    event.replyWarning("Alright, I guess we're not having a giveaway after all..."+CANCEL);
                }
                else
                {
                    String prize = e.getMessage().getRawContent();
                    if(prize.length()>250)
                    {
                        event.replyWarning("Ack! That prize is too long. Can you shorten it a bit?"+PRIZE);
                        waitForPrize(event, tchan, seconds, winners);
                    }
                    else
                    {
                        Instant now = Instant.now();
                        if(bot.startGiveaway(tchan, now, seconds, winners, prize))
                        {
                            event.replySuccess("Done! The giveaway for the `"+e.getMessage().getRawContent()+"` is starting in "+tchan.getAsMention()+"!");
                        }
                        else
                        {
                            event.replyError("Uh oh. Something went wrong and I wasn't able to start the giveaway."+CANCEL);
                        }
                    }
                }
            }, 
            2, TimeUnit.MINUTES, () -> event.replyWarning("Uh oh! You took longer than 2 minutes to respond, "+event.getAuthor().getAsMention()+"!"+CANCEL));
}
项目:GiveawayBot    文件:GiveawayManager.java   
public List<Giveaway> getGiveaways(TextChannel channel)
{
    List<Giveaway> list = new LinkedList<>();
    try (Statement statement = getConnection().createStatement();
         ResultSet results = statement.executeQuery(selectAll(CHANNEL_ID.is(channel.getIdLong()))))
    {
        while(results.next())
            list.add(new Giveaway(MESSAGE_ID.getValue(results), CHANNEL_ID.getValue(results), GUILD_ID.getValue(results), 
                    END_TIME.getValue(results), NUM_WINNERS.getValue(results), PRIZE.getValue(results)));
    } catch( SQLException e) {
        e.printStackTrace();
    }
    return list;
}
项目:BullyBot    文件:Queue.java   
/**
 * Creates a new game.
 * Removes players in-game from other queues.
 * Sends notification to the pug channel and to each player in queue.
 */
private void popQueue() {
    String names = "";
    List<User> players = new ArrayList<User>(playersInQueue);
    TextChannel pugChannel = ServerManager.getServer(guildId).getPugChannel();

    // Send alert to players and compile their names
    for(User u : players){
        names += u.getName() + ", ";
        PrivateChannel c = u.openPrivateChannel().complete();
        c.sendMessage(String.format("`Your game: %s has started!`", name)).queue();
    }
    names = names.substring(0, names.lastIndexOf(","));

    // Create Game and add to the list of active games
    Game newGame = new Game(guildId, name, players);
    games.add(newGame);

    // Remove players from all other queues
    ServerManager.getServer(guildId).getQueueManager().purgeQueue(players);

    // Generate captain string
    String captainString = "";
    if(ServerManager.getServer(guildId).getSettings().randomizeCaptains()){
        captainString = String.format("**Captains:** <@%s> & <@%s>", newGame.getCaptains()[0].getId(), newGame.getCaptains()[1].getId());
    }

    // Send game start message to pug channel
    pugChannel.sendMessage(Utils.createMessage(String.format("Game: %s starting%n", name), String.format("%s%n%s", names, captainString), Color.YELLOW)).queueAfter(2, TimeUnit.SECONDS);

    /*String servers = new CmdPugServers().getServers(guildId, null);
    if(!servers.equals("N/A")){
        pugChannel.sendMessage(Utils.createMessage("`Pug servers:`", servers, true)).queueAfter(2, TimeUnit.SECONDS);
    }*/
}
项目:Minecordbot    文件:TextChannelCmd.java   
private java.util.List<String> asStringList(java.util.List<TextChannel> tcs) {
    java.util.List<String> strs = new ArrayList<>();
    for(TextChannel c : tcs) {
        strs.add(c.getId());
    }
    return strs;
}
项目:GabrielBot    文件:MusicCommands.java   
@Command(
        name = "volume",
        description = "Changes volume for this server",
        usage = "`>>volume <new volume>`: Changes the volume\n" +
                "`>>volume 100`: Resets the volume",
        permission = CommandPermission.PREMIUM,
        category = CommandCategory.MUSIC
)
public static void volume(@Argument("this") CommandReference thiz, @Argument("event")GuildMessageReceivedEvent event, @Argument("args") String[] args, @Argument("channel") TextChannel channel, @Argument("guild") Guild guild) {
    if(checkVC(event)) return;
    if(args.length == 0) {
        thiz.onHelp(event);
        return;
    }
    int i;
    try {
        i = Integer.parseInt(args[0]);
    } catch(NumberFormatException e) {
        channel.sendMessage(args[0] + " is not a valid integer").queue();
        return;
    }
    if(i < 0) {
        i = 100;
    } else if (i > 150) {
        i = 150;
    }
    GuildMusicPlayer gmp = GabrielBot.getInstance().getPlayer(guild.getIdLong());
    if(gmp == null) {
        channel.sendMessage("I'm not playing any music").queue();
        return;
    }
    gmp.player.setVolume(i);
    channel.sendMessage("Volume set to " + i).queue();
}
项目:legendarybot    文件:MusicManager.java   
/**
 * Load a song
 * @param channel The channel to send the alert in.
 * @param trackUrl The song URL
 * @param voiceChannel the voice channel to play the music in.
 */
public void loadAndPlay(final TextChannel channel, final String trackUrl, VoiceChannel voiceChannel) {
    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, voiceChannel);
        }

        @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, voiceChannel);
        }

        @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();
        }
    });
}
项目:quorrabot    文件:DiscordAPI.java   
private void getUserNames() {
    for (TextChannel channel : channelMap.values()) {
        for (Member member : channel.getMembers()) {
            addUserToMap(member);
        } 
    }
}
项目:Minecord    文件:DiscordUtils.java   
public static List<TextChannel> getTextChannels() {
    Set<TextChannel> channels = new LinkedHashSet<TextChannel>();
    for (JDA jda : Bot.shards) {
        channels.addAll(jda.getTextChannels());
    }
    return new ArrayList<TextChannel>(channels);
}
项目:NapBot    文件:CommandToggleWatchGroup.java   
@Override
public boolean execute(User user, TextChannel channel, String command, List<String> parameters, Message message) throws Exception
{
    Member member = channel.getGuild().getMember(user);
    NapSchedule schedule = CommonPolyStuff.determineScheduleFromMemberName(member.getEffectiveName());
    List<Role> nmoRole = channel.getGuild().getRolesByName("NMO Watch Group", true);
    boolean inWatchGroup = false;
    for (Role role : member.getRoles())
    {
        if (nmoRole.contains(role))
        {
            inWatchGroup = true;
            break;
        }
    }
    if (inWatchGroup)
    {
        channel.getGuild().getController().removeRolesFromMember(member, nmoRole).complete();
        channel.sendMessage(member.getAsMention() + " You have been removed from the NMO Watch Group.").complete();
    }
    else if (schedule == null)
    {
        channel.sendMessage(member.getAsMention() + " You must set a sleep schedule before you can join the NMO Watch Group").complete();
    }
    else
    {
        channel.getGuild().getController().addRolesToMember(member, nmoRole).complete();
        channel.sendMessage(member.getAsMention() + " You have been added to the NMO Watch Group.").complete();
    }
    return true;
}
项目:momo-2    文件:Bot.java   
/**
 * Get a text channel from an ID from all shards
 * @param channelId Channel ID
 * @return TextChannel if found, null if not
 */
public TextChannel getTextChannelById(long channelId) {
    for (JDA j : jdaClients) {
        TextChannel t;
        if ((t = j.getTextChannelById(channelId)) != null) {
            return t;
        }
    }
    return null;
}