Skip to content

Commit

Permalink
feat: Added in command renderers
Browse files Browse the repository at this point in the history
  • Loading branch information
bendavies99 committed Jun 7, 2023
1 parent 439d002 commit dda07ca
Show file tree
Hide file tree
Showing 10 changed files with 379 additions and 148 deletions.
3 changes: 0 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,6 @@
]
]
},
"engines" : {
"node" : "^12.12.0"
},
"config" : {
"commitizen" : {
"path" : "./node_modules/cz-conventional-changelog"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,38 +25,29 @@

package net.bdavies.babblebot.command;

import discord4j.core.object.entity.Guild;
import discord4j.core.object.entity.PartialMember;
import discord4j.core.object.entity.channel.TextChannel;
import discord4j.core.spec.EmbedCreateSpec;
import discord4j.discordjson.json.ApplicationCommandRequest;
import discord4j.rest.util.Color;
import lombok.extern.slf4j.Slf4j;
import net.bdavies.babblebot.api.IApplication;
import net.bdavies.babblebot.api.command.ICommand;
import net.bdavies.babblebot.api.command.ICommandContext;
import net.bdavies.babblebot.api.command.ICommandDispatcher;
import net.bdavies.babblebot.api.command.ICommandMiddleware;
import net.bdavies.babblebot.api.config.EPluginPermission;
import net.bdavies.babblebot.api.obj.DiscordColor;
import net.bdavies.babblebot.api.obj.message.discord.embed.EmbedAuthor;
import net.bdavies.babblebot.api.obj.message.discord.embed.EmbedFooter;
import net.bdavies.babblebot.api.obj.message.discord.embed.EmbedMessage;
import net.bdavies.babblebot.api.plugins.IPlugin;
import net.bdavies.babblebot.api.plugins.IPluginContainer;
import net.bdavies.babblebot.api.plugins.IPluginSettings;
import net.bdavies.babblebot.api.plugins.Plugin;
import net.bdavies.babblebot.command.errors.UsageException;
import net.bdavies.babblebot.command.parser.MessageParser;
import net.bdavies.babblebot.command.renderer.CommandRenderer;
import net.bdavies.babblebot.command.response.BaseResponse;
import net.bdavies.babblebot.discord.DiscordFacade;
import net.bdavies.babblebot.discord.obj.factories.EmbedMessageFactory;
import net.bdavies.babblebot.variables.VariableParser;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.Loggers;

import java.time.Instant;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
Expand Down Expand Up @@ -252,10 +243,11 @@ public Mono<ICommand> getCommandByAlias(String namespace, String alias, String t
*
* @param parser - The way the message is interpreted.
* @param message - This is the user's input or any other type of input.
* @param application - The application instance.
* @param application - The application instance
* @param renderer - The command renderer that will process the command responses
*/
public void execute(MessageParser parser, String message, Mono<TextChannel> channel, Mono<Guild> guild,
IApplication application)
public void execute(MessageParser parser, String message, IApplication application,
CommandRenderer renderer)
{
ICommandContext commandContext = parser.parseString(message);

Expand Down Expand Up @@ -313,12 +305,12 @@ public void execute(MessageParser parser, String message, Mono<TextChannel> chan
}, null, () -> {
if (!hasSentMessage.get())
{
channel.subscribe(
c -> c.createMessage("Babblebot command couldn't be found.").subscribe());
renderer.render(ResponseFactory.createStringResponse(
"Babblebot command couldn't be found."));
} else
{
sb.append("```");
channel.subscribe(c -> c.createMessage(sb.toString()).subscribe());
renderer.render(ResponseFactory.createStringResponse(sb.toString()));
}
});
}
Expand All @@ -329,61 +321,36 @@ public void execute(MessageParser parser, String message, Mono<TextChannel> chan
return Flux.error(new UsageException(c.getUsage()));
}

//noinspection ReactiveStreamsUnusedPublisher
// commandContext.getMessage().getGuild().doOnNext(g ->
// log.debug(
// "Running command: " + commandContext.getCommandName() + "In
// Guild: " +
// g.getName()));
c.exec(application, commandContext);
return commandContext.getCommandResponse().getResponses()
.asFlux()
.log(Loggers.getLogger("CommandResponses"));
}).subscribe(s -> {
if (s.isStringResponse())
})
.cast(BaseResponse.class)
.map(br -> {
if (br.isStringResponse())
{

channel.subscribe(c -> c.createMessage(
new VariableParser(s.getStringResponse(), application).toString()).subscribe());
hasSentMessage.set(true);
} else if (s.getEmbedCreateSpecResponse() != null)
return br.toBuilder()
.stringResponse(new VariableParser(br.getStringResponse(),
application).toString())
.build();
}
return br;
})
.subscribe(r -> {
renderer.render(r);
hasSentMessage.set(true);
}, e -> {
boolean handled = false;
if (e instanceof Exception)
{
channel.subscribe(c -> {
EmbedMessage em = s.getEmbedCreateSpecResponse().get();
if (em.getFooter() == null)
{
em.setFooter(EmbedFooter.builder()
.text("Server Version: " + application.getServerVersion()).build());
}
if (em.getAuthor() == null)
{
em.setAuthor(EmbedAuthor.builder().name("BabbleBot")
.url("https://github.com/bendavies99/BabbleBot-Server").build());
}
if (em.getTimestamp() == null)
{
em.setTimestamp(Instant.now());
}
Optional<Color> color = guild.flatMap(
g -> application.get(DiscordFacade.class).getClient().getSelf()
.flatMap(u -> u.asMember(g.getId()).flatMap(PartialMember::getColor)))
.blockOptional();
if (em.getColor() == null && color.isPresent())
{
em.setColor(DiscordColor.from(color.get().getRGB()));
}

EmbedCreateSpec spec = EmbedMessageFactory.fromBabblebot(em);
c.typeUntil(c.createMessage(spec)).subscribe();
});
hasSentMessage.set(true);
handled = renderer.onError((Exception) e);
}
}, throwable -> {
if (throwable instanceof UsageException)

if (!handled)
{
channel.subscribe(c -> c.createMessage(throwable.getMessage()).subscribe());
log.error("Unable to render command {}", commandName, e);
}
hasSentMessage.set(true);
});

} else
Expand All @@ -396,7 +363,8 @@ public void execute(MessageParser parser, String message, Mono<TextChannel> chan
private Flux<ICommand> getCommandsLike(String commandName, String type)
{
return Flux.create(sink -> getCommands(type).doOnComplete(sink::complete)
.filter(c -> Arrays.stream(c.getAliases()).anyMatch(a -> a.contains(commandName)))
.filter(c -> Arrays.stream(c.getAliases())
.anyMatch(a -> a.contains(commandName)))
.doOnNext(sink::next).subscribe());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import lombok.extern.slf4j.Slf4j;
import net.bdavies.babblebot.api.command.IResponse;
import net.bdavies.babblebot.api.obj.message.discord.embed.EmbedMessage;
import net.bdavies.babblebot.command.response.BaseResponse;

import java.util.function.Supplier;

Expand All @@ -36,42 +37,26 @@
* @since 1.2.7
*/
@Slf4j
public class ResponseFactory {
public class ResponseFactory
{

public static IResponse createResponse(String s, Supplier<EmbedMessage> spec) {
return new IResponse() {
@Override
public String getStringResponse() {
return s;
}

@Override
public Supplier<EmbedMessage> getEmbedCreateSpecResponse() {
return spec;
}

@Override
public boolean isStringResponse() {

if (s == null) {
log.error("Response is null, please fix!!!");
return false;
}

return !s.equals("");
}
};
public static IResponse createResponse(String s, Supplier<EmbedMessage> spec)
{
return BaseResponse.builder().stringResponse(s).embedMessageResponse(spec).build();
}

public static IResponse createStringResponse(String s) {
public static IResponse createStringResponse(String s)
{
return createResponse(s, null);
}

public static IResponse createEmbedResponse(EmbedMessage s) {
public static IResponse createEmbedResponse(EmbedMessage s)
{
return createResponse("", () -> s);
}

public static IResponse createEmbedResponse(Supplier<EmbedMessage> s) {
public static IResponse createEmbedResponse(Supplier<EmbedMessage> s)
{
return createResponse("", s);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* MIT License
*
* Copyright (c) 2020 Ben Davies
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/

package net.bdavies.babblebot.command.renderer;

import net.bdavies.babblebot.api.command.IResponse;

/**
* A Command Renderer will determine how a response
* from a command will then rendered to the output for discord it will render it on the discord channel
*
* @author me@bdavies.net (Ben Davies)
* @since __RELEASE_VERSION__
*/
public interface CommandRenderer
{
void render(IResponse response);

boolean onError(Exception e);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
* MIT License
*
* Copyright (c) 2020 Ben Davies
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/

package net.bdavies.babblebot.command.renderer;

import discord4j.core.object.entity.channel.TextChannel;
import discord4j.core.spec.EmbedCreateSpec;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.bdavies.babblebot.api.IApplication;
import net.bdavies.babblebot.api.command.IResponse;
import net.bdavies.babblebot.api.obj.message.discord.embed.EmbedMessage;
import net.bdavies.babblebot.command.errors.UsageException;
import net.bdavies.babblebot.discord.obj.factories.EmbedMessageFactory;

/**
* Discord Command Renderer that will send the response to the channel
*
* @author me@bdavies.net (Ben Davies)
* @since __RELEASE_VERSION__
*/
@Slf4j
@RequiredArgsConstructor
public class DiscordCommandRenderer implements CommandRenderer
{
private final TextChannel channel;
private final IApplication application;

@Override
public void render(IResponse response)
{
if (response.isStringResponse())
{
channel.createMessage(response.getStringResponse()).subscribe();
} else
{
EmbedMessage em = response.getEmbedCreateSpecResponse().get();
EmbedMessageFactory.addDefaults(em, application, channel.getGuild());
EmbedCreateSpec spec = EmbedMessageFactory.fromBabblebot(em);
channel.typeUntil(channel.createMessage(spec)).subscribe();
}
}

@Override
public boolean onError(Exception e)
{
if (e instanceof UsageException)
{
channel.createMessage(e.getMessage()).subscribe();
return true;
}

return false;
}
}
Loading

0 comments on commit dda07ca

Please sign in to comment.