From 2482fbbbed84d83d27a4c6c74a519382ff075226 Mon Sep 17 00:00:00 2001 From: Dmitry Alekseev Date: Tue, 31 Oct 2023 17:16:25 +0400 Subject: [PATCH] Small code quality improvements --- package.json | 2 +- src/bot.ts | 12 +++++----- src/config.ts | 44 +++++++++++++++++----------------- src/index.ts | 3 ++- src/scenes/dialog/handlers.ts | 9 +++---- src/scenes/settings/actions.ts | 6 ++--- src/scenes/settings/index.ts | 5 ++-- src/services/Translation.ts | 7 ++---- src/services/index.ts | 6 +++-- src/services/openai.ts | 12 +++++++--- 10 files changed, 55 insertions(+), 51 deletions(-) diff --git a/package.json b/package.json index 82cd50b..0dcd5cf 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "gptitor", - "version": "1.3.1", + "version": "1.3.3", "description": "", "main": "src/index.ts", "scripts": { diff --git a/src/bot.ts b/src/bot.ts index 46d794f..f8ddde9 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -89,12 +89,12 @@ export default class Bot extends Telegraf { }; await Datastore.init(); - await Midjourney.init({ - ServerId: DISCORD_SERVER_ID!, - ChannelId: DISCORD_CHANNEL_ID!, - SalaiToken: DISCORD_SALAI_TOKEN!, - Debug: isDev - }); + // await Midjourney.init({ + // ServerId: DISCORD_SERVER_ID!, + // ChannelId: DISCORD_CHANNEL_ID!, + // SalaiToken: DISCORD_SALAI_TOKEN!, + // Debug: isDev + // }); for (const lang of this.botServices.translation.supportedLangs) { const $t = this.botServices.translation.getTranslator(lang); diff --git a/src/config.ts b/src/config.ts index 1336b00..23eaf4c 100644 --- a/src/config.ts +++ b/src/config.ts @@ -27,28 +27,28 @@ const config = { maxTokens: 4096 }, functions: [ - { - name: "generateImage", - description: "Generate an image from a user's prompt. Can be called only when user explicitly asks for an image", - parameters: { - type: "object", - properties: { - prompt: { - type: "string", - description: "Clear and concise prompt string in English language without verbs that describes the image to be generated" - } - }, - required: ["prompt"] - }, - }, - { - name: "describeImage", - description: "Describe in human readable format what is depicted on provided image", - parameters: { - type: "object", - properties: {} - } - } + // { + // name: "generateImage", + // description: "Generate an image from a user's prompt. Can be called only when user explicitly asks for an image", + // parameters: { + // type: "object", + // properties: { + // prompt: { + // type: "string", + // description: "Clear and concise prompt string in English language without verbs that describes the image to be generated" + // } + // }, + // required: ["prompt"] + // }, + // }, + // { + // name: "describeImage", + // description: "Describe in human readable format what is depicted on provided image", + // parameters: { + // type: "object", + // properties: {} + // } + // } ], userQuota: { startTokens: 10000, diff --git a/src/index.ts b/src/index.ts index a70fb9e..ceef2ba 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,7 @@ import "dotenv/config"; import * as fs from "fs"; import express from "express"; +import { type AxiosError } from 'axios'; import d from "debug"; import Bot from "./bot"; @@ -29,7 +30,7 @@ app.post("/bot", async (request, response, next) => { (error as Error).message, (error as Error).stack, request.body, - (error as any).response?.data + (error as AxiosError).response?.data ); log.write(`Error: ${JSON.stringify(error, null, 2)}\nRequest: ${request.body}`, "utf-8"); } diff --git a/src/scenes/dialog/handlers.ts b/src/scenes/dialog/handlers.ts index 1dd5809..3328950 100644 --- a/src/scenes/dialog/handlers.ts +++ b/src/scenes/dialog/handlers.ts @@ -11,7 +11,7 @@ const debug = d("bot:dialog"); export async function onPhoto(ctx: BotContext, next: () => Promise) { const message = ctx.message as Message.PhotoMessage & Message.TextMessage; - message.photo = [message.photo.sort((photoA, photoB) => photoB.file_size! - photoA.file_size!)[0]]; + message.photo = message.photo.sort((photoA, photoB) => photoB.file_size! - photoA.file_size!).slice(0, 0); message.text = message.caption ?? ""; return next(); @@ -90,11 +90,8 @@ async function answer(ctx: BotContext, conversation: ChatCompletionRequestMessag if (content) { for (const answer of format(content)) { - const reply = await ctx.replyWithMarkdownV2(answer, { - reply_to_message_id: msg.reply_to_message ? msg.message_id : undefined - }); - - ctx.conversation.save(msg, reply, conversation[conversation.length - 1].content!, answer); + const reply = await ctx.replyWithMarkdownV2(answer, { reply_to_message_id: msg.message_id }); + ctx.conversation.save(msg, reply, conversation[conversation.length - 1].content!, content); } } } diff --git a/src/scenes/settings/actions.ts b/src/scenes/settings/actions.ts index 3a5b3aa..c270f42 100644 --- a/src/scenes/settings/actions.ts +++ b/src/scenes/settings/actions.ts @@ -12,7 +12,7 @@ export default { async model(ctx: BotContext) { const models = await ctx.openai.getModels(); - return ctx.editMessageReplyMarkup(Markup.inlineKeyboard( + await ctx.editMessageReplyMarkup(Markup.inlineKeyboard( models.map(model => Markup.button.callback(model, `selectModel:${model}`)), { columns: 3 } ).reply_markup); @@ -30,7 +30,7 @@ export default { .sort((a, b) => parseFloat(a[0]) - parseFloat(b[0])) .map(([id, label]) => Markup.button.callback(label, `setTemperature:${id}`)); - return ctx.editMessageReplyMarkup(Markup.inlineKeyboard(buttons, { columns: 2 }).reply_markup); + await ctx.editMessageReplyMarkup(Markup.inlineKeyboard(buttons, { columns: 2 }).reply_markup); }, async setTemperature(ctx: BotContext, selectedLevel: string) { @@ -57,4 +57,4 @@ export default { // return ctx.scene.reenter(); // } -} as const; \ No newline at end of file +} as Record Promise>; diff --git a/src/scenes/settings/index.ts b/src/scenes/settings/index.ts index 56851ff..d33fdd6 100644 --- a/src/scenes/settings/index.ts +++ b/src/scenes/settings/index.ts @@ -44,10 +44,11 @@ scene.enter(async (ctx) => { scene.action(/^(\w+)(?::(.+))?$/, async (ctx) => { const [, action, param] = ctx.match; + const actionHandler = actions[action as keyof typeof actions]; await ctx.answerCbQuery(); - if (actions[action as keyof typeof actions]) { - await actions[action as keyof typeof actions](ctx, param as any); + if (actionHandler) { + await actionHandler(ctx, param); } }); diff --git a/src/services/Translation.ts b/src/services/Translation.ts index e02c3e6..941219e 100644 --- a/src/services/Translation.ts +++ b/src/services/Translation.ts @@ -1,6 +1,5 @@ import { default as en } from "../lang/en"; import { default as ru } from "../lang/ru"; -import config from "../config"; export type LangName = keyof typeof langs; export type LangStringKey = keyof typeof en; @@ -13,11 +12,9 @@ export default class Translation { return Object.keys(langs) as LangName[]; } - getTranslator(lang: string): Translator { - const strings = langs[lang as LangName] ?? langs[config.defaultLang]; - // return new Translation(strings); + getTranslator(lang: LangName): Translator { return (key, tokens) => { - const text = strings[key]; + const text = langs[lang][key]; if (typeof text === "function") { return text(tokens as any); } diff --git a/src/services/index.ts b/src/services/index.ts index 80c5f04..fe3063e 100644 --- a/src/services/index.ts +++ b/src/services/index.ts @@ -1,10 +1,12 @@ import Bot, { type BotContext } from "../bot"; +import config from "../config"; import Datastore from "./Datastore"; import OpenAI from "./OpenAI"; import Quota from "./Quota"; import Settings from "./Settings"; import Midjourney from "./Midjourney"; +import { type LangName } from "./Translation"; export { default as Datastore } from "./Datastore"; export { default as OpenAI } from "./OpenAI"; @@ -12,7 +14,7 @@ export { default as Quota, type UserQuota } from "./Quota"; export { default as Settings, type ChatSettings } from "./Settings"; export { default as Conversation } from "./Conversation"; export { default as Midjourney, type Generation, type GeneratedImage } from "./Midjourney"; -export { default as Translation, type Translator } from "./Translation"; +export { default as Translation, type Translator, type LangName } from "./Translation"; export function services(bot: Bot) { const { OPENAI_KEY } = process.env; @@ -29,7 +31,7 @@ export function services(bot: Bot) { ctx.settings = new Settings(ctx.session); ctx.timestamp = Date.now(); ctx.host = bot.host!; - ctx.$t = translation.getTranslator(ctx.from?.language_code!); + ctx.$t = translation.getTranslator(ctx.from?.language_code as LangName || config.defaultLang); await next(); } diff --git a/src/services/openai.ts b/src/services/openai.ts index 3331bba..2333d69 100644 --- a/src/services/openai.ts +++ b/src/services/openai.ts @@ -1,4 +1,10 @@ -import { Configuration, OpenAIApi, ChatCompletionRequestMessage, CreateChatCompletionResponseChoicesInner } from "openai"; +import { + Configuration, + OpenAIApi, + ChatCompletionRequestMessage, + CreateChatCompletionResponseChoicesInner +} from "openai"; +import { type AxiosError } from 'axios'; import { Readable } from "stream"; import d from "debug"; @@ -39,9 +45,9 @@ export default class OpenAI { return data.choices; } catch (error) { - debug("createChatCompletion error", (error as any).response?.data ?? (error as Error).message); + debug("createChatCompletion error", (error as AxiosError).response?.data ?? (error as Error).message); - const message = (error as any).response?.data?.error?.message; + const message = (error as AxiosError).response?.data?.error?.message; return message ? [{ message: { content: message, role: "system" }, finish_reason: "error" }] : [];