本文整理汇总了Java中sx.blah.discord.Discord4J类的典型用法代码示例。如果您正苦于以下问题:Java Discord4J类的具体用法?Java Discord4J怎么用?Java Discord4J使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Discord4J类属于sx.blah.discord包,在下文中一共展示了Discord4J类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: invokeMethod
import sx.blah.discord.Discord4J; //导入依赖的package包/类
/**
* Invokes the method of the command.
*
* @param command The command.
* @param event The event.
* @param parameters The parameters for the method.
*/
private void invokeMethod(SimpleCommand command, MessageReceivedEvent event, Object[] parameters) {
Method method = command.getMethod();
Object reply = null;
try {
method.setAccessible(true);
reply = method.invoke(command.getExecutor(), parameters);
} catch (IllegalAccessException | InvocationTargetException e) {
Discord4J.LOGGER.warn("Cannot invoke method {}!", method.getName(), e);
}
if (reply != null) {
try {
event.getMessage().getChannel().sendMessage(String.valueOf(reply));
} catch (MissingPermissionsException | RateLimitException | DiscordException ignored) { }
}
}
示例2: main
import sx.blah.discord.Discord4J; //导入依赖的package包/类
public static void main (String... args) throws RateLimitException {
LOG.info("Wrapping standard output and error streams with tracer!");
System.setOut(new PrintStreamTraced(System.out));
System.setErr(new PrintStreamTraced(System.err));
LOG.info("Shutting Discord4J's Yap");
LoggingHandler.setLoggerLevel((ch.qos.logback.classic.Logger) Discord4J.LOGGER, Level.OFF);
LOG.info("Starting bot with token " + Utilities.partiallyReplace(config.authToken, 4));
try {
instance = new ClientBuilder().withToken(config.authToken).login();
instance.getDispatcher().registerListener(state);
instance.getDispatcher().registerListener(commands);
instance.getDispatcher().registerListener(auditor);
}
catch (final DiscordException e) {
LOG.trace("Error during startup", e);
instance.logout();
System.exit(0);
}
}
示例3: sendMessage
import sx.blah.discord.Discord4J; //导入依赖的package包/类
public static void sendMessage(IChannel channel, String message, EmbedObject object) {
if (message.length() > 2000 || object.description.length() > 2000) {
Utilities.sendMessage(channel, "I tried to send a message, but it was too long. " + message.length() + "/2000 chars! Embedded: " + object.description.length() + "/2000!");
Discord4J.LOGGER.info(message);
Discord4J.LOGGER.info(object.description);
return;
}
try {
channel.sendMessage(message, object, false);
Thread.sleep(1000);
} catch (RateLimitException | DiscordException | MissingPermissionsException | InterruptedException e) {
e.printStackTrace();
}
}
示例4: details
import sx.blah.discord.Discord4J; //导入依赖的package包/类
/**
* Gains the same information as accepting,
* but doesn't actually accept the invite.
*
* @return an InviteResponse containing the invite's details.
* @throws Exception
*/
public InviteResponse details() throws Exception {
if (DiscordClient.get().isReady()) {
String response = Requests.GET.makeRequest(DiscordEndpoints.INVITE + inviteCode,
new BasicNameValuePair("authorization", DiscordClient.get().getToken()));
JSONObject object1 = (JSONObject) new JSONParser().parse(response);
JSONObject guild = (JSONObject) object1.get("guild");
JSONObject channel = (JSONObject) object1.get("channel");
return new InviteResponse((String) guild.get("id"),
(String) guild.get("name"),
(String) channel.get("id"),
(String) channel.get("name"));
} else {
Discord4J.logger.error("Bot has not signed in yet!");
return null;
}
}
示例5: execute
import sx.blah.discord.Discord4J; //导入依赖的package包/类
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
if (clientRegistry.getClients().isEmpty()) {
log.warn("No bots to track data for");
}
for (Map.Entry<Bot, IDiscordClient> entry : clientRegistry.getClients().entrySet()) {
IDiscordClient client = entry.getValue();
if (client.isReady()) {
String botTag = "bot:" + entry.getKey().getName();
for (IShard shard : client.getShards()) {
String shardTag = "shard:" + shard.getInfo()[0];
long millis = shard.getResponseTime();
metricRegistry.timer("discord.ws.response[" + botTag + "," + shardTag + "]")
.update(millis, TimeUnit.MILLISECONDS);
}
for (IGuild guild : client.getGuilds()) {
String guildTag = "guild:" + guild.getStringID();
long online = guild.getUsers().stream()
.filter(user -> user.getPresence().getStatus() == StatusType.ONLINE)
.count();
long connected = guild.getUsers().stream()
.filter(user -> user.getPresence().getStatus() != StatusType.OFFLINE)
.count();
long joined = guild.getUsers().size();
String onlineMetric = "discord.ws.users[" + botTag + "," + guildTag + "," + "status:online]";
String connectedMetric = "discord.ws.users[" + botTag + "," + guildTag + "," + "status:connected]";
String joinedMetric = "discord.ws.users[" + botTag + "," + guildTag + "," + "status:joined]";
metricRegistry.histogram(onlineMetric).update(online);
metricRegistry.histogram(connectedMetric).update(connected);
metricRegistry.histogram(joinedMetric).update(joined);
}
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
loggerContext.getLogger("org.eclipse.jetty.websocket").setLevel(Level.WARN);
loggerContext.getLogger(Discord4J.class).setLevel(Level.DEBUG);
} else {
log.warn("Bot {} is not ready!", entry.getKey().getName());
}
}
}
示例6: onDisconnect
import sx.blah.discord.Discord4J; //导入依赖的package包/类
@EventSubscriber
public void onDisconnect(DisconnectedEvent event) {
log.info("[{}] Discord bot disconnected due to {}", ourBotName(event), event.getReason());
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
context.getLogger("org.eclipse.jetty.websocket").setLevel(Level.TRACE);
context.getLogger(Discord4J.class).setLevel(Level.TRACE);
}
示例7: afterPropertiesSet
import sx.blah.discord.Discord4J; //导入依赖的package包/类
@Override
public void afterPropertiesSet() throws Exception {
try (InputStream stream = Discord4J.class.getClassLoader().getResourceAsStream("app.properties")) {
properties.load(stream);
} catch (IOException e) {
log.warn("", e);
}
properties.setProperty("startTime", "" + runtimeMXBean.getStartTime());
properties.setProperty("version", buildProperties.getVersion());
}
示例8: joinGuild
import sx.blah.discord.Discord4J; //导入依赖的package包/类
@Override
public void joinGuild(IGuild guild) {
checkScope(Scope.GUILDS_JOIN);
refreshTokenIfNeeded();
DiscordUtils.checkPermissions(this.user.getClient(), guild, EnumSet.of(Permissions.CREATE_INVITE));
try {
((DiscordClientImpl) this.user.getClient()).REQUESTS.PATCH.makeRequest(
DiscordEndpoints.GUILDS + guild.getLongID() + "/members/" + user.getStringID(),
DiscordUtils.MAPPER_NO_NULLS.writeValueAsString(new MemberAddRequest.Builder(getAccessToken()).build()));
} catch (JsonProcessingException e) {
Discord4J.LOGGER.error(LogMarkers.HANDLE, "Discord4J Internal Exception", e);
}
}
示例9: execute
import sx.blah.discord.Discord4J; //导入依赖的package包/类
@Override
public void execute(Context context) {
long ping = TimeUtils.getMillisUntil(context.getMessage().getCreationDate());
long uptime = TimeUtils.getMillisUntil(Discord4J.getLaunchTime());
Runtime runtime = Runtime.getRuntime();
int mbUnit = 1024 * 1024;
long usedMemory = (runtime.totalMemory() - runtime.freeMemory()) / mbUnit;
long maxMemory = runtime.maxMemory() / mbUnit;
IUser owner = context.getClient().getApplicationOwner();
String info = new String("```prolog"
+ String.format("%n-= Performance Info =-")
+ String.format("%nMemory: %s/%s MB", FormatUtils.formatNum(usedMemory), FormatUtils.formatNum(maxMemory))
+ String.format("%nCPU Usage: %.1f%%", Utils.getProcessCpuLoad())
+ String.format("%nThreads Count: %s", FormatUtils.formatNum(Thread.activeCount()))
+ String.format("%n%n-= APIs Info =-")
+ String.format("%nJava Version: %s", System.getProperty("java.version"))
+ String.format("%n%s Version: %s", Discord4J.NAME, Discord4J.VERSION)
+ String.format("%nLavaPlayer Version: %s", PlayerLibrary.VERSION)
+ String.format("%n%n-= Shadbot Info =-")
+ String.format("%nUptime: %s", DurationFormatUtils.formatDuration(uptime, "d 'days,' HH 'hours and' mm 'minutes'", true))
+ String.format("%nDeveloper: %s#%s", owner.getName(), owner.getDiscriminator())
+ String.format("%nShadbot Version: %s", Shadbot.getVersion())
+ String.format("%nShard: %d/%d", context.getShadbotShard().getID() + 1, context.getClient().getShardCount())
+ String.format("%nServers: %s", FormatUtils.formatNum(context.getClient().getGuilds().size()))
+ String.format("%nVoice Channels: %d", context.getClient().getConnectedVoiceChannels().size())
+ String.format("%nUsers: %s", FormatUtils.formatNum(context.getClient().getUsers().size()))
+ String.format("%nPing: %dms", ping)
+ "```");
BotUtils.sendMessage(info, context.getChannel());
}
示例10: info
import sx.blah.discord.Discord4J; //导入依赖的package包/类
private String info(IMessage m, OptionSet o) {
if (gitProperties == null) {
gitProperties = new GitProperties();
}
StringBuilder builder = new StringBuilder();
RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean();
long uptime = rb.getUptime();
String version = gitProperties.getProperty("git.commit.id.describe", "0.x");
builder.append("Hello! I'm here to help with **UGC support**.\n")
.append("Running `v").append(version).append("` with **Discord4J** library `v")
.append(Discord4J.VERSION).append("`.\nUptime: ").append(formatHuman(Duration.ofMillis(uptime)))
.append("\nCheck the available commands with `.help`");
return builder.toString();
}
示例11: onCommand
import sx.blah.discord.Discord4J; //导入依赖的package包/类
@Override
public void onCommand(IUser sender, IChannel channel, IMessage message, String[] args) {
EmbedBuilder bld = MessageUtils.getEmbed(sender).withThumbnail(MessageUtils.getAvatar(channel.getClient().getOurUser()));
bld.withDesc("FlareBot v" + FlareBot.getInstance().getVersion() + " info");
bld.appendField("Servers: ", String.valueOf(client.getGuilds().size()), true);
bld.appendField("Voice Connections: ", String.valueOf(client.getConnectedVoiceChannels().size()), true);
bld.appendField("Channels playing music: ", String.valueOf(client.getConnectedVoiceChannels().stream()
.map(IVoiceChannel::getGuild)
.map(IDiscordObject::getID)
.filter(gid -> FlareBot.getInstance().getMusicManager().hasPlayer(gid))
.map(g -> FlareBot.getInstance().getMusicManager().getPlayer(g))
.filter(p -> p.getPlayingTrack() != null)
.filter(p -> !p.getPaused()).count()), true);
bld.appendField("Text Channels: ", String.valueOf(client.getChannels(false).size()), true);
bld.appendField("Uptime: ", FlareBot.getInstance().getUptime(), true);
bld.appendField("Memory Usage: ", getMb(runtime.totalMemory() - runtime.freeMemory()), true);
bld.appendField("Memory Free: ", getMb(runtime.freeMemory()), true);
bld.appendField("Video threads: ", String.valueOf(VideoThread.VIDEO_THREADS.activeCount()), true);
bld.appendField("Total threads: ", String.valueOf(Thread.getAllStackTraces().size()), true);
bld.appendField("Discord4J Version: ", Discord4J.VERSION, true);
if (git != null)
bld.appendField("Git revision: ", git, true);
bld.appendField("CPU Usage: ",
((int) (ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class).getSystemCpuLoad() * 10000)) / 100f + "%", true);
bld.appendField("Support Server: ", "[`Discord`](http://discord.me/flarebot)", true);
bld.appendField("Donate to our host: ", "[`PayPal`](https://www.paypal.me/CaptainBaconz)", true);
bld.appendField("Our Patreon: ", "[`Patreon`](https://www.patreon.com/flarebot)", true);
bld.appendField("Website: ", "[`FlareBot`](http://flarebot.stream/)", true);
bld.appendField("Twitter: ", "[`Twitter`](https://twitter.com/DiscordFlareBot)", true);
bld.appendField("Invite: ", String.format("[`Invite`](%s)", FlareBot.getInstance().getInvite()), true);
bld.appendField("\u200B", "\u200B", false);
// bld.appendField("\u200B", "\u200B", true);
bld.appendField("Made By: ", "bwfcwalshy#1284 and Arsen#3291", true);
bld.appendField("Source: ", "[`GitHub`](https://github.com/ArsenArsen/FlareBot)", true);
MessageUtils.sendMessage(bld.build(), channel);
}
示例12: downloadDocs
import sx.blah.discord.Discord4J; //导入依赖的package包/类
private static void downloadDocs() {
docParser = null;
DOWNLOAD_FOLDER.mkdirs();
shouldForceRedownload = false;
Discord4J.LOGGER.info("Attempting to download sources from " + URL_URL + "...");
boolean success = chrislo27.oldbot.util.documentation.DocumentationParser
.downloadSources(SOURCES_URL, DOWNLOAD_PATH);
Discord4J.LOGGER.info((success ? "Successfully gotten sources!" : "Failed to get sources!"));
if (!success) {
docParser = null;
throw new RuntimeException("Failed to download sources!");
}
}
示例13: accept
import sx.blah.discord.Discord4J; //导入依赖的package包/类
/**
* @return Accepts the invite and returns relevant information,
* such as the Guild ID and name, and the channel the invite
* was created from.
* @throws Exception
*/
public void accept() throws HTTP403Exception {
if (DiscordClient.get().isReady()) {
String response = Requests.POST.makeRequest(DiscordEndpoints.INVITE + inviteCode,
new BasicNameValuePair("authorization", DiscordClient.get().getToken()));
} else {
Discord4J.logger.error("Bot has not signed in yet!");
}
}
示例14: registerListener
import sx.blah.discord.Discord4J; //导入依赖的package包/类
/**
* Registers an IListener to receive events.
* @param listener Listener to register
*/
@Override public void registerListener(Object listener) {
if(listener instanceof IListener) {
Class<?> rawType = TypeResolver.resolveRawArgument(IListener.class, listener.getClass());
if (IEvent.class.isAssignableFrom(rawType)) {
Class<? extends IEvent> eventType = (Class<? extends IEvent>) rawType;
if (listenerMap.containsKey(eventType)) {
listenerMap.get(eventType).add((IListener) listener);
} else {
listenerMap.put(eventType, new ArrayList<>(Collections.singletonList((IListener) listener)));
}
Discord4J.logger.debug("Registered IListener for {}. Map size now {}.", eventType.getSimpleName(), listenerMap.size());
}
}
}
示例15: dispatch
import sx.blah.discord.Discord4J; //导入依赖的package包/类
/**
* Sends an IEvent to all listeners that listen for that specific event.
* @param event The event to dispatch.
*/
@Override public void dispatch(IEvent event) {
Class<? extends IEvent> eventType = event.getClass();
Discord4J.logger.debug("Dispatching event of type {}.", eventType.getSimpleName());
if (listenerMap.containsKey(eventType)) {
for (IListener listener : listenerMap.get(eventType)) {
listener.receive(event);
}
}
}