Skip to content

Commit

Permalink
Merge branch 'develop' into feature/cake-day
Browse files Browse the repository at this point in the history
  • Loading branch information
christolis committed Mar 13, 2024
2 parents 27f5fd0 + 5ac1e07 commit d8c7206
Show file tree
Hide file tree
Showing 15 changed files with 146 additions and 168 deletions.
2 changes: 1 addition & 1 deletion .github/CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
@@ -1 +1 @@
* @Together-Java/moderators @Together-Java/maintainers
* @Together-Java/maintainers
2 changes: 1 addition & 1 deletion application/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ dependencies {

implementation 'org.kohsuke:github-api:1.319'

testImplementation 'org.mockito:mockito-core:5.3.1'
testImplementation 'org.mockito:mockito-core:5.10.0'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.10.0'
testImplementation 'org.junit.jupiter:junit-jupiter-params:5.10.0'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
Expand Down
3 changes: 2 additions & 1 deletion application/config.json.template
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,9 @@
"special": [
]
},
"selectRolesChannelPattern": "select-your-roles",
"cakeDayConfig": {
"rolePattern": "Cake Day"
}
"memberCountCategoryPattern": "Info",
"selectRolesChannelPattern": "select-your-roles"
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ public final class Config {
private final HelperPruneConfig helperPruneConfig;
private final FeatureBlacklistConfig featureBlacklistConfig;
private final String selectRolesChannelPattern;
private final String memberCountCategoryPattern;
private final CakeDayConfig cakeDayConfig;

@SuppressWarnings("ConstructorWithTooManyParameters")
Expand Down Expand Up @@ -87,6 +88,8 @@ private Config(@JsonProperty(value = "token", required = true) String token,
@JsonProperty(value = "openaiApiKey", required = true) String openaiApiKey,
@JsonProperty(value = "sourceCodeBaseUrl", required = true) String sourceCodeBaseUrl,
@JsonProperty(value = "jshell", required = true) JShellConfig jshell,
@JsonProperty(value = "memberCountCategoryPattern",
required = true) String memberCountCategoryPattern,
@JsonProperty(value = "helperPruneConfig",
required = true) HelperPruneConfig helperPruneConfig,
@JsonProperty(value = "featureBlacklist",
Expand All @@ -98,6 +101,7 @@ private Config(@JsonProperty(value = "token", required = true) String token,
this.githubApiKey = Objects.requireNonNull(githubApiKey);
this.databasePath = Objects.requireNonNull(databasePath);
this.projectWebsite = Objects.requireNonNull(projectWebsite);
this.memberCountCategoryPattern = Objects.requireNonNull(memberCountCategoryPattern);
this.discordGuildInvite = Objects.requireNonNull(discordGuildInvite);
this.modAuditLogChannelPattern = Objects.requireNonNull(modAuditLogChannelPattern);
this.modMailChannelPattern = Objects.requireNonNull(modMailChannelPattern);
Expand Down Expand Up @@ -417,4 +421,13 @@ public String getSelectRolesChannelPattern() {
public CakeDayConfig getCakeDayConfig() {
return cakeDayConfig;
}

/**
* Gets the pattern matching the category that is used to display the total member count.
*
* @return the categories name types
*/
public String getMemberCountCategoryPattern() {
return memberCountCategoryPattern;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import org.togetherjava.tjbot.config.FeatureBlacklist;
import org.togetherjava.tjbot.config.FeatureBlacklistConfig;
import org.togetherjava.tjbot.db.Database;
import org.togetherjava.tjbot.features.basic.MemberCountDisplayRoutine;
import org.togetherjava.tjbot.features.basic.PingCommand;
import org.togetherjava.tjbot.features.basic.RoleSelectCommand;
import org.togetherjava.tjbot.features.basic.SlashCommandEducator;
Expand Down Expand Up @@ -113,6 +114,7 @@ public static Collection<Feature> createFeatures(JDA jda, Database database, Con
.add(new AutoPruneHelperRoutine(config, helpSystemHelper, modAuditLogWriter, database));
features.add(new HelpThreadAutoArchiver(helpSystemHelper));
features.add(new LeftoverBookmarksCleanupRoutine(bookmarksSystem));
features.add(new MemberCountDisplayRoutine(config));
features.add(new CakeDayRoutine(cakeDayService));

// Message receivers
Expand Down Expand Up @@ -168,7 +170,7 @@ public static Collection<Feature> createFeatures(JDA jda, Database database, Con
features.add(new HelpThreadCommand(config, helpSystemHelper));
features.add(new ReportCommand(config));
features.add(new BookmarksCommand(bookmarksSystem));
features.add(new ChatGptCommand(chatGptService));
features.add(new ChatGptCommand(chatGptService, helpSystemHelper));
features.add(new JShellCommand(jshellEval));

FeatureBlacklist<Class<?>> blacklist = blacklistConfig.normal();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package org.togetherjava.tjbot.features.basic;

import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.channel.concrete.Category;

import org.togetherjava.tjbot.config.Config;
import org.togetherjava.tjbot.features.Routine;

import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.regex.Pattern;

/**
* Shows the guild member count on selected category, which updates everyday.
*/
public class MemberCountDisplayRoutine implements Routine {
private final Predicate<String> memberCountCategoryPredicate;

/**
* Creates an instance on member count display routine.
*
* @param config the config to use
*/
public MemberCountDisplayRoutine(Config config) {
memberCountCategoryPredicate =
Pattern.compile(config.getMemberCountCategoryPattern() + "( - \\d+ Members)?")
.asMatchPredicate();
}

private void updateCategoryName(Category category) {
int totalMemberCount = category.getGuild().getMemberCount();
String baseName = category.getName().split("-")[0].trim();

category.getManager()
.setName("%s - %d Members".formatted(baseName, totalMemberCount))
.queue();
}

@Override
public Schedule createSchedule() {
return new Schedule(ScheduleMode.FIXED_RATE, 0, 24, TimeUnit.HOURS);
}

@Override
public void runRoutine(JDA jda) {
jda.getGuilds()
.forEach(guild -> guild.getCategories()
.stream()
.filter(category -> memberCountCategoryPredicate.test(category.getName()))
.findAny()
.ifPresent(this::updateCategoryName));
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.entities.SelfUser;
import net.dv8tion.jda.api.events.interaction.ModalInteractionEvent;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.components.Modal;
Expand All @@ -10,6 +12,7 @@

import org.togetherjava.tjbot.features.CommandVisibility;
import org.togetherjava.tjbot.features.SlashCommandAdapter;
import org.togetherjava.tjbot.features.help.HelpSystemHelper;

import java.time.Duration;
import java.time.Instant;
Expand All @@ -28,6 +31,7 @@ public final class ChatGptCommand extends SlashCommandAdapter {
private static final int MIN_MESSAGE_INPUT_LENGTH = 4;
private static final Duration COMMAND_COOLDOWN = Duration.of(10, ChronoUnit.SECONDS);
private final ChatGptService chatGptService;
private final HelpSystemHelper helper;

private final Cache<String, Instant> userIdToAskedAtCache =
Caffeine.newBuilder().maximumSize(1_000).expireAfterWrite(COMMAND_COOLDOWN).build();
Expand All @@ -36,11 +40,13 @@ public final class ChatGptCommand extends SlashCommandAdapter {
* Creates an instance of the chatgpt command.
*
* @param chatGptService ChatGptService - Needed to make calls to ChatGPT API
* @param helper HelpSystemHelper - Needed to generate response embed for prompt
*/
public ChatGptCommand(ChatGptService chatGptService) {
public ChatGptCommand(ChatGptService chatGptService, HelpSystemHelper helper) {
super(COMMAND_NAME, "Ask the ChatGPT AI a question!", CommandVisibility.GUILD);

this.chatGptService = chatGptService;
this.helper = helper;
}

@Override
Expand Down Expand Up @@ -75,20 +81,23 @@ public void onModalSubmitted(ModalInteractionEvent event, List<String> args) {
event.deferReply().queue();

String context = "";
Optional<String[]> optional =
chatGptService.ask(event.getValue(QUESTION_INPUT).getAsString(), context);
String question = event.getValue(QUESTION_INPUT).getAsString();

Optional<String> optional = chatGptService.ask(question, context);
if (optional.isPresent()) {
userIdToAskedAtCache.put(event.getMember().getId(), Instant.now());
}

String[] errorResponse = {"""
String errorResponse = """
An error has occurred while trying to communicate with ChatGPT.
Please try again later.
"""};
""";

String[] response = optional.orElse(errorResponse);
for (String message : response) {
event.getHook().sendMessage(message).queue();
}
String response = optional.orElse(errorResponse);
SelfUser selfUser = event.getJDA().getSelfUser();

MessageEmbed responseEmbed = helper.generateGptResponseEmbed(response, selfUser, question);

event.getHook().sendMessageEmbeds(responseEmbed).queue();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,11 @@ public ChatGptService(Config config) {
* @param question The question being asked of ChatGPT. Max is {@value MAX_TOKENS} tokens.
* @param context The category of asked question, to set the context(eg. Java, Database, Other
* etc).
* @return partitioned response from ChatGPT as a String array.
* @return response from ChatGPT as a String.
* @see <a href="https://platform.openai.com/docs/guides/chat/managing-tokens">ChatGPT
* Tokens</a>.
*/
public Optional<String[]> ask(String question, String context) {
public Optional<String> ask(String question, String context) {
if (isDisabled) {
return Optional.empty();
}
Expand Down Expand Up @@ -121,7 +121,7 @@ public Optional<String[]> ask(String question, String context) {
return Optional.empty();
}

return Optional.of(AIResponseParser.parse(response));
return Optional.of(response);
} catch (OpenAiHttpException openAiHttpException) {
logger.warn(
"There was an error using the OpenAI API: {} Code: {} Type: {} Status Code: {}",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ private void processAttachments(MessageReceivedEvent event,
.build()
.createGist()
.public_(false)
.description("Uploaded by " + event.getAuthor().getAsTag());
.description("Uploaded by " + event.getAuthor().getName());

List<CompletableFuture<Void>> tasks = new ArrayList<>();

Expand Down
Loading

0 comments on commit d8c7206

Please sign in to comment.