Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/develop' into feature-guess-lang…
Browse files Browse the repository at this point in the history
…uage

# Conflicts:
#	app/bot-config.properties.template
#	app/build.gradle
#	app/src/main/java/com/togetherjava/tjplays/Bot.java
#	app/src/main/java/com/togetherjava/tjplays/services/chatgpt/ChatGptService.java
  • Loading branch information
Suleman70 committed Mar 17, 2024
2 parents 9c7af18 + 54cc10a commit 101b0ab
Show file tree
Hide file tree
Showing 10 changed files with 111 additions and 75 deletions.
4 changes: 2 additions & 2 deletions app/bot-config.properties.template
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
BOT_TOKEN=<ENTER BOT_TOKEN>
OPEN_AI_TOKEN=<ENTER OPEN_AI_TOKEN>
BOT_TOKEN=<put your token here>
OPENAI_API_KEY=<check pins in #tjbot_discussion for the key>
27 changes: 21 additions & 6 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,18 @@ repositories {

java {
toolchain {
languageVersion = JavaLanguageVersion.of(19)
languageVersion = JavaLanguageVersion.of(21)
}
}

ext {
chatGPTVersion = '0.18.0'
}

var outputImage = 'togetherjava.org:5001/togetherjava/tjplays:master' ?: 'latest'

jib {
from.image = 'eclipse-temurin:19'
from.image = 'eclipse-temurin:21'
to {
image = outputImage
auth {
Expand All @@ -31,19 +35,22 @@ jib {
setCreationTime(java.time.Instant.now().toString())
}
}
ext {
chatGPTVersion = '0.18.0'
}

shadowJar {
archiveBaseName.set('TJ-Plays')
archiveClassifier.set('')
archiveVersion.set('')
}

dependencies {
implementation 'net.dv8tion:JDA:5.0.0-beta.3'
implementation 'net.dv8tion:JDA:5.0.0-beta.21'

implementation "com.theokanning.openai-gpt3-java:api:$chatGPTVersion"
implementation "com.theokanning.openai-gpt3-java:service:$chatGPTVersion"

implementation 'org.apache.logging.log4j:log4j-core:2.23.0'
runtimeOnly 'org.apache.logging.log4j:log4j-slf4j18-impl:2.18.0'

testImplementation 'org.junit.jupiter:junit-jupiter:5.9.1'
}

Expand All @@ -54,3 +61,11 @@ application {
tasks.named('test') {
useJUnitPlatform()
}

compileJava {
options.encoding = 'UTF-8'
}

compileTestJava {
options.encoding = 'UTF-8'
}
30 changes: 7 additions & 23 deletions app/src/main/java/com/togetherjava/tjplays/Bot.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
package com.togetherjava.tjplays;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.Properties;

import com.togetherjava.tjplays.listeners.commands.*;

import net.dv8tion.jda.api.JDA;
Expand All @@ -13,27 +11,15 @@

public final class Bot {
public static void main(String[] args) throws IOException {
Properties properties = readProperties(args);

String botToken = properties.getProperty("BOT_TOKEN");
String chatGptToken = properties.getProperty("OPEN_AI_TOKEN");
Config config = Config.readConfig(args.length == 0 ? null : Path.of(args[0]));

createJDA(botToken);
createBot(config);
}

private static Properties readProperties(String... args) throws IOException {
Properties properties = new Properties();
private static JDA createBot(Config config) {
JDA jda = JDABuilder.createDefault(config.botToken()).build();

String configPath = args.length == 0 ? "app/src/bot-config.properties" : args[0];
properties.load(new FileInputStream(configPath));

return properties;
}

private static JDA createJDA(String botToken) {
JDA jda = JDABuilder.createDefault(botToken).build();

List<SlashCommand> commands = getCommands();
List<SlashCommand> commands = getCommands(config);
commands.forEach(command -> jda.addEventListener(command));

List<SlashCommandData> commandDatas = commands.stream()
Expand All @@ -45,12 +31,10 @@ private static JDA createJDA(String botToken) {
return jda;
}

private static List<SlashCommand> getCommands() {
private static List<SlashCommand> getCommands(Config config) {
return List.of(
new PingCommand(),
new GuessLanguageCommand(),
new Game2048Command()

);
}
}
28 changes: 28 additions & 0 deletions app/src/main/java/com/togetherjava/tjplays/Config.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.togetherjava.tjplays;

import java.util.Properties;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public final record Config(
@NotNull String botToken,
@NotNull String openAIApiKey
) {
private static final String DEFAULT_PATH = "bot-config.properties";

public static Config readConfig(@Nullable Path configPath) throws IOException {
Properties properties = new Properties();

configPath = configPath == null ? Path.of(DEFAULT_PATH) : configPath;
properties.load(new FileInputStream(configPath.toString()));

return new Config(
properties.getProperty("BOT_TOKEN"),
properties.getProperty("OPENAI_API_KEY")
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@

public final class Game2048Command extends SlashCommand {
private static final String COMMAND_NAME = "2048";
private static final Emoji RESET_EMOJI = Emoji.fromUnicode("🔃");
private static final Emoji UP_EMOJI = Emoji.fromUnicode("⬆️");
private static final Emoji DELETE_EMOJI = Emoji.fromUnicode("🗑️");
private static final Emoji LEFT_EMOJI = Emoji.fromUnicode("⬅️");
private static final Emoji DOWN_EMOJI = Emoji.fromUnicode("⬇️");
private static final Emoji RIGHT_EMOJI = Emoji.fromUnicode("➡️");

private Map<String, Renderer2048> sessions = new HashMap<>();

public Game2048Command() {
Expand Down Expand Up @@ -71,13 +78,13 @@ else if (buttonId.contains("delete")) {
}

private MessageCreateData gameMessage(Renderer2048 gameRenderer, String playerId) {
Button resetButton = Button.success(COMMAND_NAME + " " + playerId + " reset", Emoji.fromUnicode("🔃"));
Button upButton = Button.primary(COMMAND_NAME + " " + playerId + " up", Emoji.fromUnicode("⬆️"));
Button deleteButton = Button.danger(COMMAND_NAME + " " + playerId + " delete", Emoji.fromUnicode("🗑️"));
Button resetButton = Button.success(COMMAND_NAME + " " + playerId + " reset", RESET_EMOJI);
Button upButton = Button.primary(COMMAND_NAME + " " + playerId + " up", UP_EMOJI);
Button deleteButton = Button.danger(COMMAND_NAME + " " + playerId + " delete", DELETE_EMOJI);

Button leftButton = Button.primary(COMMAND_NAME + " " + playerId + " left", Emoji.fromUnicode("⬅️"));
Button downButton = Button.primary(COMMAND_NAME + " " + playerId + " down", Emoji.fromUnicode("⬇️"));
Button rightButton = Button.primary(COMMAND_NAME + " " + playerId + " right", Emoji.fromUnicode("➡️"));
Button leftButton = Button.primary(COMMAND_NAME + " " + playerId + " left", LEFT_EMOJI);
Button downButton = Button.primary(COMMAND_NAME + " " + playerId + " down", DOWN_EMOJI);
Button rightButton = Button.primary(COMMAND_NAME + " " + playerId + " right", RIGHT_EMOJI);

if (gameRenderer.getGame().getState() != GameState.ONGOING) {
upButton = upButton.asDisabled();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import org.togetherjava.tjbot.config.Config;

import java.time.Duration;
import java.util.List;
Expand Down Expand Up @@ -52,7 +52,7 @@ public class ChatGptService {
/**
* Creates instance of ChatGPTService
*
* @param config needed for token to OpenAI API.
* @param apiKey needed for token to OpenAI API.
*/
public ChatGptService(String apiKey) {
boolean keyIsDefaultDescription = apiKey.startsWith("<") && apiKey.endsWith(">");
Expand All @@ -63,9 +63,7 @@ public ChatGptService(String apiKey) {

openAiService = new OpenAiService(apiKey, TIMEOUT);

ChatMessage setupMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), """
For code supplied for review, refer to the old code supplied rather than
rewriting the code. DON'T supply a corrected version of the code.\s""");
ChatMessage setupMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), "");
ChatCompletionRequest systemSetupRequest = ChatCompletionRequest.builder()
.model(AI_MODEL)
.messages(List.of(setupMessage))
Expand All @@ -85,24 +83,22 @@ public ChatGptService(String apiKey) {
* @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();
}

try {
String instructions = "KEEP IT CONCISE, NOT MORE THAN 280 WORDS";
String questionWithContext = "context: Category %s on a Java Q&A discord server. %s %s"
.formatted(context, instructions, question);
ChatMessage chatMessage = new ChatMessage(ChatMessageRole.USER.value(),
Objects.requireNonNull(questionWithContext));
ChatMessage chatQuestion = new ChatMessage(ChatMessageRole.USER.value(), question);
ChatMessage chatContext = new ChatMessage(ChatMessageRole.USER.value(), context);

ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
.model(AI_MODEL)
.messages(List.of(chatMessage))
.messages(List.of(chatContext, chatQuestion))
.frequencyPenalty(FREQUENCY_PENALTY)
.temperature(TEMPERATURE)
.maxTokens(MAX_TOKENS)
Expand All @@ -111,15 +107,15 @@ public Optional<String[]> ask(String question, String context) {

String response = openAiService.createChatCompletion(chatCompletionRequest)
.getChoices()
.get(0)
.getFirst()
.getMessage()
.getContent();

if (response == null) {
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
Binary file modified gradle/wrapper/gradle-wrapper.jar
Binary file not shown.
3 changes: 2 additions & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
29 changes: 17 additions & 12 deletions gradlew
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,8 @@ done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit

# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
Expand Down Expand Up @@ -133,26 +131,29 @@ location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi

# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
Expand Down Expand Up @@ -197,11 +198,15 @@ if "$cygwin" || "$msys" ; then
done
fi

# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.

# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'

# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.

set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
Expand Down
20 changes: 10 additions & 10 deletions gradlew.bat
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@ set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute

echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2

goto fail

Expand All @@ -57,11 +57,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe

if exist "%JAVA_EXE%" goto execute

echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2

goto fail

Expand Down

0 comments on commit 101b0ab

Please sign in to comment.