@codebam/cf-workers-telegram-bot 12.4.0 → 12.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/** Class representing a manager for conversation history stored in KV */
|
|
2
|
+
export declare class HistoryManager {
|
|
3
|
+
private kv;
|
|
4
|
+
constructor(kv: KVNamespace);
|
|
5
|
+
private getKey;
|
|
6
|
+
/**
|
|
7
|
+
* Get the conversation history for a user
|
|
8
|
+
* @param userId - the telegram user ID
|
|
9
|
+
* @param threadId - optional thread ID
|
|
10
|
+
* @returns array of messages
|
|
11
|
+
*/
|
|
12
|
+
getHistory(userId: number, threadId?: number): Promise<{
|
|
13
|
+
role: string;
|
|
14
|
+
content: string;
|
|
15
|
+
}[]>;
|
|
16
|
+
/**
|
|
17
|
+
* Add a message and its response to the history
|
|
18
|
+
* @param userId - the telegram user ID
|
|
19
|
+
* @param prompt - the user message
|
|
20
|
+
* @param response - the bot response
|
|
21
|
+
* @param threadId - optional thread ID
|
|
22
|
+
*/
|
|
23
|
+
addMessage(userId: number, prompt: string, response: string, threadId?: number): Promise<void>;
|
|
24
|
+
/**
|
|
25
|
+
* Clear the conversation history for a user
|
|
26
|
+
* @param userId - the telegram user ID
|
|
27
|
+
* @param threadId - optional thread ID
|
|
28
|
+
*/
|
|
29
|
+
clearHistory(userId: number, threadId?: number): Promise<void>;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Get the balance for a user, initializing it if it doesn't exist
|
|
33
|
+
* @param userId - the telegram user ID
|
|
34
|
+
* @param kv - the KV namespace
|
|
35
|
+
* @returns the user's balance
|
|
36
|
+
*/
|
|
37
|
+
export declare function getBalance(userId: number, kv: KVNamespace): Promise<number>;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/** Class representing a manager for conversation history stored in KV */
|
|
2
|
+
export class HistoryManager {
|
|
3
|
+
kv;
|
|
4
|
+
constructor(kv) {
|
|
5
|
+
this.kv = kv;
|
|
6
|
+
}
|
|
7
|
+
getKey(userId, threadId) {
|
|
8
|
+
return threadId ? `history:${String(userId)}:${String(threadId)}` : `history:${String(userId)}`;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Get the conversation history for a user
|
|
12
|
+
* @param userId - the telegram user ID
|
|
13
|
+
* @param threadId - optional thread ID
|
|
14
|
+
* @returns array of messages
|
|
15
|
+
*/
|
|
16
|
+
async getHistory(userId, threadId) {
|
|
17
|
+
if (!this.kv) {
|
|
18
|
+
return [];
|
|
19
|
+
}
|
|
20
|
+
const history = await this.kv.get(this.getKey(userId, threadId), 'json');
|
|
21
|
+
return history ?? [];
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Add a message and its response to the history
|
|
25
|
+
* @param userId - the telegram user ID
|
|
26
|
+
* @param prompt - the user message
|
|
27
|
+
* @param response - the bot response
|
|
28
|
+
* @param threadId - optional thread ID
|
|
29
|
+
*/
|
|
30
|
+
async addMessage(userId, prompt, response, threadId) {
|
|
31
|
+
if (!this.kv) {
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
const history = await this.getHistory(userId, threadId);
|
|
35
|
+
history.push({ role: 'user', content: prompt });
|
|
36
|
+
history.push({ role: 'assistant', content: response });
|
|
37
|
+
const trimmedHistory = history.slice(-20);
|
|
38
|
+
await this.kv.put(this.getKey(userId, threadId), JSON.stringify(trimmedHistory), {
|
|
39
|
+
expirationTtl: 86400
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Clear the conversation history for a user
|
|
44
|
+
* @param userId - the telegram user ID
|
|
45
|
+
* @param threadId - optional thread ID
|
|
46
|
+
*/
|
|
47
|
+
async clearHistory(userId, threadId) {
|
|
48
|
+
if (!this.kv) {
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
await this.kv.delete(this.getKey(userId, threadId));
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Get the balance for a user, initializing it if it doesn't exist
|
|
56
|
+
* @param userId - the telegram user ID
|
|
57
|
+
* @param kv - the KV namespace
|
|
58
|
+
* @returns the user's balance
|
|
59
|
+
*/
|
|
60
|
+
export async function getBalance(userId, kv) {
|
|
61
|
+
const balanceKey = `balance:${String(userId)}`;
|
|
62
|
+
const balance = await kv.get(balanceKey, 'json');
|
|
63
|
+
if (balance === null) {
|
|
64
|
+
const defaultBalance = 200;
|
|
65
|
+
await kv.put(balanceKey, JSON.stringify(defaultBalance));
|
|
66
|
+
return defaultBalance;
|
|
67
|
+
}
|
|
68
|
+
return balance;
|
|
69
|
+
}
|
package/dist/main.d.ts
CHANGED
|
@@ -8,5 +8,6 @@ import TelegramGuestMessage from './types/TelegramGuestMessage.js';
|
|
|
8
8
|
import PartialTelegramUpdate from './types/PartialTelegramUpdate.js';
|
|
9
9
|
import TelegramInlineQueryType from './types/TelegramInlineQueryType.js';
|
|
10
10
|
import { markdownToHtml, fetchTool } from './utils.js';
|
|
11
|
+
import { HistoryManager, getBalance } from './history_manager.js';
|
|
11
12
|
export default TelegramBot;
|
|
12
|
-
export { TelegramBot, TelegramExecutionContext, Webhook, TelegramApi, TelegramApiBaseParams, SendMessageParams, SendMessageDraftParams, SendPhotoParams, SendVideoParams, SendVoiceParams, SendChatActionParams, AnswerCallbackParams, AnswerInlineParams, AnswerGuestParams, SendInvoiceParams, AnswerPreCheckoutParams, TelegramApiParams, TelegramCommand, TelegramFrom, TelegramChat, TelegramUser, TelegramMessageEntity, TelegramPhotoSize, TelegramMessage, TelegramVoice, TelegramGuestMessage, TelegramInputMessageContent, TelegramInlineQuery, TelegramUpdate, PartialTelegramUpdate, TelegramInlineQueryType, TelegramInlineQueryResult, TelegramInlineQueryResultPhoto, TelegramInlineQueryResultArticle, TelegramInlineQueryResultVideo, TelegramInlineQueryResultVoice, ChatPermissions, TelegramBusinessMessage, TelegramCallbackQuery, TelegramPreCheckoutQuery, TelegramDocument, TelegramSuccessfulPayment, markdownToHtml, fetchTool, };
|
|
13
|
+
export { TelegramBot, TelegramExecutionContext, Webhook, TelegramApi, TelegramApiBaseParams, SendMessageParams, SendMessageDraftParams, SendPhotoParams, SendVideoParams, SendVoiceParams, SendChatActionParams, AnswerCallbackParams, AnswerInlineParams, AnswerGuestParams, SendInvoiceParams, AnswerPreCheckoutParams, TelegramApiParams, TelegramCommand, TelegramFrom, TelegramChat, TelegramUser, TelegramMessageEntity, TelegramPhotoSize, TelegramMessage, TelegramVoice, TelegramGuestMessage, TelegramInputMessageContent, TelegramInlineQuery, TelegramUpdate, PartialTelegramUpdate, TelegramInlineQueryType, TelegramInlineQueryResult, TelegramInlineQueryResultPhoto, TelegramInlineQueryResultArticle, TelegramInlineQueryResultVideo, TelegramInlineQueryResultVoice, ChatPermissions, TelegramBusinessMessage, TelegramCallbackQuery, TelegramPreCheckoutQuery, TelegramDocument, TelegramSuccessfulPayment, markdownToHtml, fetchTool, HistoryManager, getBalance, };
|
package/dist/main.js
CHANGED
|
@@ -3,5 +3,6 @@ import TelegramExecutionContext from './telegram_execution_context.js';
|
|
|
3
3
|
import Webhook from './webhook.js';
|
|
4
4
|
import TelegramApi from './telegram_api.js';
|
|
5
5
|
import { markdownToHtml, fetchTool } from './utils.js';
|
|
6
|
+
import { HistoryManager, getBalance } from './history_manager.js';
|
|
6
7
|
export default TelegramBot;
|
|
7
|
-
export { TelegramBot, TelegramExecutionContext, Webhook, TelegramApi, markdownToHtml, fetchTool, };
|
|
8
|
+
export { TelegramBot, TelegramExecutionContext, Webhook, TelegramApi, markdownToHtml, fetchTool, HistoryManager, getBalance, };
|
|
@@ -7,8 +7,6 @@ export default class TelegramExecutionContext {
|
|
|
7
7
|
private static businessOwners;
|
|
8
8
|
/** Cache for dead business connections */
|
|
9
9
|
private static poisonedConnections;
|
|
10
|
-
/** Cache for self-response counts to prevent infinite loops */
|
|
11
|
-
private static selfResponseCount;
|
|
12
10
|
/** an instance of the telegram bot */
|
|
13
11
|
bot: TelegramBot;
|
|
14
12
|
/** an instance of the telegram update */
|
|
@@ -5,8 +5,6 @@ export default class TelegramExecutionContext {
|
|
|
5
5
|
static businessOwners = new Map();
|
|
6
6
|
/** Cache for dead business connections */
|
|
7
7
|
static poisonedConnections = new Set();
|
|
8
|
-
/** Cache for self-response counts to prevent infinite loops */
|
|
9
|
-
static selfResponseCount = new Map();
|
|
10
8
|
/** an instance of the telegram bot */
|
|
11
9
|
bot;
|
|
12
10
|
/** an instance of the telegram update */
|
|
@@ -85,16 +83,6 @@ export default class TelegramExecutionContext {
|
|
|
85
83
|
*/
|
|
86
84
|
async shouldProcess() {
|
|
87
85
|
if (this.update_type !== 'business_message') {
|
|
88
|
-
if (this.userId === this.bot.botId) {
|
|
89
|
-
const chatId = this.getChatId();
|
|
90
|
-
const count = TelegramExecutionContext.selfResponseCount.get(chatId) || 0;
|
|
91
|
-
if (count < this.bot.ttl) {
|
|
92
|
-
TelegramExecutionContext.selfResponseCount.set(chatId, count + 1);
|
|
93
|
-
return true;
|
|
94
|
-
}
|
|
95
|
-
return false;
|
|
96
|
-
}
|
|
97
|
-
TelegramExecutionContext.selfResponseCount.delete(this.getChatId());
|
|
98
86
|
return true;
|
|
99
87
|
}
|
|
100
88
|
const connectionId = this.update.business_message?.business_connection_id?.toString();
|
|
@@ -132,16 +120,6 @@ export default class TelegramExecutionContext {
|
|
|
132
120
|
console.warn('Failed to fetch business connection info:', e);
|
|
133
121
|
}
|
|
134
122
|
}
|
|
135
|
-
if (ownerId !== undefined && (this.getChatId() === ownerId.toString() || this.userId === ownerId)) {
|
|
136
|
-
const chatId = this.getChatId();
|
|
137
|
-
const count = TelegramExecutionContext.selfResponseCount.get(chatId) || 0;
|
|
138
|
-
if (count < this.bot.ttl) {
|
|
139
|
-
TelegramExecutionContext.selfResponseCount.set(chatId, count + 1);
|
|
140
|
-
return true;
|
|
141
|
-
}
|
|
142
|
-
return false;
|
|
143
|
-
}
|
|
144
|
-
TelegramExecutionContext.selfResponseCount.delete(this.getChatId());
|
|
145
123
|
return true;
|
|
146
124
|
}
|
|
147
125
|
determineUpdateType() {
|