Skip to content

Commit

Permalink
refactoring(*)
Browse files Browse the repository at this point in the history
  • Loading branch information
aronbergman committed May 12, 2024
1 parent c9509b6 commit 1ac3180
Show file tree
Hide file tree
Showing 17 changed files with 121 additions and 182 deletions.
35 changes: 5 additions & 30 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,22 +15,9 @@ import authRoutes from './api/routes/auth.routes.js'
import userRoutes from './api/routes/user.routes.js'
import subsRoutes from './api/routes/subs.routes.js'
import {
COMMAND_ACCOUNT_EN,
COMMAND_ACCOUNT_FR,
COMMAND_ACCOUNT_RU,
COMMAND_DALL_E,
COMMAND_FILE_CONVERTOR_EN,
COMMAND_FILE_CONVERTOR_FR,
COMMAND_FILE_CONVERTOR_RU,
COMMAND_GPT,
COMMAND_HELP_EN,
COMMAND_HELP_FR,
COMMAND_HELP_RU,
COMMAND_MIDJOURNEY,
COMMAND_QUIZ_EN, COMMAND_QUIZ_FR, COMMAND_QUIZ_RU,
COMMAND_TEXT_TO_SPEECH_EN,
COMMAND_TEXT_TO_SPEECH_FR,
COMMAND_TEXT_TO_SPEECH_RU,
REQUEST_TYPES
} from './bot/constants/index.js'
import { keyboardChatGPT } from './bot/commands/keyboard/chat_gpt.js'
Expand Down Expand Up @@ -115,36 +102,24 @@ bot.on('message', async (msg, match) => {
})

switch (msg.text) {
case COMMAND_ACCOUNT_RU:
case COMMAND_ACCOUNT_FR:
case COMMAND_ACCOUNT_EN:
case t('keyboard_acc'):
switchToMode('GPT', msg.chat.id, msg.from)
return keyboardMyAccount(bot, msg)
case COMMAND_GPT:
return keyboardChatGPT(bot, msg)
case COMMAND_FILE_CONVERTOR_FR:
case COMMAND_FILE_CONVERTOR_EN:
case COMMAND_FILE_CONVERTOR_RU:
case t('keyboard_convertor'):
switchToMode('GPT', msg.chat.id, msg.from)
return keyboardConverter(bot, msg)
case COMMAND_MIDJOURNEY:
return keyboardMidjourney(bot, msg)
case COMMAND_TEXT_TO_SPEECH_EN:
case COMMAND_TEXT_TO_SPEECH_RU:
case COMMAND_TEXT_TO_SPEECH_FR:
case t('keyboard_tts'):
return keyboardTextToSpeech(bot, msg)
case COMMAND_DALL_E:
switchToMode('GPT', msg.chat.id, msg.from)
return keyboardDalle(bot, msg)
break
case COMMAND_HELP_RU:
case COMMAND_HELP_EN:
case COMMAND_HELP_FR:
case t('keyboard_help'):
switchToMode('GPT', msg.chat.id, msg.from)
return keyboardHelp(bot, msg, t)
case COMMAND_QUIZ_RU:
case COMMAND_QUIZ_EN:
case COMMAND_QUIZ_FR:
case t('keyboard_quiz'):
switchToMode('GPT', msg.chat.id, msg.from)
return keyboardQuiz(bot, msg, true)
default:
Expand Down
2 changes: 1 addition & 1 deletion bot/commands/hoc/autoRemoveMessage.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export const autoRemoveMessage = async (content, bot, chatId, options, duration = 5000) => {
export const autoRemoveMessage = async (content, bot, chatId, options = {}, duration = 5000) => {
const message = await bot.sendMessage(chatId, `・ \n${content}`, options)
const durationTemplate = '・'

Expand Down
8 changes: 4 additions & 4 deletions bot/commands/keyboard/chat_gpt.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import events from 'events'
import { db } from '../../db/index.js'
import { modesChatGPT } from '../../constants/modes.js'
import { saveAndSendPhoto } from '../../utils/saveAndSendPhoto.js'
import { TYPE_RESPONSE_MJ } from '../../constants/index.js'
import { createStartKeyboardForReplyMarkup } from '../../utils/createStartKeyboard.js'
import { ct } from '../../utils/createTranslate.js'

export const keyboardChatGPT = async (bot, msg) => {
Expand Down Expand Up @@ -99,7 +98,8 @@ export const keyboardChatGPT = async (bot, msg) => {
const msgId = msg.message_id
const options = {
parse_mode: 'HTML',
reply_to_message_id: msgId
reply_to_message_id: msgId,
reply_markup: await createStartKeyboardForReplyMarkup(msg)
}
try {
db.subscriber.findOne({
Expand All @@ -124,7 +124,7 @@ export const keyboardChatGPT = async (bot, msg) => {
{ where: { chat_id: chatId } }
).then(res => {
bot.select_mode = 'GPT'
return sendChatGPT(bot, chatId, options, "assistant")
return sendChatGPT(bot, chatId, options, 'assistant')
})
} else {
db.subscriber.create({
Expand Down
14 changes: 7 additions & 7 deletions bot/commands/keyboard/converter.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Converter } from '../../utils/converter.js'
import { errorMessage } from '../hoc/errorMessage.js'
import { formats } from '../../constants/formatsConterter.js'
import { ct } from '../../utils/createTranslate.js'
import { createStartKeyboardForReplyMarkup } from '../../utils/createStartKeyboard.js'

export const keyboardConverter = async (bot, msg) => {
const t = await ct(msg)
Expand All @@ -11,20 +10,21 @@ export const keyboardConverter = async (bot, msg) => {
).catch(err => console.log(err))

try {
const timeout = setTimeout((chatId, message_id) => {
const timeout = setTimeout(async (msg, message_id) => {
bot.editMessageText(
t('desc_converter'),
{
chat_id: chatId,
chat_id: msg.chat.id,
message_id: message_id,
parse_mode: 'HTML'
parse_mode: 'HTML',
reply_markup: await createStartKeyboardForReplyMarkup(msg)
}).catch(() => {
return true
})
clearTimeout(timeout)
}, 1500, msg.chat.id, accountMessage?.message_id)
}, 1500, msg, accountMessage?.message_id)
} catch (e) {
bot.deleteMessage(msg.chat.id, accountMessage.message_id)
bot.deleteMessage(msg.chat.id, accountMessage.message_id)
return errorMessage(bot, e.message, msg, 'keybourd/converter')
}
}
20 changes: 10 additions & 10 deletions bot/commands/keyboard/dalle.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import events from 'events'
import { PAYOK } from 'payok'
import { nanoid } from 'nanoid'
import dotenv from 'dotenv'
import { keyboardChatGPT } from './chat_gpt.js'
import { COMMAND_GPT } from '../../constants/index.js'
import { db } from '../../db/index.js'
import { ct } from '../../utils/createTranslate.js'
import { keyboardMyAccount } from './my_account.js'
import { createStartKeyboardForReplyMarkup } from '../../utils/createStartKeyboard.js'

dotenv.config({ path: '../.env' })

Expand All @@ -25,8 +24,8 @@ export const keyboardDalle = async (bot, msg) => {
...options,
reply_markup: {
inline_keyboard: [
[{ text: '🏞 Купить подписку', callback_data: `buy_subscription_M_${chatId}` }],
[{ text: 'Выйти', callback_data: `${COMMAND_GPT}_M_${chatId}` }]
[{ text: t('keyboard_buy_subscription'), callback_data: `buy_subscription_M_${chatId}` }],
[{ text: t('exit_key'), callback_data: `${COMMAND_GPT}_M_${chatId}` }]
]
}
}
Expand Down Expand Up @@ -65,7 +64,8 @@ export const keyboardDalle = async (bot, msg) => {
const msgId = msg.message_id
const options = {
parse_mode: 'HTML',
reply_to_message_id: msgId
reply_to_message_id: msgId,
reply_markup: await createStartKeyboardForReplyMarkup(msg)
}
try {
db.subscriber.findOne({
Expand All @@ -74,20 +74,20 @@ export const keyboardDalle = async (bot, msg) => {
user_id: msg.from.id
}
}).then(res => {
if (res?.dataValues.mode?.match(/\DALL-E/))
if (res?.dataValues.mode?.match(/\DALLE/))
return sendDalle(bot, chatId, options)
else if (res?.dataValues.mode) {
db.subscriber.update(
{
mode: 'DALL-E',
mode: 'DALLE',
first_name: msg.from.first_name,
last_name: msg.from.last_name,
username: msg.from.username,
language_code: msg.from.language_code
},
{ where: { chat_id: chatId } }
).then(res => {
bot.select_mode = 'DALL-E'
bot.select_mode = 'DALLE'
return sendDalle(bot, chatId, options)
})
} else {
Expand All @@ -98,9 +98,9 @@ export const keyboardDalle = async (bot, msg) => {
last_name: msg.from.last_name,
username: msg.from.username,
language_code: msg.from.language_code,
mode: 'DALL-E'
mode: 'DALLE'
}).then(res => {
bot.select_mode = 'DALL-E'
bot.select_mode = 'DALLE'
return sendDalle(bot, chatId, options)
})
}
Expand Down
4 changes: 3 additions & 1 deletion bot/commands/keyboard/my_account.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { keyboardQuiz } from './quiz.js'
import Stripe from 'stripe'
import { createFullName } from '../../utils/createFullName.js'
import { numberWithSpaces } from '../../utils/numberWithSpaces.js'
import { createStartKeyboardForReplyMarkup } from '../../utils/createStartKeyboard.js'

dotenv.config({ path: '../.env' })

Expand All @@ -29,7 +30,8 @@ export const keyboardMyAccount = async (bot, msg, prevMessageForEdit, prevLevel,
const generalOptions = {
parse_mode: 'HTML',
reply_to_message_id: msgId,
disable_web_page_preview: true
disable_web_page_preview: true,
reply_markup: await createStartKeyboardForReplyMarkup(msg)
}
try {
const inlineKeyboard = [
Expand Down
11 changes: 3 additions & 8 deletions bot/commands/modes/chatGPT.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import { INITIAL_SESSION } from '../../constants/index.js'
import { INITIAL_SESSION, REQUEST_TYPES } from '../../constants/index.js'
import { OpenAI } from '../../utils/openAi.js'
import { spinnerOff, spinnerOn } from '../../utils/spinner.js'
import { errorMessage } from '../hoc/errorMessage.js'
import { modesChatGPT } from '../../constants/modes.js'
import { db } from '../../db/index.js'
import { exceptionForHistoryLogging } from '../../utils/exceptionForHistoryLogging.js'
import { createFullName } from '../../utils/createFullName.js'
import { calculationOfNumberOfTokens } from '../../utils/checkTokens.js'
import { ct } from '../../utils/createTranslate.js'
import { Sequelize } from 'sequelize'
import { writingOffTokens } from '../../utils/checkTokens.js'

export const modeChatGPT = async (bot, msg, qweryOptions) => {
const t = await ct(msg)
Expand Down Expand Up @@ -64,12 +63,8 @@ export const modeChatGPT = async (bot, msg, qweryOptions) => {
const response = await openAi.chat(msg?.ctx.messages, bot, message, chatID, x.parse_mode)

const textSum = (response + newMessage)
const tokenCounts = await calculationOfNumberOfTokens(textSum)

await db.subscriber.update(
{ tokens: Sequelize.literal(`tokens - ${tokenCounts}`) },
{ where: { chat_id: chatID } }
)
await writingOffTokens(bot, msg, REQUEST_TYPES.GPT, textSum)

if (!response) {
throw new Error('Something went wrong please try again.')
Expand Down
17 changes: 4 additions & 13 deletions bot/commands/modes/midjourney.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import { Midjourney } from 'midjourney'
import { saveAndSendPhoto, saveAndSendPreloaderPhoto } from '../../utils/saveAndSendPhoto.js'
import { saveAndSendPreloaderPhoto } from '../../utils/saveAndSendPhoto.js'
import { loaderOn } from '../../utils/loader.js'
import { REQUEST_TYPES_COST, TYPE_RESPONSE_MJ } from '../../constants/index.js'
import { REQUEST_TYPES } from '../../constants/index.js'
import { upscale } from './midjourney/upscale.js'
import events from 'events'
import { variation } from './midjourney/variation.js'
import dotenv from 'dotenv'
import { calculationOfNumberOfTokens } from '../../utils/checkTokens.js'
import { db } from '../../db/index.js'
import { Sequelize } from 'sequelize'
import { writingOffTokens } from '../../utils/checkTokens.js'

dotenv.config()

Expand Down Expand Up @@ -85,14 +83,7 @@ export const modeMidjourney = async (bot, sudoUser, msg, match) => {
const imgDir = './Imagines'
const filePath = `${imgDir}/${userMessageId}.png`

const prevMessage = await saveAndSendPhoto(imgUrl, imgDir, filePath, chatID, bot, options, TYPE_RESPONSE_MJ.PHOTO, waiting)

const tokenCounts = await calculationOfNumberOfTokens(' ', REQUEST_TYPES_COST.MIDJOURNEY)

await db.subscriber.update(
{ tokens: Sequelize.literal(`tokens - ${tokenCounts}`) },
{ where: { chat_id: chatID } }
)
await writingOffTokens(bot, msg, REQUEST_TYPES.MIDJOURNEY)

for (let i = 1; i < 5; i++) {
eventEmitter.on(`V${i}++${waiting.message_id}`, async function(query) {
Expand Down
16 changes: 4 additions & 12 deletions bot/commands/modes/modeDalle.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ import dotenv from 'dotenv'
import { saveAndSendPhoto } from '../../utils/saveAndSendPhoto.js'
import { sudoChecker } from '../../utils/sudoChecker.js'
import { spinnerOn } from '../../utils/spinner.js'
import { REQUEST_TYPES_COST, TYPE_RESPONSE_MJ } from '../../constants/index.js'
import { REQUEST_TYPES, TYPE_RESPONSE_MJ } from '../../constants/index.js'
import { loaderOn } from '../../utils/loader.js'
import { OpenAI } from '../../utils/openAi.js'
import { calculationOfNumberOfTokens } from '../../utils/checkTokens.js'
import { db } from '../../db/index.js'
import { Sequelize } from 'sequelize'
import { writingOffTokens } from '../../utils/checkTokens.js'

dotenv.config()

Expand Down Expand Up @@ -48,21 +46,15 @@ export const modeDalle = async (bot, sudoUser, msg, match) => {

const response = await openAi.image(prompt)

const tokenCounts = await calculationOfNumberOfTokens(' ', REQUEST_TYPES_COST.DALLE)

await db.subscriber.update(
{ tokens: Sequelize.literal(`tokens - ${tokenCounts}`) },
{ where: { chat_id: chatID } }
)

const imgUrl = response
const imgDir = './dalle'
const filePath = `${imgDir}/${userMessageId}.png`

await loaderOn('42%', bot, chatID, waiting?.message_id)
await loaderOn('78%', bot, chatID, waiting?.message_id)

await saveAndSendPhoto(imgUrl, imgDir, filePath, chatID, bot, options, TYPE_RESPONSE_MJ.PHOTO, spinner,
waiting)
await writingOffTokens(bot, msg, REQUEST_TYPES.DALLE)
await bot.deleteMessage(chatID, waiting.message_id).catch()
} catch (error) {
await bot.deleteMessage(chatID, spinner)
Expand Down
13 changes: 4 additions & 9 deletions bot/commands/onMessageDocument.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ import { formats, formatsConvertor } from '../constants/formatsConterter.js'
import { stepperOn } from '../utils/stepper.js'
import { sleep } from '../utils/sleep.js'
import { db } from '../db/index.js'
import { Op, Sequelize } from 'sequelize'
import { Op } from 'sequelize'
import { nanoid } from 'nanoid'
import { ct } from '../utils/createTranslate.js'
import { calculationOfNumberOfTokens } from '../utils/checkTokens.js'
import { REQUEST_TYPES_COST } from '../constants/index.js'
import { REQUEST_TYPES } from '../constants/index.js'
import { writingOffTokens } from '../utils/checkTokens.js'

// TODO: определять тип файла от типа в meta telegram

Expand Down Expand Up @@ -128,12 +128,7 @@ export const onMessageDocument = async (bot, msg) => {
price_tokens: settings['cost_converter']
})

const tokenCounts = await calculationOfNumberOfTokens(' ', REQUEST_TYPES_COST.CONVERTOR)

await db.subscriber.update(
{ tokens: Sequelize.literal(`tokens - ${tokenCounts}`) },
{ where: { chat_id: msg.from.id } }
)
await writingOffTokens(bot, msg, REQUEST_TYPES.CONVERTOR)

await bot.deleteMessage(msg.from.id, msg.message.message_id).catch((error) => console.log('error dm', error))
const waiting = await stepperOn(bot, msg, 0) // верочтно логичнее будет сохранить прошлое сообщение msg.message.message_id
Expand Down
Loading

0 comments on commit 1ac3180

Please sign in to comment.