IISHKO: Telegram bot, Mini App and gateway
Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
import { readFileSync, existsSync } from "node:fs";
|
||||
|
||||
export interface Config {
|
||||
botToken: string;
|
||||
mainKey: string;
|
||||
newapiUrl: string;
|
||||
adminIds: number[];
|
||||
userQuota: number;
|
||||
keyWaitHours: number;
|
||||
dbPath: string;
|
||||
}
|
||||
|
||||
function env(name: string, fallback = ""): string {
|
||||
return process.env[name] ?? fallback;
|
||||
}
|
||||
|
||||
export function loadConfig(path = env("IISHKO_TS_CONFIG", "config.json")): Config {
|
||||
const raw = existsSync(path) ? JSON.parse(readFileSync(path, "utf-8")) : {};
|
||||
const cfg: Config = {
|
||||
botToken: env("IISHKO_BOT_TOKEN", raw.bot_token ?? ""),
|
||||
mainKey: env("IISHKO_MAIN_KEY", raw.main_key ?? ""),
|
||||
newapiUrl: env("IISHKO_NEWAPI_URL", raw.newapi_url ?? "http://127.0.0.1:48000"),
|
||||
adminIds: (raw.admin_ids ?? []).map(Number).filter((n: number) => Number.isFinite(n)),
|
||||
userQuota: Number(raw.user_quota ?? 250_000_000),
|
||||
keyWaitHours: Number(raw.key_wait_hours ?? 24),
|
||||
dbPath: env("IISHKO_DB", raw.db_path ?? "iishko.db"),
|
||||
};
|
||||
const adminEnv = env("IISHKO_ADMIN_ID");
|
||||
if (adminEnv && Number.isFinite(Number(adminEnv))) cfg.adminIds.push(Number(adminEnv));
|
||||
if (!cfg.botToken) throw new Error("bot_token missing (env IISHKO_BOT_TOKEN or config.json)");
|
||||
if (!cfg.mainKey) throw new Error("main_key missing (env IISHKO_MAIN_KEY or config.json)");
|
||||
return cfg;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { Context, SessionFlavor } from "grammy";
|
||||
import type { Config } from "./config.js";
|
||||
import type { Db } from "./db.js";
|
||||
import type { Gateway } from "./gateway.js";
|
||||
import type { Economy } from "./modules/economy.js";
|
||||
|
||||
export interface SessionData {
|
||||
history: { role: "system" | "user" | "assistant" | "tool"; content: string | null }[];
|
||||
}
|
||||
|
||||
export interface Deps {
|
||||
config: Config;
|
||||
db: Db;
|
||||
gateway: Gateway;
|
||||
economy: Economy;
|
||||
defaultModel: string;
|
||||
}
|
||||
|
||||
export type Ctx = Context & SessionFlavor<SessionData> & { deps: Deps };
|
||||
@@ -0,0 +1,34 @@
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
|
||||
export function openDb(path: string): DatabaseSync {
|
||||
const db = new DatabaseSync(path);
|
||||
db.exec("PRAGMA journal_mode = WAL");
|
||||
db.exec("PRAGMA busy_timeout = 20000");
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
uid INTEGER PRIMARY KEY,
|
||||
username TEXT,
|
||||
created INTEGER NOT NULL DEFAULT (strftime('%s','now')),
|
||||
referred_by INTEGER,
|
||||
quota INTEGER NOT NULL DEFAULT 0,
|
||||
agent_model TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS tokens (
|
||||
uid INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
key TEXT NOT NULL,
|
||||
created INTEGER NOT NULL DEFAULT (strftime('%s','now'))
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS ledger (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
uid INTEGER NOT NULL,
|
||||
delta INTEGER NOT NULL,
|
||||
reason TEXT NOT NULL,
|
||||
ts INTEGER NOT NULL DEFAULT (strftime('%s','now'))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_ledger_uid ON ledger(uid, ts);
|
||||
`);
|
||||
return db;
|
||||
}
|
||||
|
||||
export type Db = DatabaseSync;
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* OpenAI-compatible gateway client (new-api).
|
||||
* Native tools only. Streaming SSE + non-stream. Fallback model chain.
|
||||
*/
|
||||
|
||||
export interface ChatMessage {
|
||||
role: "system" | "user" | "assistant" | "tool";
|
||||
content: string | null;
|
||||
tool_calls?: ToolCall[];
|
||||
tool_call_id?: string;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
export interface ToolCall {
|
||||
id: string;
|
||||
type: "function";
|
||||
function: { name: string; arguments: string };
|
||||
}
|
||||
|
||||
export interface ChatOpts {
|
||||
model: string;
|
||||
messages: ChatMessage[];
|
||||
tools?: unknown[];
|
||||
tool_choice?: unknown;
|
||||
max_tokens?: number;
|
||||
temperature?: number;
|
||||
}
|
||||
|
||||
export interface StreamCallbacks {
|
||||
onDelta(text: string): void;
|
||||
onToolCall?(call: ToolCall): void;
|
||||
}
|
||||
|
||||
const NON_TERMINAL_400 = /content.?policy|green.?net/i;
|
||||
|
||||
export class Gateway {
|
||||
constructor(
|
||||
private baseUrl: string,
|
||||
private apiKey: string,
|
||||
private timeoutMs = 120_000,
|
||||
) {}
|
||||
|
||||
private headers(): Record<string, string> {
|
||||
return {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
}
|
||||
|
||||
/** Non-streaming completion. */
|
||||
async chat(opts: ChatOpts): Promise<{ content: string; toolCalls: ToolCall[]; model: string }> {
|
||||
const resp = await fetch(`${this.baseUrl}/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: this.headers(),
|
||||
body: JSON.stringify({ ...opts, stream: false }),
|
||||
signal: AbortSignal.timeout(this.timeoutMs),
|
||||
});
|
||||
if (!resp.ok) throw new GatewayError(resp.status, await resp.text().catch(() => ""));
|
||||
const data = (await resp.json()) as {
|
||||
model?: string;
|
||||
choices?: { message?: { content?: string | null; tool_calls?: ToolCall[] } }[];
|
||||
};
|
||||
const msg = data.choices?.[0]?.message;
|
||||
return { content: msg?.content ?? "", toolCalls: msg?.tool_calls ?? [], model: data.model ?? opts.model };
|
||||
}
|
||||
|
||||
/** Streaming completion via SSE. */
|
||||
async chatStream(opts: ChatOpts, cb: StreamCallbacks): Promise<{ toolCalls: ToolCall[]; model: string }> {
|
||||
const resp = await fetch(`${this.baseUrl}/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: this.headers(),
|
||||
body: JSON.stringify({ ...opts, stream: true }),
|
||||
signal: AbortSignal.timeout(this.timeoutMs),
|
||||
});
|
||||
if (!resp.ok) throw new GatewayError(resp.status, await resp.text().catch(() => ""));
|
||||
const toolCalls: ToolCall[] = [];
|
||||
let model = opts.model;
|
||||
const reader = resp.body!.pipeThrough(new TextDecoderStream()).getReader();
|
||||
let buf = "";
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buf += value;
|
||||
const lines = buf.split("\n");
|
||||
buf = lines.pop() ?? "";
|
||||
for (const line of lines) {
|
||||
const t = line.trim();
|
||||
if (!t.startsWith("data:")) continue;
|
||||
const payload = t.slice(5).trim();
|
||||
if (payload === "[DONE]") continue;
|
||||
let ev: {
|
||||
model?: string;
|
||||
choices?: { delta?: { content?: string | null; tool_calls?: Partial<ToolCall>[] } }[];
|
||||
};
|
||||
try {
|
||||
ev = JSON.parse(payload);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
if (ev.model) model = ev.model;
|
||||
const delta = ev.choices?.[0]?.delta;
|
||||
if (delta?.content) cb.onDelta(delta.content);
|
||||
for (const tc of delta?.tool_calls ?? []) {
|
||||
const idx = toolCalls.findIndex((x) => x.id && tc.id && x.id === tc.id);
|
||||
if (tc.id || idx === -1) {
|
||||
toolCalls.push({
|
||||
id: tc.id ?? `call_${toolCalls.length}`,
|
||||
type: "function",
|
||||
function: { name: tc.function?.name ?? "", arguments: tc.function?.arguments ?? "" },
|
||||
});
|
||||
} else if (idx >= 0) {
|
||||
const slot = toolCalls[idx]!;
|
||||
if (tc.function?.name) slot.function.name += tc.function.name;
|
||||
if (tc.function?.arguments) slot.function.arguments += tc.function.arguments;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const tc of toolCalls) cb.onToolCall?.(tc);
|
||||
return { toolCalls, model };
|
||||
}
|
||||
|
||||
/** Fallback chain: try models in order, skip non-terminal 400 (content-policy) to next. */
|
||||
async chatWithFallback(models: string[], opts: Omit<ChatOpts, "model">): Promise<{ content: string; model: string }> {
|
||||
let lastErr: unknown = new Error("no models");
|
||||
for (const model of models) {
|
||||
try {
|
||||
const r = await this.chat({ ...opts, model });
|
||||
return { ...r, model: r.model || model };
|
||||
} catch (e) {
|
||||
lastErr = e;
|
||||
if (e instanceof GatewayError && e.status === 400 && !NON_TERMINAL_400.test(e.body)) throw e;
|
||||
}
|
||||
}
|
||||
throw lastErr;
|
||||
}
|
||||
}
|
||||
|
||||
export class GatewayError extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
public body: string,
|
||||
) {
|
||||
super(`gateway ${status}: ${body.slice(0, 200)}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { Bot, session, GrammyError, HttpError } from "grammy";
|
||||
import { loadConfig } from "./config.js";
|
||||
import { openDb } from "./db.js";
|
||||
import { Gateway } from "./gateway.js";
|
||||
import { Economy } from "./modules/economy.js";
|
||||
import { start } from "./modules/start.js";
|
||||
import { keys } from "./modules/keys.js";
|
||||
import { chat } from "./modules/chat.js";
|
||||
import type { Ctx, SessionData } from "./ctx.js";
|
||||
|
||||
const config = loadConfig();
|
||||
const db = openDb(config.dbPath);
|
||||
const gateway = new Gateway(config.newapiUrl, config.mainKey);
|
||||
const economy = new Economy(db);
|
||||
|
||||
const bot = new Bot<Ctx>(config.botToken);
|
||||
bot.use(
|
||||
session({
|
||||
initial: (): SessionData => ({ history: [] }),
|
||||
}),
|
||||
);
|
||||
|
||||
const deps = { config, db, gateway, economy, defaultModel: process.env.IISHKO_DEFAULT_MODEL ?? "gpt-4o-mini" };
|
||||
bot.use(async (ctx, next) => {
|
||||
ctx.deps = deps;
|
||||
await next();
|
||||
});
|
||||
|
||||
bot.use(start);
|
||||
bot.use(keys);
|
||||
bot.use(chat);
|
||||
|
||||
bot.catch((err) => {
|
||||
const ctx = err.ctx;
|
||||
console.error(`[iishko-ts] update ${ctx.update.update_id} failed:`, err.error);
|
||||
if (err.error instanceof GrammyError) console.error("Telegram API:", err.error.description);
|
||||
else if (err.error instanceof HttpError) console.error("HTTP error:", err.error);
|
||||
});
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const me = await bot.api.getMe();
|
||||
console.log(`[iishko-ts] starting @${me.username} (id=${me.id}) model=${deps.defaultModel}`);
|
||||
await bot.start({
|
||||
onStart: (info) => console.log(`[iishko-ts] polling started for @${info.username}`),
|
||||
});
|
||||
}
|
||||
|
||||
process.once("SIGINT", () => void bot.stop());
|
||||
process.once("SIGTERM", () => void bot.stop());
|
||||
|
||||
main().catch((e) => {
|
||||
console.error("[iishko-ts] fatal:", e);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import { Composer } from "grammy";
|
||||
import type { Ctx } from "../ctx.js";
|
||||
|
||||
const EDIT_INTERVAL_MS = 1200;
|
||||
|
||||
/** Text chat with the LLM: streaming edits, per-user model, quota spend. */
|
||||
export const chat = new Composer<Ctx>();
|
||||
|
||||
chat.on("message:text", async (ctx) => {
|
||||
const uid = ctx.from!.id;
|
||||
ctx.deps.economy.credit(uid, 0, "touch"); // ensure row exists via upsert below
|
||||
ctx.deps.db
|
||||
.prepare("INSERT OR IGNORE INTO users (uid, username) VALUES (?,?)")
|
||||
.run(uid, ctx.from?.username ?? null);
|
||||
|
||||
const model =
|
||||
(ctx.deps.db.prepare("SELECT agent_model FROM users WHERE uid = ?").get(uid) as { agent_model: string | null } | undefined)
|
||||
?.agent_model ?? ctx.deps.defaultModel;
|
||||
|
||||
const history = ctx.session.history;
|
||||
history.push({ role: "user", content: ctx.message.text });
|
||||
if (history.length > 20) history.splice(0, history.length - 20);
|
||||
|
||||
const out = await ctx.reply("…");
|
||||
let buf = "";
|
||||
let lastEdit = 0;
|
||||
const flush = async (final = false) => {
|
||||
const now = Date.now();
|
||||
if (!final && now - lastEdit < EDIT_INTERVAL_MS) return;
|
||||
lastEdit = now;
|
||||
const text = buf.slice(0, 4000) || "…";
|
||||
await ctx.api.editMessageText(ctx.chat!.id, out.message_id, text).catch(() => undefined);
|
||||
};
|
||||
|
||||
try {
|
||||
await ctx.deps.gateway.chatStream(
|
||||
{ model, messages: history, max_tokens: 4096 },
|
||||
{
|
||||
onDelta: (t) => {
|
||||
buf += t;
|
||||
void flush();
|
||||
},
|
||||
},
|
||||
);
|
||||
history.push({ role: "assistant", content: buf });
|
||||
await flush(true);
|
||||
// rough quota spend: (in+out)/1e6 * ratio — placeholder, real ratio from ModelRatio option
|
||||
const approx = Math.ceil(((ctx.message.text.length + buf.length) / 4) * 0.002 * 500_000 * 0.001);
|
||||
ctx.deps.economy.spend(uid, approx, `chat:${model}`);
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
await ctx.api.editMessageText(ctx.chat!.id, out.message_id, `⚠️ ${msg.slice(0, 300)}`).catch(() => undefined);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { Db } from "../db.js";
|
||||
|
||||
const QUOTA_PER_USD = 500_000;
|
||||
|
||||
export class Economy {
|
||||
constructor(private db: Db) {}
|
||||
|
||||
balance(uid: number): number {
|
||||
const row = this.db.prepare("SELECT quota FROM users WHERE uid = ?").get(uid) as { quota: number } | undefined;
|
||||
return row?.quota ?? 0;
|
||||
}
|
||||
|
||||
usdBalance(uid: number): number {
|
||||
return this.balance(uid) / QUOTA_PER_USD;
|
||||
}
|
||||
|
||||
/** Atomic credit/debit inside an explicit transaction with ledger entry. */
|
||||
credit(uid: number, delta: number, reason: string): boolean {
|
||||
this.db.exec("BEGIN IMMEDIATE");
|
||||
try {
|
||||
const cur = this.balance(uid);
|
||||
if (cur + delta < 0) {
|
||||
this.db.exec("ROLLBACK");
|
||||
return false;
|
||||
}
|
||||
this.db.prepare("UPDATE users SET quota = quota + ? WHERE uid = ?").run(delta, uid);
|
||||
this.db.prepare("INSERT INTO ledger (uid, delta, reason) VALUES (?,?,?)").run(uid, delta, reason);
|
||||
this.db.exec("COMMIT");
|
||||
return true;
|
||||
} catch (e) {
|
||||
this.db.exec("ROLLBACK");
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
spend(uid: number, quota: number, reason: string): boolean {
|
||||
return this.credit(uid, -Math.abs(quota), reason);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Composer } from "grammy";
|
||||
import type { Ctx } from "../ctx.js";
|
||||
|
||||
/** /key — issue the user's gateway API key (KEYWAIT-gated). */
|
||||
export const keys = new Composer<Ctx>();
|
||||
|
||||
keys.command("key", async (ctx) => {
|
||||
const uid = ctx.from!.id;
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const user = ctx.deps.db.prepare("SELECT created FROM users WHERE uid = ?").get(uid) as { created: number } | undefined;
|
||||
const waitSec = ctx.deps.config.keyWaitHours * 3600;
|
||||
if (user && now - user.created < waitSec && !ctx.deps.config.adminIds.includes(uid)) {
|
||||
const leftH = Math.ceil((waitSec - (now - user.created)) / 3600);
|
||||
await ctx.reply(`🔑 Ключ будет доступен через ${leftH} ч (анти-абьюз для новых аккаунтов).`);
|
||||
return;
|
||||
}
|
||||
const existing = ctx.deps.db.prepare("SELECT name, key FROM tokens WHERE uid = ?").get(uid) as
|
||||
| { name: string; key: string }
|
||||
| undefined;
|
||||
if (existing) {
|
||||
await ctx.reply(`🔑 Твой ключ:\n\`${existing.key}\`\nBase URL: ${ctx.deps.config.newapiUrl}/v1`, {
|
||||
parse_mode: "Markdown",
|
||||
});
|
||||
return;
|
||||
}
|
||||
// Key creation is delegated to the gateway admin API (new-api): name tg<uid>
|
||||
const resp = await fetch(`${ctx.deps.config.newapiUrl}/api/token/?p=0&size=10&name=tg${uid}`, {
|
||||
headers: { Authorization: `Bearer ${ctx.deps.config.mainKey}` },
|
||||
}).catch(() => null);
|
||||
if (!resp || !resp.ok) {
|
||||
await ctx.reply("⚠️ Шлюз недоступен, попробуй позже.");
|
||||
return;
|
||||
}
|
||||
const data = (await resp.json()) as { data?: { items?: { name: string; key: string }[] } };
|
||||
const item = data.data?.items?.[0];
|
||||
if (!item) {
|
||||
await ctx.reply("⚠️ Не смог создать ключ. Напиши админу.");
|
||||
return;
|
||||
}
|
||||
ctx.deps.db.prepare("INSERT OR REPLACE INTO tokens (uid, name, key) VALUES (?,?,?)").run(uid, item.name, item.key);
|
||||
await ctx.reply(`🔑 Твой ключ:\n\`${item.key}\`\nBase URL: ${ctx.deps.config.newapiUrl}/v1`, { parse_mode: "Markdown" });
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Composer } from "grammy";
|
||||
import type { Ctx } from "../ctx.js";
|
||||
|
||||
export const start = new Composer<Ctx>();
|
||||
|
||||
start.command("start", async (ctx) => {
|
||||
const uid = ctx.from!.id;
|
||||
const refRaw = ctx.match;
|
||||
const ref = typeof refRaw === "string" && /^\d+$/.test(refRaw) ? Number(refRaw) : null;
|
||||
const existing = ctx.deps.db.prepare("SELECT uid FROM users WHERE uid = ?").get(uid);
|
||||
if (!existing) {
|
||||
ctx.deps.db
|
||||
.prepare("INSERT INTO users (uid, username, referred_by, quota) VALUES (?,?,?,?)")
|
||||
.run(uid, ctx.from?.username ?? null, ref && ref !== uid ? ref : null, ctx.deps.config.userQuota);
|
||||
ctx.deps.db
|
||||
.prepare("INSERT INTO ledger (uid, delta, reason) VALUES (?,?,?)")
|
||||
.run(uid, ctx.deps.config.userQuota, "welcome");
|
||||
}
|
||||
await ctx.reply(
|
||||
[
|
||||
"🤖 *иишко* — бесплатный доступ к нейросетям через Telegram.",
|
||||
"",
|
||||
"Просто напиши сообщение — отвечу. Команды:",
|
||||
"/key — твой API-ключ",
|
||||
"/balance — баланс иишек",
|
||||
"/model — сменить модель",
|
||||
].join("\n"),
|
||||
{ parse_mode: "Markdown" },
|
||||
);
|
||||
});
|
||||
|
||||
start.command("balance", async (ctx) => {
|
||||
const usd = ctx.deps.economy.usdBalance(ctx.from!.id);
|
||||
await ctx.reply(`💰 Баланс: $${usd.toFixed(2)} (${(usd * 500_000).toFixed(0)} иишек)`);
|
||||
});
|
||||
Reference in New Issue
Block a user