當前位置: 首頁>>代碼示例>>Java>>正文


Java MessageReceivedEvent.getAuthor方法代碼示例

本文整理匯總了Java中net.dv8tion.jda.core.events.message.MessageReceivedEvent.getAuthor方法的典型用法代碼示例。如果您正苦於以下問題:Java MessageReceivedEvent.getAuthor方法的具體用法?Java MessageReceivedEvent.getAuthor怎麽用?Java MessageReceivedEvent.getAuthor使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在net.dv8tion.jda.core.events.message.MessageReceivedEvent的用法示例。


在下文中一共展示了MessageReceivedEvent.getAuthor方法的13個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: handleMessages

import net.dv8tion.jda.core.events.message.MessageReceivedEvent; //導入方法依賴的package包/類
private void handleMessages(MessageReceivedEvent event) {
    String channelName = event.getChannel().getName();
    String username = event.getAuthor().getName();
    String message = event.getMessage().getContent();
    String messageId = event.getMessage().getId();
    Channel channel = event.getTextChannel();
    User sender = event.getAuthor();
    Boolean isAdmin = PermissionUtil.checkPermission(channel, event.getMember(), Permission.ADMINISTRATOR);

    com.gmt2001.Console.out.println("[DISCORD] [#" + channelName + "] " + username.toLowerCase() + ": " + message);

    // Be sure that this is commented out before a release back into the master branch!  
    /*
    if (message.equals("!testjoin") && isAdmin) { 
        EventBus.instance().post(new DiscordJoinEvent(event.getMember()));
    }
    */

    if (message.startsWith("!")) {
        commandEvent(sender, channel, message, isAdmin);
    }

    EventBus.instance().postAsync(new DiscordMessageEvent(sender, channel, message, messageId, isAdmin));
}
 
開發者ID:GloriousEggroll,項目名稱:quorrabot,代碼行數:25,代碼來源:DiscordAPI.java

示例2: onMessageReceived

import net.dv8tion.jda.core.events.message.MessageReceivedEvent; //導入方法依賴的package包/類
@Override
public void onMessageReceived(MessageReceivedEvent event) {
    JDA jda = event.getJDA();
    long responseNumber = event.getResponseNumber();

    User author = event.getAuthor();                    //The user that sent the message
    Message message = event.getMessage();               //The message that was received
    MessageChannel channel = event.getChannel();        //The channel the message was sent in

    TransparentDiscord.receiveMessage(message, channel);
}
 
開發者ID:MCPlummet,項目名稱:TransparentDiscord,代碼行數:12,代碼來源:MessageListener.java

示例3: onMessageReceived

import net.dv8tion.jda.core.events.message.MessageReceivedEvent; //導入方法依賴的package包/類
/**
 * NOTE THE @Override!
 * This method is actually overriding a method in the ListenerAdapter class! We place an @Override annotation
 * right before any method that is overriding another to guarantee to ourselves that it is actually overriding
 * a method from a super class properly. You should do this every time you override a method!
 * <p>
 * As stated above, this method is overriding a hook method in the
 * {@link net.dv8tion.jda.core.hooks.ListenerAdapter ListenerAdapter} class. It has convience methods for all JDA events!
 * Consider looking through the events it offers if you plan to use the ListenerAdapter.
 * <p>
 * In this example, when a message is received it is printed to the console.
 *
 * @param event An event containing information about a {@link net.dv8tion.jda.core.entities.Message Message} that was
 *              sent in a channel.
 */

//All Messages recieved, from Private channels (DM), Public Channels(server/guild), Groups (Client only, we're using bot account so we can't do groups)
@Override
public void onMessageReceived(MessageReceivedEvent event) {
    //These are provided with every event in JDA
    JDA jda = event.getJDA();                       //JDA, the core of the api.


    //long responseNumber = event.getResponseNumber();//The amount of discord events that JDA has received since the last reconnect.

    //Event specific information
    User author = event.getAuthor();                //The user that sent the message
    Message message = event.getMessage();           //The message that was received.

  String msg = message.getContentDisplay();              //This returns a human readable version of the Message. Similar to
    // what you would see in the client.
    boolean isBotAdminOwner = isBotAdminOwner(author);

    if (message.isFromType(ChannelType.TEXT)) {
        if (message.isMentioned(jda.getSelfUser())) {
            if (msg.contains("shutdown")) {
                //Make sure we have permission
                if (isBotAdminOwner) {
                    closeMeDown(author);
                }
            }
        }
    } else if (message.isFromType(ChannelType.PRIVATE)) {
        if (msg.contains("shutdown")) {
            //Make sure we have permission
            if (isBotAdminOwner) {
                closeMeDown(author);
            }
        }
    }


}
 
開發者ID:IANetworks,項目名稱:Ducky-Mc-Duckerson,代碼行數:54,代碼來源:EventListener.java

示例4: onMessageReceived

import net.dv8tion.jda.core.events.message.MessageReceivedEvent; //導入方法依賴的package包/類
public void onMessageReceived(MessageReceivedEvent event) {
	if(event.getAuthor().equals(event.getJDA().getSelfUser())) return;
	
	User user = event.getAuthor();
	String message = event.getMessage().getContent();
	if(message.length()>=10) {
		Random rand = new Random();
		levelManager.addXP(event, user, rand.nextInt(25 - 15) + 15);
	}
}
 
開發者ID:Nonoland,項目名稱:TaverneBot,代碼行數:11,代碼來源:LevelEvent.java

示例5: onMessage

import net.dv8tion.jda.core.events.message.MessageReceivedEvent; //導入方法依賴的package包/類
@SubscribeEvent
protected void onMessage(MessageReceivedEvent event)
{
    // TODO: Krobot 2.5.0, handle mentions with space / quotes / etc...

    String[] line = splitWithQuotes(event.getMessage().getContent());

    if (line.length == 0)
    {
        return;
    }

    for (Command command : commands)
    {
        if (command.getLabel().equalsIgnoreCase(line[0]))
        {
            if (typing)
            {
                event.getChannel().sendTyping().queue();
            }

            CommandContext context = new CommandContext(event.getAuthor(), event.getMessage(), event.getTextChannel());
            List<String> args = Arrays.asList(ArrayUtils.subarray(line, 1, line.length));

            try
            {
                command.call(context, args);
            }
            catch (Throwable t)
            {
                exHandler.handle(t, command, args, context);
            }

            return;
        }
    }
}
 
開發者ID:krobot-framework,項目名稱:krobot,代碼行數:38,代碼來源:CommandManager.java

示例6: MCBUser

import net.dv8tion.jda.core.events.message.MessageReceivedEvent; //導入方法依賴的package包/類
public MCBUser(MessageReceivedEvent e) {
    nickNames = new HashMap<>();
    name = e.getAuthor().getName();
    nickNames.put(e.getGuild(), e.getMember().getNickname());
    ID = e.getAuthor().getId();
    mcUUID = null;
    user = e.getAuthor();
}
 
開發者ID:CyR1en,項目名稱:Minecordbot,代碼行數:9,代碼來源:MCBUser.java

示例7: onMessageReceived

import net.dv8tion.jda.core.events.message.MessageReceivedEvent; //導入方法依賴的package包/類
@Override
public void onMessageReceived(MessageReceivedEvent event)
{
    JDA jda = event.getJDA();
    //Amount of Discord events that JDA has received since the last reconnect
    long responsNo = event.getResponseNumber();

    //Event specific information

    User user = event.getAuthor();
    Message message = event.getMessage();
    MessageChannel channel = event.getChannel();    //Could be a TextChannel, PrivateChannel or Group

    String messageText = message.getContent();
    boolean isBot = user.isBot();

    //FYI in the API, Guilds are Servers
    ChannelType type = event.getChannelType();
    String guildName;
    String channelName = channel.getName();
    String userName = user.getName();

    if(type.isGuild())
    {
        guildName = event.getGuild().getName();
        Member member = event.getMember();

        //If this is a Webhook message then there is no Member associated with the User, so we use User for the name
        //If not a Webhook message, we'll use the Member's nickname if they have one. Otherwise we'll use their username
        userName = message.isWebhookMessage() ? user.getName() : member.getEffectiveName();
    }
    else
    {
        guildName = type.toString();
    }

    if(isBot) userName = "BOT:" + userName;

    Util.info(getClass(),"(" + guildName + ")[" + channelName + "]<" + userName + ">: " + messageText);


    if(messageText.equals("hello"))
        channel.sendMessage("Hello " + user.getAsMention() + "!").queue();
    else if(messageText.equals("roll"))
    {
        int roll = new Random().nextInt(6) + 1;
        channel.sendMessage("Your roll: " + roll).queue(message1 ->
        {
            if(roll < 3)
                channel.sendMessage("Ohh that was a bit of a low roll...").queue();
        });
    }
}
 
開發者ID:thebrightspark,項目名稱:MDC-Discord-Bot,代碼行數:54,代碼來源:MessageReceivedListener.java

示例8: getResponseFromSender

import net.dv8tion.jda.core.events.message.MessageReceivedEvent; //導入方法依賴的package包/類
private Predicate<MessageReceivedEvent> getResponseFromSender(MessageReceivedEvent original) {
	System.out.println("here");
	return p -> p.getAuthor() == original.getAuthor() && p.getMessage().getContentRaw().equals("sup");
}
 
開發者ID:JessWalters,項目名稱:Vinny-Redux,代碼行數:5,代碼來源:Bot.java

示例9: onMessageReceived

import net.dv8tion.jda.core.events.message.MessageReceivedEvent; //導入方法依賴的package包/類
@Override
public void onMessageReceived(MessageReceivedEvent event) {
	String message = event.getMessage().getContentDisplay();
	MessageChannel channel = event.getChannel();
	User author = event.getAuthor();

	if ( (channel == controlChannel || channel.getType() == ChannelType.PRIVATE) && message.startsWith(Config.get(Config.COMMAND_PREFIX)) && (!author.getId().equals(api.getSelfUser().getId())) ) {

		Log.debug("Got command from {}: {}", author.getName(), message);

		String[] cmdarg = message.substring(Config.get(Config.COMMAND_PREFIX).length()).split(" ", 2);
		String cmd = cmdarg[0];
		String arg;
		try {
			arg = cmdarg[1];
		} catch (IndexOutOfBoundsException e) {
			arg = null;
		}

		boolean commandFound = false;

		for(Command command : Command.commands) {
			if (command.compare(cmd)) {
				commandFound = true;

				if(command.hasPermission(author)) {
					command.execute(arg, author, channel, guild);
				} else {
					channel.sendMessage(author.getAsMention() + " ``You are not allowed to use this command.``").queue();
				}

				break;
			}
		}

		if(commandFound) {
			return;
		}

		channel.sendMessage(author.getAsMention() + " ``Unknown command``").queue();

	}
}
 
開發者ID:Bleuzen,項目名稱:Blizcord,代碼行數:44,代碼來源:Bot.java

示例10: run

import net.dv8tion.jda.core.events.message.MessageReceivedEvent; //導入方法依賴的package包/類
@Override
public Result run(String[] args, MessageReceivedEvent e) throws Exception {
	
	//Parse args
	if (args.length == 0) {
		return new Result(Outcome.WARNING, "Missing code argument.");
	}
	
	//Javascript engine with JDA, event and config variables.
	ScriptEngineManager factory = new ScriptEngineManager();
	ScriptEngine engine = factory.getEngineByName("JavaScript");
	engine.put("jda", e.getJDA());
	engine.put("config", Bot.config);
	engine.put("event", e);
	engine.put("guild", e.getGuild());
	engine.put("channel", e.getChannel());
	engine.put("user", e.getAuthor());
	
	//Extract code from message
	String code = "";
	for (String arg : args) {
		code += arg + " ";
	}
	code = code.substring(0, code.length() - 1);
	
	//Evaluate and print code
	Object output = engine.eval(code);
	if (output == null) {
		return new Result(Outcome.ERROR, ":x: Recieved null as output.");
	}
	
	EmbedBuilder eb = new EmbedBuilder();
	eb.addField("Input", "```js\n" + clean(code) + "\n```", false);
	eb.addField("Output", "```js\n" + clean(output.toString()) + "\n```", false);
	eb.setTimestamp(OffsetDateTime.now());
	User u = e.getAuthor();
	eb.setFooter("Sent by " + u.getName() + "#" + u.getDiscriminator() + " (" + u.getId() + ")", u.getAvatarUrl());
	
	return new Result(Outcome.SUCCESS, eb.build());
	
}
 
開發者ID:Tisawesomeness,項目名稱:Minecord,代碼行數:42,代碼來源:EvalCommand.java

示例11: onMessageReceived

import net.dv8tion.jda.core.events.message.MessageReceivedEvent; //導入方法依賴的package包/類
@Override
public void onMessageReceived(MessageReceivedEvent event)
{
	if (NapBot.terminationReason != null || event.getAuthor().getIdLong() == event.getAuthor().getJDA().getSelfUser().getIdLong())
	{
		// don't respond to messages if the bot is shutting down, or if the messages are coming the bot itself
		return;
	}
	try
	{
		if (event.isFromType(ChannelType.PRIVATE))
		{
			log.info("PRIVATE/{}: {}", event.getAuthor().getName(), event.getMessage().getRawContent());
			event.getChannel().sendMessage("I haven't been programmed to respond to private messages O_O").complete();
		}
		else if (event.isFromType(ChannelType.TEXT))
		{
			Message message = event.getMessage();
			User author = event.getAuthor();
			TextChannel channel = event.getTextChannel();
			String content = message.getRawContent();
			if (content.startsWith(NapBot.CONFIGURATION.messagePrefix) && content.length() > NapBot.CONFIGURATION.messagePrefix.length())
			{
				log.info("PUBLIC/{}/{}/{}: {}", author.getName(), channel.getGuild().getName(), channel.getName(), content);
				ArrayList<String> split = new ArrayList<String>(Arrays.asList(content.substring(NapBot.CONFIGURATION.messagePrefix.length()).split(" ")));
				String command = split.remove(0);
				ICommand icommand = commands.get(command.toLowerCase(Locale.ENGLISH));
				if (icommand == null)
				{
					channel.sendMessage("I don't know what you mean by `" + content + "`. If you're not sure what you're doing, try typing `" + NapBot.CONFIGURATION.messagePrefix + "help`.").complete();
					return;
				}
				if (!icommand.hasPermission(author))
				{
					channel.sendMessage("You don't have permission to execute that command").complete();
					return;
				}
				if (!icommand.execute(author, channel, command, split, message))
				{
					channel.sendMessage("I don't know what you mean by `" + content + "`. If you're not sure what you're doing, try typing `" + NapBot.CONFIGURATION.messagePrefix + "help`.").complete();
					return;
				}
			}
		}
	}
	catch (Throwable t)
	{
		event.getChannel().sendMessage("An internal error occurred and I wasn't able to process that command. Please ask <@147356941860077568> to investigate").complete();
		t.printStackTrace();
	}
}
 
開發者ID:PolyphasicDevTeam,項目名稱:NapBot,代碼行數:52,代碼來源:NapBotListener.java

示例12: onMessageReceived

import net.dv8tion.jda.core.events.message.MessageReceivedEvent; //導入方法依賴的package包/類
@Override
public void onMessageReceived(MessageReceivedEvent event) {
    CoreConfig config = this.phononPlugin.getConfigAdapter(CoreModule.ID, CoreConfigAdapter.class).get().getNodeOrDefault();

    if (event.getMessage().getRawContent().startsWith(config.getPrefix()) && !event.getMessage().getAuthor().isBot()) {
        DiscordCommandSource source = new DiscordCommandSource(event.getAuthor(), event.getChannel());

        int end = event.getMessage().getRawContent().indexOf(" ");
        String commandName;
        String arguments;
        if (end == -1) {
            commandName = event.getMessage().getRawContent().substring(1);
            arguments = "";
        } else {
            commandName = event.getMessage().getRawContent().substring(1, end);
            arguments = event.getMessage().getRawContent().substring(end + 1);
        }


        if (aliases.containsKey(commandName)) {
            IDiscordCommand command = aliases.get(commandName);
            CommandElement args= null;
            try {
                CommandArgs commandArgs = new CommandArgs(arguments,
                        InputTokenizer.quotedStrings(false).tokenize(arguments, true));
                CommandContext context = new CommandContext();
                args = GenericArguments.seq(command.getArgs());
                args.parse(source, commandArgs, context);
                if (commandArgs.hasNext()) {
                    commandArgs.next();
                    throw commandArgs.createError(t("Invalid arguments!"));
                }
                command.execute(event.getAuthor(), context, event.getChannel());
            } catch (ArgumentParseException e) {
                String message = "Invalid Arguments";
                if (e.getMessage() != null) {
                    message = e.getMessage();
                }

                if (args == null) {
                    event.getChannel().sendMessage(message).queue();
                } else {
                    event.getChannel().sendMessage(message + System.lineSeparator() +
                            config.getPrefix() + commandName + args.getUsage(source).toPlain()).queue();
                }
            }

            if (!(event.getChannel() instanceof PrivateChannel)) {
                event.getMessage().delete().queue();
            }
        }
    }
}
 
開發者ID:NucleusPowered,項目名稱:Phonon,代碼行數:54,代碼來源:CommandListener.java

示例13: doCommand

import net.dv8tion.jda.core.events.message.MessageReceivedEvent; //導入方法依賴的package包/類
@Override
public boolean doCommand(MessageReceivedEvent message, BotContext context, String query) {
    DateTimeFormatter formatter = DateTimeFormat.fullDateTime().withLocale(contextService.getLocale());
    User author = message.getAuthor();
    User user = author;
    if (!message.getMessage().getMentionedUsers().isEmpty()) {
        user = message.getMessage().getMentionedUsers().get(0);
    }
    Member member = null;
    if (message.getGuild() != null) {
        member = message.getGuild().getMember(user);
    }

    EmbedBuilder builder = messageService.getBaseEmbed();
    builder.setTitle(messageService.getMessage("discord.command.user.title",
            member != null ? member.getEffectiveName() : user.getName()));
    builder.setImage(user.getEffectiveAvatarUrl());
    builder.setFooter(messageService.getMessage("discord.command.info.identifier", user.getId()), null);

    builder.addField(getName(user, member));
    if (member != null) {
        builder.addField(getOnlineStatus(user, member));
        if (member.getGame() != null) {
            builder.addField(getGame(user, member));
        }
        builder.addField(getJoinedAt(user, member, formatter));
    }
    builder.addField(getCreatedAt(user, member, formatter));
    if (member != null && !user.isBot()) {
        if (rankingService.isEnabled(member.getGuild().getIdLong())) {
            RankingInfo info = rankingService.getRankingInfo(member);
            if (info != null) {
                rankCommand.addFields(builder, info);
            }
        }
        MemberBio memberBio = bioRepository.findByGuildIdAndUserId(member.getGuild().getId(), user.getId());
        String bio = memberBio != null ? memberBio.getBio() : null;
        if (StringUtils.isEmpty(bio) && Objects.equals(author, user)) {
            bio = messageService.getMessage("discord.command.user.bio.none", context.getConfig().getPrefix());
        }
        builder.setDescription(CommonUtils.trimTo(bio, MessageEmbed.TEXT_MAX_LENGTH));
    }
    messageService.sendMessageSilent(message.getChannel()::sendMessage, builder.build());
    return true;
}
 
開發者ID:GoldRenard,項目名稱:JuniperBotJ,代碼行數:46,代碼來源:UserInfoCommand.java


注:本文中的net.dv8tion.jda.core.events.message.MessageReceivedEvent.getAuthor方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。