Skip to content

Commit c9509b6

Browse files
committed
feat(*): fix subtraction tokens and mi
1 parent 03815d9 commit c9509b6

File tree

11 files changed

+67
-19
lines changed

11 files changed

+67
-19
lines changed

README.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,10 @@ quiz_requests
2424
В будущем дать возможность отправлять все новые запросы из таждой таблицы на обработку, в порядке их сохранения.
2525
В будущем не отправлять больше 5 запросов подряд в Mi. и посмотреть ограничения по OpenAI.
2626

27-
Проверить с Максимом как ведет себя бот если 2 пользователя делают одновременно одинаковые действия, пересеаются ли реквизиты.
27+
Проверить с Максимом как ведет себя бот если 2 пользователя делают одновременно одинаковые действия, пересеаются ли реквизиты.
28+
29+
Баги
30+
при выбранном миджорни нужно менять режим если выбрана кнопка смены режима
31+
в конверторе не падает огибка
32+
в конверторе если долго статус wokr тоже сбрасывать как refund
33+
перенести переводы в таблицы

bot/commands/admin/refundTokensIfError.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { INITIAL_SESSION } from '../../constants/index.js'
22
import { db } from '../../db/index.js'
3-
import { Sequelize } from 'sequelize'
3+
import { Op, Sequelize } from 'sequelize'
44
import { ct } from '../../utils/createTranslate.js'
55

66
export const refundTokensIfError = bot => {
@@ -16,7 +16,7 @@ export const refundTokensIfError = bot => {
1616
}
1717
msg['ctx'] = INITIAL_SESSION
1818
try {
19-
const errors = await db.convertor_requests.findAll({ where: { status: 'error' } })
19+
const errors = await db.convertor_requests.findAll({ where: { [Op.or]: [{ status: 'work' }, { status: 'error' }] } })
2020

2121
if (errors.length) {
2222
errors.map(async error => {

bot/commands/keyboard/my_account.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { referralLevelCreator } from '../../utils/payments/referralLevelCreator.
99
import { keyboardQuiz } from './quiz.js'
1010
import Stripe from 'stripe'
1111
import { createFullName } from '../../utils/createFullName.js'
12+
import { numberWithSpaces } from '../../utils/numberWithSpaces.js'
1213

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

@@ -97,7 +98,7 @@ export const keyboardMyAccount = async (bot, msg, prevMessageForEdit, prevLevel,
9798

9899
eventEmitter.on(`get_first_level_A_${msgId}`, async function() {
99100
await bot.editMessageText(
100-
t('account', { tokens, paid_days }),
101+
t('account', { tokens: numberWithSpaces(tokens), paid_days }),
101102
{
102103
message_id: accountMessage.message_id,
103104
chat_id: chatId,
@@ -218,7 +219,7 @@ Payok - оплачивайте следующими способами:
218219
}).then(res => {
219220
clearTimeout(timeout)
220221
bot.editMessageText(
221-
changeDescription ? changeDescription : t('account', { tokens, paid_days }),
222+
changeDescription ? changeDescription : t('account', { tokens: numberWithSpaces(tokens), paid_days }),
222223
{
223224
message_id: accountMessage.message_id,
224225
chat_id: chatId,

bot/commands/modes/chatGPT.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,8 @@ export const modeChatGPT = async (bot, msg, qweryOptions) => {
6767
const tokenCounts = await calculationOfNumberOfTokens(textSum)
6868

6969
await db.subscriber.update(
70-
{ tokens: Sequelize.literal(`tokens - ${tokenCounts.length}`) },
71-
{ where: { user_id: chatID } }
70+
{ tokens: Sequelize.literal(`tokens - ${tokenCounts}`) },
71+
{ where: { chat_id: chatID } }
7272
)
7373

7474
if (!response) {

bot/commands/modes/midjourney.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
import { Midjourney } from 'midjourney'
22
import { saveAndSendPhoto, saveAndSendPreloaderPhoto } from '../../utils/saveAndSendPhoto.js'
33
import { loaderOn } from '../../utils/loader.js'
4-
import { TYPE_RESPONSE_MJ } from '../../constants/index.js'
4+
import { REQUEST_TYPES_COST, TYPE_RESPONSE_MJ } from '../../constants/index.js'
55
import { upscale } from './midjourney/upscale.js'
66
import events from 'events'
77
import { variation } from './midjourney/variation.js'
88
import dotenv from 'dotenv'
9+
import { calculationOfNumberOfTokens } from '../../utils/checkTokens.js'
10+
import { db } from '../../db/index.js'
11+
import { Sequelize } from 'sequelize'
912

1013
dotenv.config()
1114

@@ -84,6 +87,13 @@ export const modeMidjourney = async (bot, sudoUser, msg, match) => {
8487

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

90+
const tokenCounts = await calculationOfNumberOfTokens(' ', REQUEST_TYPES_COST.MIDJOURNEY)
91+
92+
await db.subscriber.update(
93+
{ tokens: Sequelize.literal(`tokens - ${tokenCounts}`) },
94+
{ where: { chat_id: chatID } }
95+
)
96+
8797
for (let i = 1; i < 5; i++) {
8898
eventEmitter.on(`V${i}++${waiting.message_id}`, async function(query) {
8999
await variation(prompt, Imagine, client, query, bot, chatID, prevMessage.message_id, userMessageId)

bot/commands/modes/midjourney/upscale.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,10 @@ export const upscale = async (Variation, client, query, bot, chatID, prevMessage
1717
let waiting = await loaderOn(0, bot, chatID)
1818

1919
try {
20-
if (prevMessageId)
21-
await bot.deleteMessage(chatID, prevMessageId).catch(() => {
22-
console.log('🔺 upscale | error remove loader ', prevMessageId)
23-
})
20+
// if (prevMessageId)
21+
// await bot.deleteMessage(chatID, prevMessageId).catch(() => {
22+
// console.log('🔺 upscale | error remove loader ', prevMessageId)
23+
// })
2424

2525
const upscaleLabel = query.data
2626
const selectedL = upscaleLabel.split('+')[0]

bot/commands/modes/midjourney/variation.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,10 @@ export const variation = async (prompt, Imagine, client, query, bot, chatID, pre
1010
let waiting = await loaderOn(0, bot, chatID)
1111

1212
try {
13-
if (prevMessageId)
14-
await bot.deleteMessage(chatID, prevMessageId).catch(() => {
15-
console.log("🔺 variation | error remove loader ", prevMessageId)
16-
})
13+
// if (prevMessageId)
14+
// await bot.deleteMessage(chatID, prevMessageId).catch(() => {
15+
// console.log("🔺 variation | error remove loader ", prevMessageId)
16+
// })
1717

1818
const { id: chat_id, title: chat_name } = query.message.chat
1919
const { message_id } = query.message

bot/commands/modes/modeDalle.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,12 @@ import dotenv from 'dotenv'
22
import { saveAndSendPhoto } from '../../utils/saveAndSendPhoto.js'
33
import { sudoChecker } from '../../utils/sudoChecker.js'
44
import { spinnerOn } from '../../utils/spinner.js'
5-
import { TYPE_RESPONSE_MJ } from '../../constants/index.js'
5+
import { REQUEST_TYPES_COST, TYPE_RESPONSE_MJ } from '../../constants/index.js'
66
import { loaderOn } from '../../utils/loader.js'
77
import { OpenAI } from '../../utils/openAi.js'
8+
import { calculationOfNumberOfTokens } from '../../utils/checkTokens.js'
9+
import { db } from '../../db/index.js'
10+
import { Sequelize } from 'sequelize'
811

912
dotenv.config()
1013

@@ -45,6 +48,13 @@ export const modeDalle = async (bot, sudoUser, msg, match) => {
4548

4649
const response = await openAi.image(prompt)
4750

51+
const tokenCounts = await calculationOfNumberOfTokens(' ', REQUEST_TYPES_COST.DALLE)
52+
53+
await db.subscriber.update(
54+
{ tokens: Sequelize.literal(`tokens - ${tokenCounts}`) },
55+
{ where: { chat_id: chatID } }
56+
)
57+
4858
const imgUrl = response
4959
const imgDir = './dalle'
5060
const filePath = `${imgDir}/${userMessageId}.png`

bot/commands/onMessageDocument.js

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,11 @@ import { formats, formatsConvertor } from '../constants/formatsConterter.js'
99
import { stepperOn } from '../utils/stepper.js'
1010
import { sleep } from '../utils/sleep.js'
1111
import { db } from '../db/index.js'
12-
import { Op } from 'sequelize'
12+
import { Op, Sequelize } from 'sequelize'
1313
import { nanoid } from 'nanoid'
1414
import { ct } from '../utils/createTranslate.js'
15+
import { calculationOfNumberOfTokens } from '../utils/checkTokens.js'
16+
import { REQUEST_TYPES_COST } from '../constants/index.js'
1517

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

@@ -126,7 +128,12 @@ export const onMessageDocument = async (bot, msg) => {
126128
price_tokens: settings['cost_converter']
127129
})
128130

129-
console.log('createTask', createTask)
131+
const tokenCounts = await calculationOfNumberOfTokens(' ', REQUEST_TYPES_COST.CONVERTOR)
132+
133+
await db.subscriber.update(
134+
{ tokens: Sequelize.literal(`tokens - ${tokenCounts}`) },
135+
{ where: { chat_id: msg.from.id } }
136+
)
130137

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

bot/commands/textToSpeech.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
import fs from 'fs'
22
import { OpenAI } from '../utils/openAi.js'
33
import { spinnerOn } from '../utils/spinner.js'
4+
import { calculationOfNumberOfTokens } from '../utils/checkTokens.js'
5+
import { REQUEST_TYPES_COST } from '../constants/index.js'
6+
import { db } from '../db/index.js'
7+
import { Sequelize } from 'sequelize'
48

59
export const textToSpeech = async (bot, chatID, msg, prompt, voice) => {
610
let spinner = await spinnerOn(bot, chatID, null, 'modeDalle')
@@ -13,6 +17,13 @@ export const textToSpeech = async (bot, chatID, msg, prompt, voice) => {
1317
const ttsPathFile = await openAi.textToSpeech(prompt, msg, voice)
1418
const stream = fs.createReadStream(ttsPathFile)
1519

20+
const tokenCounts = await calculationOfNumberOfTokens(prompt, REQUEST_TYPES_COST.TTS)
21+
22+
await db.subscriber.update(
23+
{ tokens: Sequelize.literal(`tokens - ${tokenCounts}`) },
24+
{ where: { chat_id: chatID } }
25+
)
26+
1627
await bot.sendAudio(chatID, stream, {
1728
reply_to_message_id: msg.message_id
1829
})

0 commit comments

Comments
 (0)