Skip to content

Commit

Permalink
!requests command to show how many requests to the bingAI has been ma…
Browse files Browse the repository at this point in the history
…de (#94)

* docs: Update README.md

* feat: !requests command
  • Loading branch information
Luisotee authored Jul 3, 2023
1 parent b361941 commit fcbf4d0
Show file tree
Hide file tree
Showing 6 changed files with 93 additions and 10 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ puppeteer/

.env

conversations_cache.sqlite
conversations_cache.sqlite
counter_cache.sqlite
4 changes: 2 additions & 2 deletions src/clients/sydney.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@ export const sydney = new BingAIClient({
cookies: BING_COOKIES,
userToken: BING_TOKEN,
cache: {
store: new KeyvSqlite({ uri: "sqlite://./conversations_cache.sqlite" })
}
store: new KeyvSqlite({ uri: "sqlite://./conversations_cache.sqlite" }),
},
});
8 changes: 8 additions & 0 deletions src/handlers/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { promptTracker } from "../clients/prompt";
import { sydney } from "../clients/sydney";
import { config } from "../config";
import { getAvailableTones, react } from "../utils";
import { loadCounterData, messageCounter } from "./requests-counter";

const AVAILABLE_TONES = getAvailableTones();

Expand Down Expand Up @@ -90,13 +91,20 @@ export async function handleCommand(
}
}
break;
case "!requests":
await loadCounterData();
await message.reply(
`Sydney has made approximately ${messageCounter} requests, with a limit of 300 per 24 hours.`
);
break;
case "!help":
// this help message was generated by Sydney
await message.reply(
"These are the available commands:\n\n" +
"👉 *!help* shows you this awesome help message.\n" +
"👉 *!ping* tells you if I'm still alive with a *pong!*; this should be super fast.\n" +
"👉 *!tone _args_?* lets you check or change my tone if you pass *_args_*; if you don't pass *_args_*, i will answer with the current tone and the available options. \n" +
"👉 *!requests* estimates the remaining requests to the bingAI API (300/24h).\n" +
"👉 *!pending* gives you a list of the not yet answered prompts you have in this chat.\n" +
"👉 *!reset* erases our conversation history. In group chats, *only admins* can perform this command."
);
Expand Down
12 changes: 9 additions & 3 deletions src/handlers/message.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { Contact, Message, MessageMedia } from "whatsapp-web.js";
import { serializeError } from "serialize-error";
import { Contact, Message, MessageMedia } from "whatsapp-web.js";
import { promptTracker } from "../clients/prompt";
import { sydney } from "../clients/sydney";
import { config } from "../config";
import type { IOptions, SourceAttribution, SydneyResponse } from "../types";
import { react } from "../utils";
import { getContext } from "./context";
import { transcribeAudio } from "./audio-transcription";
import type { SourceAttribution, IOptions, SydneyResponse } from "../types";
import { getContext } from "./context";
import { counterRequests } from "./requests-counter";

function appendSources(sources: SourceAttribution[]) {
let sourcesString = "\n\n";
Expand Down Expand Up @@ -128,6 +129,9 @@ export async function handleMessage(message: Message) {
let interval = setTimeout(() => {}, 0);
const chat = await message.getChat();

clearTimeout(interval);
chat.clearState();

if (chat.isGroup) {
const shouldReply = await handleGroupMessage(message);
if (!shouldReply) return;
Expand Down Expand Up @@ -160,6 +164,8 @@ export async function handleMessage(message: Message) {
typingIndicator();
await react(message, "working");

counterRequests();

try {
const { response, details } = await promptTracker.track(
message.body,
Expand Down
69 changes: 69 additions & 0 deletions src/handlers/requests-counter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import KeyvSqlite from "@keyv/sqlite";
import Keyv from "keyv";

// Part of the logic to count the requests used
const counterCache = new Keyv({
store: new KeyvSqlite({ uri: "sqlite://./counter_cache.sqlite" }),
});

export let messageCounter = 0;
let lastResetDate = new Date();

export async function loadCounterData() {
try {
const counterData = await counterCache.get("counterData");
console.log("counterData:", counterData);
if (counterData) {
messageCounter = counterData.counter;
lastResetDate = new Date(counterData.lastReset);
}
} catch (error) {
console.log("Failed to load counter data:", error);
}
}

export async function saveCounterData() {
try {
await counterCache.set("counterData", {
counter: messageCounter,
lastReset: lastResetDate.toISOString(),
});
} catch (error) {
console.log("Failed to save counter data:", error);
}
}

export function resetCounter() {
messageCounter = 0;
lastResetDate = new Date();
saveCounterData();
}

export function has24HoursPassed() {
const currentDate = new Date();
const timeDiff = currentDate.getTime() - lastResetDate.getTime();
const hoursPassed = timeDiff / (1000 * 3600);
return hoursPassed >= 24;
}

export function increaseCounter() {
messageCounter++;
}

export async function counterRequests() {
// Load counter data from the cache
await loadCounterData();

// Check if 24 hours have passed since the last reset
if (has24HoursPassed()) {
resetCounter();
}

// Increment the counter
increaseCounter();

// Rest of the code...

// Save counter data after each handled message
await saveCounterData();
}
7 changes: 3 additions & 4 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@ dotenv.config();

export function intersection<T>(array1: T[], array2: T[]) {
const set = new Set(array1);
return array2.filter(value => set.has(value));
};

return array2.filter((value) => set.has(value));
}

const ENABLE_REACTIONS =
(process.env.ENABLE_REACTIONS as
Expand All @@ -24,7 +23,7 @@ const reactEmoji = {
queued: QUEUED_REACTION,
working: WORKING_REACTION,
done: DONE_REACTION,
error: ERROR_REACTION
error: ERROR_REACTION,
};

export async function react(
Expand Down

0 comments on commit fcbf4d0

Please sign in to comment.