Added username parameter to chat token, tracking by username.

This commit is contained in:
Niels Simenon 2023-04-09 15:54:39 +02:00
parent 4b8077f7e7
commit ef30c41758
1 changed files with 10 additions and 7 deletions

View File

@ -123,10 +123,10 @@ function setRule(rule, context) {
context.sendMessage(`Chat rule must be at least 3 characters long, ${context.user.prefixedUsername}`, context.room.id, { label: false });
}
async function getTokens(context) {
async function getTokens(username) {
const { used_tokens: usedTokens } = await knex('chat_tokens')
.sum('tokens as used_tokens')
.where('user_id', context.user.id)
.where('user_id', username)
.where('created', '>', knex.raw(`datetime('now', '-${config.chat.userTokenPeriod} hour')`)) // 1 day ago
.first();
@ -154,9 +154,11 @@ async function onCommand(args, context) {
return;
}
if (['tokens', 'credit'].includes(context.subcommand)) {
const tokens = await getTokens(context);
context.sendMessage(`You have ${config.chat.userTokenLimit - tokens} chat tokens remaining. They will be returned gradually over ${config.chat.userTokenPeriod} hours.`, context.room.id, { label: false });
if (['tokens', 'credit'].includes(context.subcommand || context.command)) {
const username = args[0] ? args[0].replace(new RegExp(`^${config.usernamePrefix}`), '') : context.user.username;
const tokens = await getTokens(username);
context.sendMessage(`${args[0] ? `${style.bold(username)} has` : 'You have'} ${style.bold(config.chat.userTokenLimit - tokens)} chat tokens remaining. They will be returned gradually over ${config.chat.userTokenPeriod} hours.`, context.room.id, { label: false });
return;
}
@ -164,7 +166,7 @@ async function onCommand(args, context) {
const prompt = args.join(' ');
try {
const usedTokens = await getTokens(context);
const usedTokens = await getTokens(context.user.username);
if (usedTokens >= config.chat.userTokenLimit) {
context.logger.info(`${context.user.username} was rate limited at ${usedTokens}: ${prompt}`);
@ -200,7 +202,7 @@ async function onCommand(args, context) {
context.sendMessage(`${context.user.prefixedUsername}: ${curatedContent}`, context.room.id, { label: false });
await knex('chat_tokens').insert({
user_id: context.user.id,
user_id: context.user.username,
tokens: res.body.usage.total_tokens,
created: knex.raw("datetime('now')"),
});
@ -224,4 +226,5 @@ module.exports = {
onCommand,
onMessage,
onStart,
commands: ['tokens'],
};