Skip to content

Commit

Permalink
removes chatgpt entirely, and fixes startup not working
Browse files Browse the repository at this point in the history
  • Loading branch information
Chr1s70ph committed Oct 22, 2024
1 parent eed701d commit ea309c4
Show file tree
Hide file tree
Showing 7 changed files with 3 additions and 190 deletions.
2 changes: 0 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ Clone the repository, `cd` into it and run `npm install`.
## ➤ Features

- [x] Calendar
- [x] ChatGPT
- [x] Exams
- [x] Mensa
- [x] Multi Language Support
Expand Down Expand Up @@ -58,6 +57,5 @@ The only required value is `botToken`, which you can get from the [Discord Devel
"calendar_2": "<your calendar url>",
},
"botToken": "<your bot token>",
"openai_token": "<your openai token>",
}
```
151 changes: 1 addition & 150 deletions events/messageCreate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,94 +2,12 @@ import { EmbedBuilder, MessageCreateOptions, MessagePayload, TextChannel } from
import tx2 from 'tx2'
import { DiscordClient, DiscordMessage } from '../types/customTypes'

/**
* Custom PM2 metric.
*/
const openai_api_requests = tx2.counter('OpenAI-API Requests')

exports.run = (client: DiscordClient, message: DiscordMessage) => {
/**
* Only respond to messages sent by users.
*/
if (message.author.bot) return

/**
* OpenAI's Chat-GPT
*/
if (message.channel.isThread() && message.channel.name === 'chat-gpt') {
try {
let requestDone = false
let openai_api_request_sent = false

console.log(`Chat-GPT request, by: ${message.author.username}`)
/**
* Function to wait for the API response and send typing.
*/
const awaiting_api_reposonse = () => {
setTimeout(() => {
/**
* Send typing indicator.
*/
message.channel.sendTyping()

if (openai_api_request_sent === false) {
openai_api_request_sent = true
client.openai.chat.completions
.create({
model: 'gpt-3.5-turbo',
messages: [{ role: 'user', content: message.content.toString() }],
})
.then(request => {
/**
* Set requestDone to true, so the request doesn't get sent again.
*/
requestDone = true

/**
* Split the message into multiple messages if it's too long.
*/
splitMessageRegex(request.choices[0].message.content.toString(), {
maxLength: 2000,
prepend: '',
append: '',
}).forEach((element: string | MessagePayload | MessageCreateOptions) => {
message.channel.send(element)
})

openai_api_requests.inc(1)
console.log(`Chat-GPT request done. Request by: ${message.author.username}`)
})
}
if (requestDone === false) {
/**
* If the request is not done, wait 1 second and send typing again.
*/
awaiting_api_reposonse()
}
}, 1000)
}

awaiting_api_reposonse()
} catch (error) {
if (error.response) {
console.log(`Error status: ${error.response.status}`)
console.log(`Error data: ${error.response.data}`)
message.channel.send(
client.translate({
key: 'interactions.chatgpt.error',
options: {
error_status: error.response.status,
error_data: error.response.data,
lng: message.author.language,
},
}),
)
} else {
console.log(`Error message: ${error.message}`)
}
}
}

/**
* DM handling and forwarding.
*/
Expand Down Expand Up @@ -132,71 +50,4 @@ exports.run = (client: DiscordClient, message: DiscordMessage) => {
throw new Error(error)
}
}
}


/**
* A function for splitting a string into fixed-length parts. Designed as a
* workaround to an issue in the discord.js Util.splitMessage function
* https://github.com/discordjs/discord.js/issues/7674
* @param {string} text The string to split into multiple messages, each of
* which will be no longer than maxLength
* @param {number} [options.maxLength] The maximum number of characters in each
* string in the returned array
* @param {RegExp} [options.regex] A global regex which matches the delimeters on
* which to split text when needed to keep each part within maxLength
* @param {string} [options.prepend] A string to add before each part iff
* text is split into multiple parts
* @param {string} [options.append] A string to add after each part iff text
* is split into multiple parts
* @returns {string[]} An array of strings which are substrings of text, split
* using options.regex, combined such that each part is as long as possible
* while not exceeding options.maxLength.
*/
function splitMessageRegex(
text: string,
{
maxLength = 2_000,
regex = /\n/g,
prepend = '',
append = '',
}: { maxLength?: number; regex?: RegExp; prepend?: string; append?: string } = {},
): any[] {
if (text.length <= maxLength) return [text]
const parts = []
let curPart = prepend
let chunkStartIndex = 0

let prevDelim = ''

function addChunk(chunkEndIndex: number, nextDelim: string) {
const nextChunk = text.substring(chunkStartIndex, chunkEndIndex)
const nextChunkLen = nextChunk.length

// If a single part would exceed the length limit by itself, throw an error:
if (prepend.length + nextChunkLen + append.length > maxLength) {
throw new RangeError('SPLIT_MAX_LEN')
}

// The length of the current part if the next chunk were added to it:
const lengthWithChunk = curPart.length + prevDelim.length + nextChunkLen + append.length

// If adding the next chunk to the current part would cause it to exceed
// the maximum length, push the current part and reset it for next time:
if (lengthWithChunk > maxLength) {
parts.push(curPart + append)
curPart = prepend + nextChunk
} else {
curPart += prevDelim + nextChunk
}
prevDelim = nextDelim
chunkStartIndex = chunkEndIndex + prevDelim.length
}

for (const match of text.matchAll(regex)) {
addChunk(match.index, match[0])
}
addChunk(text.length - 1, '')
parts.push(curPart + append)
return parts
}
}
14 changes: 0 additions & 14 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import * as fs from 'fs'
import { Collection, GatewayIntentBits, Partials } from 'discord.js'
import i18next from 'i18next'
import Backend from 'i18next-fs-backend'
import OpenAI from 'openai'
import ids from './private/ids.json'
import sensitive from './private/sensitive.json'
import settings from './private/settings.json'
Expand Down Expand Up @@ -65,19 +64,6 @@ client.config = {
*/
client.login(client.config.sensitive.botToken)

if (client.config.sensitive.openai_token) {
/*
* Create OpenAIApi instance
*/


client.openai = new OpenAI({
apiKey: client.config.sensitive.openai_token
})
} else {
console.error('client.config.sensitive.openai_token is undefined')
}

/**
* Load and run events.
*/
Expand Down
11 changes: 1 addition & 10 deletions locales/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,6 @@
"parent": "Oberkategorie",
"type": "Typ"
},
"chatgpt": {
"already_in_thread": "Ich kann keinen Thread erstellen, da du dich bereits in einem befindest.",
"cannot_create_thread": "*Chat-GPT* Thread konnte nicht erstellt werden.",
"error": "Ein Fehler ist aufgetreten. Bitte versuche es später erneut.\nWenn dieser Fehler weiterhin besteht, kontaktiere bitte den Bot-Entwickler.\n\nFehler Status: {{error}}\nFehler Daten: {{error_data}}",
"localized_description": "chats in gpt",
"localized_name": "chatgpt",
"thread_created": "*Chat-GPT* Thread erstellt!",
"thread_message": "Chat-GPT liegt zu deinen Füßen, du kannst mich alles fragen.\nNach 60min wird der Kanal archiviert"
},
"fact": {
"fact": "🧠Fakt",
"localized_description": "Spuckt einen zufälligen Fakt aus.",
Expand Down Expand Up @@ -142,4 +133,4 @@
},
"language": "Deutsch",
"missingPermission": "Du bist nicht berechtigt, diesen Befehl auszuführen."
}
}
11 changes: 1 addition & 10 deletions locales/en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,6 @@
"parent": "Parent",
"type": "Type"
},
"chatgpt": {
"already_in_thread": "Cannot create thread since you already are in a thread channel.",
"cannot_create_thread": "Cannot create *Chat-GPT* thread.",
"error": "An error occured. Please try again later.\nIf this error persists, please contact the bot owner.\n\nError Status: {{error}}\nError data: {{error_data}}",
"localized_description": "chats in gpt",
"localized_name": "chatgpt",
"thread_created": "*Chat-GPT* thread successfully created!",
"thread_message": "Chat-GPT at your service, ask me anything.\nAfter 60mins of inactivity this channel will be archived."
},
"fact": {
"fact": "🧠Fact",
"localized_description": "Spits out a random fact.",
Expand Down Expand Up @@ -142,4 +133,4 @@
},
"language": "English",
"missingPermission": "You do not have permission to perform that command."
}
}
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
"moment-timezone": "^0.5.46",
"node-ical": "^0.19.0",
"node-schedule": "^2.1.1",
"openai": "^4.68.1",
"os": "^0.1.2",
"pm2": "^5.4.2",
"tenorjs": "^1.0.10",
Expand Down
3 changes: 0 additions & 3 deletions types/customTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import {
} from 'discord.js'
import i18next, { TOptions } from 'i18next'
import { CalendarResponse } from 'node-ical'
import OpenAI from 'openai'

/**
* Extended version of the default {@link Client} with addidtional functions and properties.
Expand Down Expand Up @@ -126,7 +125,6 @@ export class DiscordClient extends Client {
*/
public interactions: Collection<string, InteractionCommands>

public openai: OpenAI
/**
* Uses {@link Message.reply()} to reply to the issued command.
* @param {Message} message message to ryply to
Expand Down Expand Up @@ -393,7 +391,6 @@ interface config_sensitive_typing {
}
calendars: { [key: string]: string }
botToken: string
openai_token?: string
}

interface config_ids_typing {
Expand Down

0 comments on commit ea309c4

Please sign in to comment.