add postgres db, use settings and user data, lots of cleanup and logic fixes, bug fixes, better error handling, update docs and docker
Some checks are pending
njsscan sarif / njsscan code scanning (push) Waiting to run
Update AUTHORS File / update-authors (push) Waiting to run
Some checks are pending
njsscan sarif / njsscan code scanning (push) Waiting to run
Update AUTHORS File / update-authors (push) Waiting to run
This commit is contained in:
parent
765b1144fa
commit
4d540078f5
30 changed files with 1664 additions and 727 deletions
|
@ -38,6 +38,9 @@ import { languageCode } from "../utils/language-code"
|
|||
import axios from "axios"
|
||||
import { rateLimiter } from "../utils/rate-limiter"
|
||||
import { logger } from "../utils/log"
|
||||
import { ensureUserInDb } from "../utils/ensure-user"
|
||||
import * as schema from '../db/schema'
|
||||
import type { NodePgDatabase } from "drizzle-orm/node-postgres"
|
||||
|
||||
const spamwatchMiddleware = spamwatchMiddlewareModule(isOnSpamWatch)
|
||||
export const flash_model = process.env.flashModel || "gemma3:4b"
|
||||
|
@ -45,6 +48,94 @@ export const thinking_model = process.env.thinkingModel || "qwen3:4b"
|
|||
|
||||
type TextContext = Context & { message: Message.TextMessage }
|
||||
|
||||
type User = typeof schema.usersTable.$inferSelect
|
||||
|
||||
interface ModelInfo {
|
||||
name: string;
|
||||
label: string;
|
||||
descriptionEn: string;
|
||||
descriptionPt: string;
|
||||
models: Array<{
|
||||
name: string;
|
||||
label: string;
|
||||
parameterSize: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
interface OllamaResponse {
|
||||
response: string;
|
||||
}
|
||||
|
||||
export const models: ModelInfo[] = [
|
||||
{
|
||||
name: 'gemma3n',
|
||||
label: 'Gemma3n',
|
||||
descriptionEn: 'Gemma3n is a family of open, light on-device models for general tasks.',
|
||||
descriptionPt: 'Gemma3n é uma família de modelos abertos, leves e para dispositivos locais, para tarefas gerais.',
|
||||
models: [
|
||||
{ name: 'gemma3n:e2b', label: 'Gemma3n e2b', parameterSize: '2B' },
|
||||
{ name: 'gemma3n:e4b', label: 'Gemma3n e4b', parameterSize: '4B' },
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'gemma3-abliterated',
|
||||
label: 'Gemma3 Uncensored',
|
||||
descriptionEn: 'Gemma3-abliterated is a family of open, uncensored models for general tasks.',
|
||||
descriptionPt: 'Gemma3-abliterated é uma família de modelos abertos, não censurados, para tarefas gerais.',
|
||||
models: [
|
||||
{ name: 'huihui_ai/gemma3-abliterated:1b', label: 'Gemma3-abliterated 1B', parameterSize: '1b' },
|
||||
{ name: 'huihui_ai/gemma3-abliterated:4b', label: 'Gemma3-abliterated 4B', parameterSize: '4b' },
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'qwen3',
|
||||
label: 'Qwen3',
|
||||
descriptionEn: 'Qwen3 is a multilingual reasoning model series.',
|
||||
descriptionPt: 'Qwen3 é uma série de modelos multilingues.',
|
||||
models: [
|
||||
{ name: 'qwen3:4b', label: 'Qwen3 4B', parameterSize: '4B' },
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'deepseek',
|
||||
label: 'DeepSeek',
|
||||
descriptionEn: 'DeepSeek is a research model for reasoning tasks.',
|
||||
descriptionPt: 'DeepSeek é um modelo de pesquisa para tarefas de raciocínio.',
|
||||
models: [
|
||||
{ name: 'deepseek-r1:1.5b', label: 'DeepSeek 1.5B', parameterSize: '1.5B' },
|
||||
{ name: 'huihui_ai/deepseek-r1-abliterated:1.5b', label: 'DeepSeek Uncensored 1.5B', parameterSize: '1.5B' },
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
const enSystemPrompt = `You are a plaintext-only, helpful assistant called {botName}.
|
||||
Current Date/Time (UTC): {date}
|
||||
|
||||
---
|
||||
|
||||
Respond to the user's message:
|
||||
{message}`
|
||||
|
||||
const ptSystemPrompt = `Você é um assistente de texto puro e útil chamado {botName}.
|
||||
Data/Hora atual (UTC): {date}
|
||||
|
||||
---
|
||||
|
||||
Responda à mensagem do usuário:
|
||||
{message}`
|
||||
|
||||
async function usingSystemPrompt(ctx: TextContext, db: NodePgDatabase<typeof schema>, botName: string): Promise<string> {
|
||||
const user = await db.query.usersTable.findMany({ where: (fields, { eq }) => eq(fields.telegramId, String(ctx.from!.id)), limit: 1 });
|
||||
if (user.length === 0) await ensureUserInDb(ctx, db);
|
||||
const userData = user[0];
|
||||
const lang = userData?.languageCode || "en";
|
||||
const utcDate = new Date().toISOString();
|
||||
const prompt = lang === "pt"
|
||||
? ptSystemPrompt.replace("{botName}", botName).replace("{date}", utcDate).replace("{message}", ctx.message.text)
|
||||
: enSystemPrompt.replace("{botName}", botName).replace("{date}", utcDate).replace("{message}", ctx.message.text);
|
||||
return prompt;
|
||||
}
|
||||
|
||||
export function sanitizeForJson(text: string): string {
|
||||
return text
|
||||
.replace(/\\/g, '\\\\')
|
||||
|
@ -69,23 +160,50 @@ export async function preChecks() {
|
|||
}
|
||||
checked++;
|
||||
}
|
||||
console.log(`[✨ AI] Pre-checks passed [${checked}/${envs.length}]\n`)
|
||||
|
||||
const ollamaApi = process.env.ollamaApi
|
||||
if (!ollamaApi) {
|
||||
console.error("[✨ AI | !] ❌ ollamaApi not set!")
|
||||
return false
|
||||
}
|
||||
let ollamaOk = false
|
||||
for (let i = 0; i < 10; i++) {
|
||||
try {
|
||||
const res = await axios.get(ollamaApi, { timeout: 2000 })
|
||||
if (res && res.data && typeof res.data === 'object' && 'ollama' in res.data) {
|
||||
ollamaOk = true
|
||||
break
|
||||
}
|
||||
if (res && res.status === 200) {
|
||||
ollamaOk = true
|
||||
break
|
||||
}
|
||||
} catch (err) {
|
||||
await new Promise(resolve => setTimeout(resolve, 1000))
|
||||
}
|
||||
}
|
||||
if (!ollamaOk) {
|
||||
console.error("[✨ AI | !] ❌ Ollama API is not responding at ", ollamaApi)
|
||||
return false
|
||||
}
|
||||
checked++;
|
||||
console.log(`[✨ AI] Pre-checks passed [${checked}/${envs.length + 1}]`)
|
||||
return true
|
||||
}
|
||||
|
||||
function isAxiosError(error: unknown): error is { response?: { data?: { error?: string }, status?: number }, request?: unknown, message?: string } {
|
||||
function isAxiosError(error: unknown): error is { response?: { data?: { error?: string }, status?: number, statusText?: string }, request?: unknown, message?: string } {
|
||||
return typeof error === 'object' && error !== null && (
|
||||
'response' in error || 'request' in error || 'message' in error
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function extractAxiosErrorMessage(error: unknown): string {
|
||||
if (isAxiosError(error)) {
|
||||
const err = error as Record<string, unknown>;
|
||||
const err = error as { response?: { data?: { error?: string }, status?: number, statusText?: string }, request?: unknown, message?: string };
|
||||
if (err.response && typeof err.response === 'object') {
|
||||
const resp = err.response as Record<string, unknown>;
|
||||
const resp = err.response;
|
||||
if (resp.data && typeof resp.data === 'object' && 'error' in resp.data) {
|
||||
return String((resp.data as Record<string, unknown>).error);
|
||||
return String(resp.data.error);
|
||||
}
|
||||
if ('status' in resp && 'statusText' in resp) {
|
||||
return `HTTP ${resp.status}: ${resp.statusText}`;
|
||||
|
@ -102,71 +220,68 @@ function extractAxiosErrorMessage(error: unknown): string {
|
|||
return 'An unexpected error occurred.';
|
||||
}
|
||||
|
||||
async function getResponse(prompt: string, ctx: TextContext, replyGenerating: Message, model: string) {
|
||||
const Strings = getStrings(languageCode(ctx))
|
||||
|
||||
async function getResponse(prompt: string, ctx: TextContext, replyGenerating: Message, model: string, aiTemperature: number): Promise<{ success: boolean; response?: string; error?: string }> {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
if (!ctx.chat) {
|
||||
return {
|
||||
success: false,
|
||||
error: Strings.unexpectedErr.replace("{error}", "No chat found"),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const aiResponse = await axios.post(
|
||||
const aiResponse = await axios.post<unknown>(
|
||||
`${process.env.ollamaApi}/api/generate`,
|
||||
{
|
||||
model,
|
||||
prompt,
|
||||
stream: true,
|
||||
options: {
|
||||
temperature: aiTemperature
|
||||
}
|
||||
},
|
||||
{
|
||||
responseType: "stream",
|
||||
}
|
||||
)
|
||||
|
||||
let fullResponse = ""
|
||||
let thoughts = ""
|
||||
let lastUpdate = Date.now()
|
||||
|
||||
const stream = aiResponse.data
|
||||
);
|
||||
let fullResponse = "";
|
||||
let thoughts = "";
|
||||
let lastUpdate = Date.now();
|
||||
const stream: NodeJS.ReadableStream = aiResponse.data as any;
|
||||
for await (const chunk of stream) {
|
||||
const lines = chunk.toString().split('\n')
|
||||
const lines = chunk.toString().split('\n');
|
||||
for (const line of lines) {
|
||||
if (!line.trim()) continue
|
||||
let ln
|
||||
if (!line.trim()) continue;
|
||||
let ln: OllamaResponse;
|
||||
try {
|
||||
ln = JSON.parse(line)
|
||||
ln = JSON.parse(line);
|
||||
} catch (e) {
|
||||
console.error("[✨ AI | !] Error parsing chunk:", e)
|
||||
continue
|
||||
console.error("[✨ AI | !] Error parsing chunk:", e);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (model === thinking_model) {
|
||||
if (model === thinking_model && ln.response) {
|
||||
if (ln.response.includes('<think>')) {
|
||||
const thinkMatch = ln.response.match(/<think>([\s\S]*?)<\/think>/)
|
||||
const thinkMatch = ln.response.match(/<think>([\s\S]*?)<\/think>/);
|
||||
if (thinkMatch && thinkMatch[1].trim().length > 0) {
|
||||
logger.logThinking(ctx.chat.id, replyGenerating.message_id, true)
|
||||
logger.logThinking(ctx.chat.id, replyGenerating.message_id, true);
|
||||
} else if (!thinkMatch) {
|
||||
logger.logThinking(ctx.chat.id, replyGenerating.message_id, true)
|
||||
logger.logThinking(ctx.chat.id, replyGenerating.message_id, true);
|
||||
}
|
||||
} else if (ln.response.includes('</think>')) {
|
||||
logger.logThinking(ctx.chat.id, replyGenerating.message_id, false)
|
||||
logger.logThinking(ctx.chat.id, replyGenerating.message_id, false);
|
||||
}
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
const now = Date.now();
|
||||
if (ln.response) {
|
||||
if (model === thinking_model) {
|
||||
let patchedThoughts = ln.response
|
||||
const thinkTagRx = /<think>([\s\S]*?)<\/think>/g
|
||||
patchedThoughts = patchedThoughts.replace(thinkTagRx, (match, p1) => p1.trim().length > 0 ? '`Thinking...`' + p1 + '`Finished thinking`' : '')
|
||||
patchedThoughts = patchedThoughts.replace(/<think>/g, '`Thinking...`')
|
||||
patchedThoughts = patchedThoughts.replace(/<\/think>/g, '`Finished thinking`')
|
||||
thoughts += patchedThoughts
|
||||
fullResponse += patchedThoughts
|
||||
let patchedThoughts = ln.response;
|
||||
const thinkTagRx = /<think>([\s\S]*?)<\/think>/g;
|
||||
patchedThoughts = patchedThoughts.replace(thinkTagRx, (match, p1) => p1.trim().length > 0 ? '`Thinking...`' + p1 + '`Finished thinking`' : '');
|
||||
patchedThoughts = patchedThoughts.replace(/<think>/g, '`Thinking...`');
|
||||
patchedThoughts = patchedThoughts.replace(/<\/think>/g, '`Finished thinking`');
|
||||
thoughts += patchedThoughts;
|
||||
fullResponse += patchedThoughts;
|
||||
} else {
|
||||
fullResponse += ln.response
|
||||
fullResponse += ln.response;
|
||||
}
|
||||
if (now - lastUpdate >= 1000) {
|
||||
await rateLimiter.editMessageWithRetry(
|
||||
|
@ -175,67 +290,104 @@ async function getResponse(prompt: string, ctx: TextContext, replyGenerating: Me
|
|||
replyGenerating.message_id,
|
||||
thoughts,
|
||||
{ parse_mode: 'Markdown' }
|
||||
)
|
||||
lastUpdate = now
|
||||
);
|
||||
lastUpdate = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
response: fullResponse,
|
||||
}
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
const errorMsg = extractAxiosErrorMessage(error)
|
||||
console.error("[✨ AI | !] Error:", errorMsg)
|
||||
|
||||
// model not found or 404
|
||||
const errorMsg = extractAxiosErrorMessage(error);
|
||||
console.error("[✨ AI | !] Error:", errorMsg);
|
||||
if (isAxiosError(error) && error.response && typeof error.response === 'object') {
|
||||
const resp = error.response as Record<string, unknown>;
|
||||
const errData = resp.data && typeof resp.data === 'object' && 'error' in resp.data ? (resp.data as Record<string, unknown>).error : undefined;
|
||||
const resp = error.response as { data?: { error?: string }, status?: number };
|
||||
const errData = resp.data && typeof resp.data === 'object' && 'error' in resp.data ? (resp.data as { error?: string }).error : undefined;
|
||||
const errStatus = 'status' in resp ? resp.status : undefined;
|
||||
if ((typeof errData === 'string' && errData.includes(`model '${model}' not found`)) || errStatus === 404) {
|
||||
ctx.telegram.editMessageText(
|
||||
ctx.chat.id,
|
||||
await ctx.telegram.editMessageText(
|
||||
ctx.chat!.id,
|
||||
replyGenerating.message_id,
|
||||
undefined,
|
||||
`🔄 *Pulling ${model} from Ollama...*\n\nThis may take a few minutes...`,
|
||||
Strings.ai.pulling.replace("{model}", model),
|
||||
{ parse_mode: 'Markdown' }
|
||||
)
|
||||
console.log(`[✨ AI | i] Pulling ${model} from ollama...`)
|
||||
);
|
||||
console.log(`[✨ AI | i] Pulling ${model} from ollama...`);
|
||||
try {
|
||||
await axios.post(
|
||||
`${process.env.ollamaApi}/api/pull`,
|
||||
{
|
||||
model,
|
||||
stream: false,
|
||||
timeout: process.env.ollamaApiTimeout || 10000,
|
||||
timeout: Number(process.env.ollamaApiTimeout) || 10000,
|
||||
}
|
||||
)
|
||||
);
|
||||
} catch (e: unknown) {
|
||||
const pullMsg = extractAxiosErrorMessage(e)
|
||||
console.error("[✨ AI | !] Pull error:", pullMsg)
|
||||
const pullMsg = extractAxiosErrorMessage(e);
|
||||
console.error("[✨ AI | !] Pull error:", pullMsg);
|
||||
return {
|
||||
success: false,
|
||||
error: `❌ Something went wrong while pulling ${model}: ${pullMsg}`,
|
||||
}
|
||||
};
|
||||
}
|
||||
console.log(`[✨ AI | i] ${model} pulled successfully`)
|
||||
console.log(`[✨ AI | i] ${model} pulled successfully`);
|
||||
return {
|
||||
success: true,
|
||||
response: `✅ Pulled ${model} successfully, please retry the command.`,
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
return {
|
||||
success: false,
|
||||
error: errorMsg,
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export default (bot: Telegraf<Context>) => {
|
||||
async function handleAiReply(ctx: TextContext, db: NodePgDatabase<typeof schema>, model: string, prompt: string, replyGenerating: Message, aiTemperature: number) {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const aiResponse = await getResponse(prompt, ctx, replyGenerating, model, aiTemperature);
|
||||
if (!aiResponse) return;
|
||||
if (!ctx.chat) return;
|
||||
if (aiResponse.success && aiResponse.response) {
|
||||
const modelHeader = `🤖 *${model}* | 🌡️ *${aiTemperature}*\n\n`;
|
||||
await rateLimiter.editMessageWithRetry(
|
||||
ctx,
|
||||
ctx.chat.id,
|
||||
replyGenerating.message_id,
|
||||
modelHeader + aiResponse.response,
|
||||
{ parse_mode: 'Markdown' }
|
||||
);
|
||||
return;
|
||||
}
|
||||
const error = Strings.unexpectedErr.replace("{error}", aiResponse.error);
|
||||
await rateLimiter.editMessageWithRetry(
|
||||
ctx,
|
||||
ctx.chat.id,
|
||||
replyGenerating.message_id,
|
||||
error,
|
||||
{ parse_mode: 'Markdown' }
|
||||
);
|
||||
}
|
||||
|
||||
async function getUserWithStringsAndModel(ctx: Context, db: NodePgDatabase<typeof schema>): Promise<{ user: User; Strings: ReturnType<typeof getStrings>; languageCode: string; customAiModel: string; aiTemperature: number }> {
|
||||
const userArr = await db.query.usersTable.findMany({ where: (fields, { eq }) => eq(fields.telegramId, String(ctx.from!.id)), limit: 1 });
|
||||
let user = userArr[0];
|
||||
if (!user) {
|
||||
await ensureUserInDb(ctx, db);
|
||||
const newUserArr = await db.query.usersTable.findMany({ where: (fields, { eq }) => eq(fields.telegramId, String(ctx.from!.id)), limit: 1 });
|
||||
user = newUserArr[0];
|
||||
const Strings = getStrings(user.languageCode);
|
||||
return { user, Strings, languageCode: user.languageCode, customAiModel: user.customAiModel, aiTemperature: user.aiTemperature };
|
||||
}
|
||||
const Strings = getStrings(user.languageCode);
|
||||
return { user, Strings, languageCode: user.languageCode, customAiModel: user.customAiModel, aiTemperature: user.aiTemperature };
|
||||
}
|
||||
|
||||
export default (bot: Telegraf<Context>, db: NodePgDatabase<typeof schema>) => {
|
||||
const botName = bot.botInfo?.first_name && bot.botInfo?.last_name ? `${bot.botInfo.first_name} ${bot.botInfo.last_name}` : "Kowalski"
|
||||
|
||||
bot.command(["ask", "think"], spamwatchMiddleware, async (ctx) => {
|
||||
|
@ -244,65 +396,75 @@ export default (bot: Telegraf<Context>) => {
|
|||
const model = isAsk ? flash_model : thinking_model
|
||||
const textCtx = ctx as TextContext
|
||||
const reply_to_message_id = replyToMessageId(textCtx)
|
||||
const Strings = getStrings(languageCode(textCtx))
|
||||
const { Strings, aiTemperature } = await getUserWithStringsAndModel(textCtx, db)
|
||||
const message = textCtx.message.text
|
||||
const author = ("@" + ctx.from?.username) || ctx.from?.first_name
|
||||
|
||||
logger.logCmdStart(author, model === flash_model ? "ask" : "think")
|
||||
|
||||
if (!process.env.ollamaApi) {
|
||||
await ctx.reply(Strings.aiDisabled, {
|
||||
await ctx.reply(Strings.ai.disabled, {
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const replyGenerating = await ctx.reply(Strings.askGenerating.replace("{model}", model), {
|
||||
const fixedMsg = message.replace(/^\/(ask|think)(@\w+)?\s*/, "").trim()
|
||||
if (fixedMsg.length < 1) {
|
||||
await ctx.reply(Strings.ai.askNoMessage, {
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const replyGenerating = await ctx.reply(Strings.ai.askGenerating.replace("{model}", model), {
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
})
|
||||
|
||||
const fixedMsg = message.replace(/\/(ask|think) /, "")
|
||||
if (fixedMsg.length < 1) {
|
||||
await ctx.reply(Strings.askNoMessage, {
|
||||
logger.logPrompt(fixedMsg)
|
||||
|
||||
const prompt = sanitizeForJson(await usingSystemPrompt(textCtx, db, botName))
|
||||
await handleAiReply(textCtx, db, model, prompt, replyGenerating, aiTemperature)
|
||||
})
|
||||
|
||||
bot.command(["ai"], spamwatchMiddleware, async (ctx) => {
|
||||
if (!ctx.message || !('text' in ctx.message)) return
|
||||
const textCtx = ctx as TextContext
|
||||
const reply_to_message_id = replyToMessageId(textCtx)
|
||||
const { Strings, customAiModel, aiTemperature } = await getUserWithStringsAndModel(textCtx, db)
|
||||
const message = textCtx.message.text
|
||||
const author = ("@" + ctx.from?.username) || ctx.from?.first_name
|
||||
|
||||
logger.logCmdStart(author, "ask")
|
||||
|
||||
if (!process.env.ollamaApi) {
|
||||
await ctx.reply(Strings.ai.disabled, {
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
logger.logPrompt(fixedMsg)
|
||||
|
||||
const prompt = sanitizeForJson(
|
||||
`You are a plaintext-only, helpful assistant called ${botName}.
|
||||
Current Date/Time (UTC): ${new Date().toLocaleString()}
|
||||
|
||||
---
|
||||
|
||||
Respond to the user's message:
|
||||
${fixedMsg}`)
|
||||
const aiResponse = await getResponse(prompt, textCtx, replyGenerating, model)
|
||||
if (!aiResponse) return
|
||||
|
||||
if (!ctx.chat) return
|
||||
if (aiResponse.success && aiResponse.response) {
|
||||
await rateLimiter.editMessageWithRetry(
|
||||
ctx,
|
||||
ctx.chat.id,
|
||||
replyGenerating.message_id,
|
||||
aiResponse.response,
|
||||
{ parse_mode: 'Markdown' }
|
||||
)
|
||||
const fixedMsg = message.replace(/^\/ai(@\w+)?\s*/, "").trim()
|
||||
if (fixedMsg.length < 1) {
|
||||
await ctx.reply(Strings.ai.askNoMessage, {
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
})
|
||||
return
|
||||
}
|
||||
const error = Strings.unexpectedErr.replace("{error}", aiResponse.error)
|
||||
await rateLimiter.editMessageWithRetry(
|
||||
ctx,
|
||||
ctx.chat.id,
|
||||
replyGenerating.message_id,
|
||||
error,
|
||||
{ parse_mode: 'Markdown' }
|
||||
)
|
||||
|
||||
const replyGenerating = await ctx.reply(Strings.ai.askGenerating.replace("{model}", customAiModel), {
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
})
|
||||
|
||||
logger.logPrompt(fixedMsg)
|
||||
|
||||
const prompt = sanitizeForJson(await usingSystemPrompt(textCtx, db, botName))
|
||||
await handleAiReply(textCtx, db, customAiModel, prompt, replyGenerating, aiTemperature)
|
||||
})
|
||||
}
|
|
@ -9,124 +9,131 @@ import { languageCode } from '../utils/language-code';
|
|||
|
||||
const spamwatchMiddleware = spamwatchMiddlewareModule(isOnSpamWatch);
|
||||
|
||||
export default (bot: Telegraf<Context>) => {
|
||||
bot.command("duck", spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
const reply_to_message_id = replyToMessageId(ctx);
|
||||
try {
|
||||
const response = await axios(Resources.duckApi);
|
||||
ctx.replyWithPhoto(response.data.url, {
|
||||
caption: "🦆",
|
||||
...({ reply_to_message_id })
|
||||
});
|
||||
} catch (error) {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const message = Strings.duckApiErr.replace('{error}', error.message);
|
||||
ctx.reply(message, {
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
});
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
bot.command("fox", spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
export const duckHandler = async (ctx: Context & { message: { text: string } }) => {
|
||||
const reply_to_message_id = replyToMessageId(ctx);
|
||||
try {
|
||||
const response = await axios(Resources.duckApi);
|
||||
ctx.replyWithPhoto(response.data.url, {
|
||||
caption: "🦆",
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
} catch (error) {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const reply_to_message_id = replyToMessageId(ctx);
|
||||
try {
|
||||
const response = await axios(Resources.foxApi);
|
||||
ctx.replyWithPhoto(response.data.image, {
|
||||
caption: "🦊",
|
||||
...({ reply_to_message_id })
|
||||
});
|
||||
} catch (error) {
|
||||
const message = Strings.foxApiErr.replace('{error}', error.message);
|
||||
ctx.reply(message, {
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
});
|
||||
return;
|
||||
}
|
||||
});
|
||||
const message = Strings.duckApiErr.replace('{error}', error.message);
|
||||
ctx.reply(message, {
|
||||
parse_mode: 'Markdown',
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
bot.command("dog", spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const reply_to_message_id = replyToMessageId(ctx);
|
||||
try {
|
||||
const response = await axios(Resources.dogApi);
|
||||
ctx.replyWithPhoto(response.data.message, {
|
||||
caption: "🐶",
|
||||
...({ reply_to_message_id })
|
||||
});
|
||||
} catch (error) {
|
||||
const message = Strings.foxApiErr.replace('{error}', error.message);
|
||||
ctx.reply(message, {
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
});
|
||||
return;
|
||||
}
|
||||
});
|
||||
export const foxHandler = async (ctx: Context & { message: { text: string } }) => {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const reply_to_message_id = replyToMessageId(ctx);
|
||||
try {
|
||||
const response = await axios(Resources.foxApi);
|
||||
ctx.replyWithPhoto(response.data.image, {
|
||||
caption: "🦊",
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
} catch (error) {
|
||||
const message = Strings.foxApiErr.replace('{error}', error.message);
|
||||
ctx.reply(message, {
|
||||
parse_mode: 'Markdown',
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
bot.command("cat", spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const apiUrl = `${Resources.catApi}?json=true`;
|
||||
export const dogHandler = async (ctx: Context & { message: { text: string } }) => {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const reply_to_message_id = replyToMessageId(ctx);
|
||||
try {
|
||||
const response = await axios(Resources.dogApi);
|
||||
ctx.replyWithPhoto(response.data.message, {
|
||||
caption: "🐶",
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
} catch (error) {
|
||||
const message = Strings.dogApiErr.replace('{error}', error.message);
|
||||
ctx.reply(message, {
|
||||
parse_mode: 'Markdown',
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
export const catHandler = async (ctx: Context & { message: { text: string } }) => {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const apiUrl = `${Resources.catApi}?json=true`;
|
||||
const reply_to_message_id = replyToMessageId(ctx);
|
||||
try {
|
||||
const response = await axios.get(apiUrl);
|
||||
const data = response.data;
|
||||
const imageUrl = `${data.url}`;
|
||||
const reply_to_message_id = replyToMessageId(ctx);
|
||||
await ctx.replyWithPhoto(imageUrl, {
|
||||
caption: `🐱`,
|
||||
parse_mode: 'Markdown',
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
} catch (error) {
|
||||
const message = Strings.catImgErr.replace('{error}', error.message);
|
||||
ctx.reply(message, {
|
||||
parse_mode: 'Markdown',
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
await ctx.replyWithPhoto(imageUrl, {
|
||||
caption: `🐱`,
|
||||
export const soggyHandler = async (ctx: Context & { message: { text: string } }) => {
|
||||
const userInput = ctx.message.text.split(' ')[1];
|
||||
const reply_to_message_id = replyToMessageId(ctx);
|
||||
|
||||
switch (true) {
|
||||
case (userInput === "2" || userInput === "thumb"):
|
||||
ctx.replyWithPhoto(
|
||||
Resources.soggyCat2, {
|
||||
caption: Resources.soggyCat2,
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
} catch (error) {
|
||||
ctx.reply(Strings.catImgErr, {
|
||||
break;
|
||||
|
||||
case (userInput === "3" || userInput === "sticker"):
|
||||
ctx.replyWithSticker(
|
||||
Resources.soggyCatSticker,
|
||||
reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : undefined
|
||||
);
|
||||
break;
|
||||
|
||||
case (userInput === "4" || userInput === "alt"):
|
||||
ctx.replyWithPhoto(
|
||||
Resources.soggyCatAlt, {
|
||||
caption: Resources.soggyCatAlt,
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
};
|
||||
});
|
||||
break;
|
||||
|
||||
bot.command(['soggy', 'soggycat'], spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
const userInput = ctx.message.text.split(' ')[1];
|
||||
const reply_to_message_id = replyToMessageId(ctx);
|
||||
default:
|
||||
ctx.replyWithPhoto(
|
||||
Resources.soggyCat, {
|
||||
caption: Resources.soggyCat,
|
||||
parse_mode: 'Markdown',
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
break;
|
||||
};
|
||||
};
|
||||
|
||||
switch (true) {
|
||||
case (userInput === "2" || userInput === "thumb"):
|
||||
ctx.replyWithPhoto(
|
||||
Resources.soggyCat2, {
|
||||
caption: Resources.soggyCat2,
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
});
|
||||
break;
|
||||
|
||||
case (userInput === "3" || userInput === "sticker"):
|
||||
ctx.replyWithSticker(
|
||||
Resources.soggyCatSticker,
|
||||
reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : undefined
|
||||
);
|
||||
break;
|
||||
|
||||
case (userInput === "4" || userInput === "alt"):
|
||||
ctx.replyWithPhoto(
|
||||
Resources.soggyCatAlt, {
|
||||
caption: Resources.soggyCatAlt,
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
});
|
||||
break;
|
||||
|
||||
default:
|
||||
ctx.replyWithPhoto(
|
||||
Resources.soggyCat, {
|
||||
caption: Resources.soggyCat,
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
});
|
||||
break;
|
||||
};
|
||||
});
|
||||
export default (bot: Telegraf<Context>) => {
|
||||
bot.command("duck", spamwatchMiddleware, duckHandler);
|
||||
bot.command("fox", spamwatchMiddleware, foxHandler);
|
||||
bot.command("dog", spamwatchMiddleware, dogHandler);
|
||||
bot.command("cat", spamwatchMiddleware, catHandler);
|
||||
bot.command(['soggy', 'soggycat'], spamwatchMiddleware, soggyHandler);
|
||||
}
|
|
@ -5,8 +5,9 @@ import spamwatchMiddlewareModule from '../spamwatch/Middleware';
|
|||
import axios from 'axios';
|
||||
import verifyInput from '../plugins/verifyInput';
|
||||
import { Context, Telegraf } from 'telegraf';
|
||||
import { languageCode } from '../utils/language-code';
|
||||
import { replyToMessageId } from '../utils/reply-to-message-id';
|
||||
import * as schema from '../db/schema';
|
||||
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
|
||||
|
||||
const spamwatchMiddleware = spamwatchMiddlewareModule(isOnSpamWatch);
|
||||
|
||||
|
@ -29,10 +30,31 @@ export async function getDeviceByCodename(codename: string): Promise<Device | nu
|
|||
}
|
||||
}
|
||||
|
||||
export default (bot: Telegraf<Context>) => {
|
||||
async function getUserAndStrings(ctx: Context, db?: NodePgDatabase<typeof schema>): Promise<{ Strings: any, languageCode: string }> {
|
||||
let languageCode = 'en';
|
||||
if (!ctx.from) {
|
||||
const Strings = getStrings(languageCode);
|
||||
return { Strings, languageCode };
|
||||
}
|
||||
const from = ctx.from;
|
||||
if (db && from.id) {
|
||||
const dbUser = await db.query.usersTable.findMany({ where: (fields, { eq }) => eq(fields.telegramId, String(from.id)), limit: 1 });
|
||||
if (dbUser.length > 0) {
|
||||
languageCode = dbUser[0].languageCode;
|
||||
}
|
||||
}
|
||||
if (from.language_code && languageCode === 'en') {
|
||||
languageCode = from.language_code;
|
||||
console.warn('[WARN !] Falling back to Telegram language_code for user', from.id);
|
||||
}
|
||||
const Strings = getStrings(languageCode);
|
||||
return { Strings, languageCode };
|
||||
}
|
||||
|
||||
export default (bot: Telegraf<Context>, db) => {
|
||||
bot.command(['codename', 'whatis'], spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
const userInput = ctx.message.text.split(" ").slice(1).join(" ");
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
const { noCodename } = Strings.codenameCheck;
|
||||
const reply_to_message_id = replyToMessageId(ctx);
|
||||
|
||||
|
|
|
@ -5,10 +5,32 @@ import os from 'os';
|
|||
import { exec } from 'child_process';
|
||||
import { error } from 'console';
|
||||
import { Context, Telegraf } from 'telegraf';
|
||||
import { languageCode } from '../utils/language-code';
|
||||
import * as schema from '../db/schema';
|
||||
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
|
||||
|
||||
const spamwatchMiddleware = spamwatchMiddlewareModule(isOnSpamWatch);
|
||||
|
||||
async function getUserAndStrings(ctx: Context, db?: NodePgDatabase<typeof schema>): Promise<{ Strings: any, languageCode: string }> {
|
||||
let languageCode = 'en';
|
||||
if (!ctx.from) {
|
||||
const Strings = getStrings(languageCode);
|
||||
return { Strings, languageCode };
|
||||
}
|
||||
const from = ctx.from;
|
||||
if (db && from.id) {
|
||||
const dbUser = await db.query.usersTable.findMany({ where: (fields, { eq }) => eq(fields.telegramId, String(from.id)), limit: 1 });
|
||||
if (dbUser.length > 0) {
|
||||
languageCode = dbUser[0].languageCode;
|
||||
}
|
||||
}
|
||||
if (from.language_code && languageCode === 'en') {
|
||||
languageCode = from.language_code;
|
||||
console.warn('[WARN !] Falling back to Telegram language_code for user', from.id);
|
||||
}
|
||||
const Strings = getStrings(languageCode);
|
||||
return { Strings, languageCode };
|
||||
}
|
||||
|
||||
function getGitCommitHash() {
|
||||
return new Promise((resolve, reject) => {
|
||||
exec('git rev-parse --short HEAD', (error, stdout, stderr) => {
|
||||
|
@ -55,7 +77,7 @@ function getSystemInfo() {
|
|||
}
|
||||
|
||||
async function handleAdminCommand(ctx: Context & { message: { text: string } }, action: () => Promise<void>, successMessage: string, errorMessage: string) {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const { Strings } = await getUserAndStrings(ctx);
|
||||
const userId = ctx.from?.id;
|
||||
const adminArray = process.env.botAdmins ? process.env.botAdmins.split(',').map(id => parseInt(id.trim())) : [];
|
||||
if (userId && adminArray.includes(userId)) {
|
||||
|
@ -64,80 +86,72 @@ async function handleAdminCommand(ctx: Context & { message: { text: string } },
|
|||
if (successMessage) {
|
||||
ctx.reply(successMessage, {
|
||||
parse_mode: 'Markdown',
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
ctx.reply(errorMessage.replace(/{error}/g, error.message), {
|
||||
parse_mode: 'Markdown',
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
}
|
||||
} else {
|
||||
ctx.reply(Strings.noPermission, {
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default (bot: Telegraf<Context>) => {
|
||||
export default (bot: Telegraf<Context>, db) => {
|
||||
bot.command('getbotstats', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
handleAdminCommand(ctx, async () => {
|
||||
const stats = getSystemInfo();
|
||||
await ctx.reply(stats, {
|
||||
parse_mode: 'Markdown',
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
}, '', Strings.errorRetrievingStats);
|
||||
});
|
||||
|
||||
bot.command('getbotcommit', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
handleAdminCommand(ctx, async () => {
|
||||
try {
|
||||
const commitHash = await getGitCommitHash();
|
||||
await ctx.reply(Strings.gitCurrentCommit.replace(/{commitHash}/g, commitHash), {
|
||||
parse_mode: 'Markdown',
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
} catch (error) {
|
||||
ctx.reply(Strings.gitErrRetrievingCommit.replace(/{error}/g, error), {
|
||||
parse_mode: 'Markdown',
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
}
|
||||
}, '', Strings.gitErrRetrievingCommit);
|
||||
});
|
||||
|
||||
bot.command('updatebot', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
handleAdminCommand(ctx, async () => {
|
||||
try {
|
||||
const result = await updateBot();
|
||||
await ctx.reply(Strings.botUpdated.replace(/{result}/g, result), {
|
||||
parse_mode: 'Markdown',
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
} catch (error) {
|
||||
ctx.reply(Strings.errorUpdatingBot.replace(/{error}/g, error), {
|
||||
parse_mode: 'Markdown',
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
}
|
||||
}, '', Strings.errorUpdatingBot);
|
||||
});
|
||||
|
||||
bot.command('setbotname', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
const botName = ctx.message.text.split(' ').slice(1).join(' ');
|
||||
handleAdminCommand(ctx, async () => {
|
||||
await ctx.telegram.setMyName(botName);
|
||||
|
@ -145,7 +159,7 @@ export default (bot: Telegraf<Context>) => {
|
|||
});
|
||||
|
||||
bot.command('setbotdesc', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
const botDesc = ctx.message.text.split(' ').slice(1).join(' ');
|
||||
handleAdminCommand(ctx, async () => {
|
||||
await ctx.telegram.setMyDescription(botDesc);
|
||||
|
@ -153,34 +167,31 @@ export default (bot: Telegraf<Context>) => {
|
|||
});
|
||||
|
||||
bot.command('botkickme', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
handleAdminCommand(ctx, async () => {
|
||||
if (!ctx.chat) {
|
||||
ctx.reply(Strings.chatNotFound, {
|
||||
parse_mode: 'Markdown',
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
return;
|
||||
}
|
||||
ctx.reply(Strings.kickingMyself, {
|
||||
parse_mode: 'Markdown',
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
await ctx.telegram.leaveChat(ctx.chat.id);
|
||||
}, '', Strings.kickingMyselfErr);
|
||||
});
|
||||
|
||||
bot.command('getfile', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
const botFile = ctx.message.text.split(' ').slice(1).join(' ');
|
||||
|
||||
if (!botFile) {
|
||||
ctx.reply(Strings.noFileProvided, {
|
||||
parse_mode: 'Markdown',
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
@ -192,14 +203,12 @@ export default (bot: Telegraf<Context>) => {
|
|||
source: botFile,
|
||||
caption: botFile
|
||||
}, {
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
} catch (error) {
|
||||
ctx.reply(Strings.unexpectedErr.replace(/{error}/g, error.message), {
|
||||
parse_mode: 'Markdown',
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
}
|
||||
}, '', Strings.unexpectedErr);
|
||||
|
@ -217,21 +226,18 @@ export default (bot: Telegraf<Context>) => {
|
|||
if (error) {
|
||||
return ctx.reply(`\`${error.message}\``, {
|
||||
parse_mode: 'Markdown',
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
}
|
||||
if (stderr) {
|
||||
return ctx.reply(`\`${stderr}\``, {
|
||||
parse_mode: 'Markdown',
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
}
|
||||
ctx.reply(`\`${stdout}\``, {
|
||||
parse_mode: 'Markdown',
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
});
|
||||
}, '', "Nope!");
|
||||
|
@ -247,14 +253,12 @@ export default (bot: Telegraf<Context>) => {
|
|||
const result = eval(code);
|
||||
ctx.reply(`Result: ${result}`, {
|
||||
parse_mode: 'Markdown',
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
} catch (error) {
|
||||
ctx.reply(`Error: ${error.message}`, {
|
||||
parse_mode: 'Markdown',
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
}
|
||||
});
|
||||
|
|
|
@ -3,46 +3,63 @@ import { getStrings } from '../plugins/checklang';
|
|||
import { isOnSpamWatch } from '../spamwatch/spamwatch';
|
||||
import spamwatchMiddlewareModule from '../spamwatch/Middleware';
|
||||
import { Context, Telegraf } from 'telegraf';
|
||||
import { languageCode } from '../utils/language-code';
|
||||
import * as schema from '../db/schema';
|
||||
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
|
||||
|
||||
const spamwatchMiddleware = spamwatchMiddlewareModule(isOnSpamWatch);
|
||||
|
||||
function sendRandomReply(ctx: Context & { message: { text: string } }, gifUrl: string, textKey: string) {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const randomNumber = Math.floor(Math.random() * 100);
|
||||
const shouldSendGif = randomNumber > 50;
|
||||
|
||||
const caption = Strings[textKey].replace('{randomNum}', randomNumber)
|
||||
|
||||
if (shouldSendGif) {
|
||||
ctx.replyWithAnimation(gifUrl, {
|
||||
caption,
|
||||
parse_mode: 'Markdown',
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
}).catch(err => {
|
||||
const gifErr = Strings.gifErr.replace('{err}', err);
|
||||
ctx.reply(gifErr, {
|
||||
parse_mode: 'Markdown',
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
});
|
||||
});
|
||||
} else {
|
||||
ctx.reply(caption, {
|
||||
parse_mode: 'Markdown',
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
});
|
||||
async function getUserAndStrings(ctx: Context, db?: NodePgDatabase<typeof schema>): Promise<{ Strings: any, languageCode: string }> {
|
||||
let languageCode = 'en';
|
||||
if (!ctx.from) {
|
||||
const Strings = getStrings(languageCode);
|
||||
return { Strings, languageCode };
|
||||
}
|
||||
const from = ctx.from;
|
||||
if (db && from.id) {
|
||||
const dbUser = await db.query.usersTable.findMany({ where: (fields, { eq }) => eq(fields.telegramId, String(from.id)), limit: 1 });
|
||||
if (dbUser.length > 0) {
|
||||
languageCode = dbUser[0].languageCode;
|
||||
}
|
||||
}
|
||||
if (from.language_code && languageCode === 'en') {
|
||||
languageCode = from.language_code;
|
||||
console.warn('[WARN !] Falling back to Telegram language_code for user', from.id);
|
||||
}
|
||||
const Strings = getStrings(languageCode);
|
||||
return { Strings, languageCode };
|
||||
}
|
||||
|
||||
function sendRandomReply(ctx: Context & { message: { text: string } }, gifUrl: string, textKey: string, db: any) {
|
||||
getUserAndStrings(ctx, db).then(({ Strings }) => {
|
||||
const randomNumber = Math.floor(Math.random() * 100);
|
||||
const shouldSendGif = randomNumber > 50;
|
||||
const caption = Strings[textKey].replace('{randomNum}', randomNumber);
|
||||
if (shouldSendGif) {
|
||||
ctx.replyWithAnimation(gifUrl, {
|
||||
caption,
|
||||
parse_mode: 'Markdown',
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
}).catch(err => {
|
||||
const gifErr = Strings.gifErr.replace('{err}', err);
|
||||
ctx.reply(gifErr, {
|
||||
parse_mode: 'Markdown',
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
});
|
||||
} else {
|
||||
ctx.reply(caption, {
|
||||
parse_mode: 'Markdown',
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function handleDiceCommand(ctx: Context & { message: { text: string } }, emoji: string, delay: number) {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
async function handleDiceCommand(ctx: Context & { message: { text: string } }, emoji: string, delay: number, db: any) {
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
|
||||
// @ts-ignore
|
||||
const result = await ctx.sendDice({ emoji, reply_to_message_id: ctx.message.message_id });
|
||||
const result = await ctx.sendDice({ emoji, ...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {}) });
|
||||
const botResponse = Strings.funEmojiResult
|
||||
.replace('{emoji}', result.dice.emoji)
|
||||
.replace('{value}', result.dice.value);
|
||||
|
@ -50,8 +67,7 @@ async function handleDiceCommand(ctx: Context & { message: { text: string } }, e
|
|||
setTimeout(() => {
|
||||
ctx.reply(botResponse, {
|
||||
parse_mode: 'Markdown',
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
}, delay);
|
||||
}
|
||||
|
@ -60,54 +76,53 @@ function getRandomInt(max: number) {
|
|||
return Math.floor(Math.random() * (max + 1));
|
||||
}
|
||||
|
||||
export default (bot: Telegraf<Context>) => {
|
||||
export default (bot: Telegraf<Context>, db) => {
|
||||
bot.command('random', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
const randomValue = getRandomInt(10);
|
||||
const randomVStr = Strings.randomNum.replace('{number}', randomValue);
|
||||
|
||||
ctx.reply(
|
||||
randomVStr, {
|
||||
parse_mode: 'Markdown',
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
});
|
||||
|
||||
// TODO: maybe send custom stickers to match result of the roll? i think there are pre-existing ones
|
||||
bot.command('dice', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
await handleDiceCommand(ctx, '🎲', 4000);
|
||||
await handleDiceCommand(ctx, '🎲', 4000, db);
|
||||
});
|
||||
|
||||
bot.command('slot', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
await handleDiceCommand(ctx, '🎰', 3000);
|
||||
await handleDiceCommand(ctx, '<EFBFBD><EFBFBD>', 3000, db);
|
||||
});
|
||||
|
||||
bot.command('ball', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
await handleDiceCommand(ctx, '⚽', 3000);
|
||||
await handleDiceCommand(ctx, '⚽', 3000, db);
|
||||
});
|
||||
|
||||
bot.command('dart', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
await handleDiceCommand(ctx, '🎯', 3000);
|
||||
await handleDiceCommand(ctx, '🎯', 3000, db);
|
||||
});
|
||||
|
||||
bot.command('bowling', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
await handleDiceCommand(ctx, '🎳', 3000);
|
||||
await handleDiceCommand(ctx, '🎳', 3000, db);
|
||||
});
|
||||
|
||||
bot.command('idice', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
ctx.replyWithSticker(
|
||||
Resources.infiniteDice, {
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
});
|
||||
|
||||
bot.command('furry', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
sendRandomReply(ctx, Resources.furryGif, 'furryAmount');
|
||||
sendRandomReply(ctx, Resources.furryGif, 'furryAmount', db);
|
||||
});
|
||||
|
||||
bot.command('gay', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
sendRandomReply(ctx, Resources.gayFlag, 'gayAmount');
|
||||
sendRandomReply(ctx, Resources.gayFlag, 'gayAmount', db);
|
||||
});
|
||||
};
|
|
@ -9,6 +9,8 @@ import spamwatchMiddlewareModule from '../spamwatch/Middleware';
|
|||
import axios from 'axios';
|
||||
import { parse } from 'node-html-parser';
|
||||
import { getDeviceByCodename } from './codename';
|
||||
import { getStrings } from '../plugins/checklang';
|
||||
import { languageCode } from '../utils/language-code';
|
||||
|
||||
const spamwatchMiddleware = spamwatchMiddlewareModule(isOnSpamWatch);
|
||||
|
||||
|
@ -207,68 +209,130 @@ function getUsername(ctx){
|
|||
return userName;
|
||||
}
|
||||
|
||||
const deviceSelectionCache: Record<number, { results: PhoneSearchResult[], timeout: NodeJS.Timeout }> = {};
|
||||
const lastSelectionMessageId: Record<number, number> = {};
|
||||
|
||||
export default (bot) => {
|
||||
bot.command(['d', 'device'], spamwatchMiddleware, async (ctx) => {
|
||||
const userId = ctx.from.id;
|
||||
const userName = getUsername(ctx);
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
|
||||
const phone = ctx.message.text.split(" ").slice(1).join(" ");
|
||||
if (!phone) {
|
||||
return ctx.reply("Please provide the phone name.", { reply_to_message_id: ctx.message.message_id });
|
||||
return ctx.reply(Strings.gsmarenaProvidePhoneName || "[TODO: Add gsmarenaProvidePhoneName to locales] Please provide the phone name.", { ...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {}) });
|
||||
}
|
||||
|
||||
console.log("[GSMArena] Searching for", phone);
|
||||
const statusMsg = await ctx.reply(`Searching for \`${phone}\`...`, { reply_to_message_id: ctx.message.message_id, parse_mode: 'Markdown' });
|
||||
const statusMsg = await ctx.reply((Strings.gsmarenaSearchingFor || "[TODO: Add gsmarenaSearchingFor to locales] Searching for {phone}...").replace('{phone}', phone), { ...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {}), parse_mode: 'Markdown' });
|
||||
|
||||
let results = await searchPhone(phone);
|
||||
if (results.length === 0) {
|
||||
const codenameResults = await getDeviceByCodename(phone.split(" ")[0]);
|
||||
if (!codenameResults) {
|
||||
await ctx.telegram.editMessageText(ctx.chat.id, statusMsg.message_id, undefined, `No phones found for \`${phone}\`.`, { parse_mode: 'Markdown' });
|
||||
await ctx.telegram.editMessageText(ctx.chat.id, statusMsg.message_id, undefined, (Strings.gsmarenaNoPhonesFound || "[TODO: Add gsmarenaNoPhonesFound to locales] No phones found for {phone}.").replace('{phone}', phone), { parse_mode: 'Markdown' });
|
||||
return;
|
||||
}
|
||||
|
||||
await ctx.telegram.editMessageText(ctx.chat.id, statusMsg.message_id, undefined, `Searching for ${codenameResults.name}...`, { parse_mode: 'Markdown' });
|
||||
await ctx.telegram.editMessageText(ctx.chat.id, statusMsg.message_id, undefined, (Strings.gsmarenaSearchingFor || "[TODO: Add gsmarenaSearchingFor to locales] Searching for {phone}...").replace('{phone}', codenameResults.name), { parse_mode: 'Markdown' });
|
||||
const nameResults = await searchPhone(codenameResults.name);
|
||||
if (nameResults.length === 0) {
|
||||
await ctx.telegram.editMessageText(ctx.chat.id, statusMsg.message_id, undefined, `No phones found for \`${codenameResults.name}\` and \`${phone}\`.`, { parse_mode: 'Markdown' });
|
||||
await ctx.telegram.editMessageText(ctx.chat.id, statusMsg.message_id, undefined, (Strings.gsmarenaNoPhonesFoundBoth || "[TODO: Add gsmarenaNoPhonesFoundBoth to locales] No phones found for {name} and {phone}.").replace('{name}', codenameResults.name).replace('{phone}', phone), { parse_mode: 'Markdown' });
|
||||
return;
|
||||
}
|
||||
results = nameResults;
|
||||
}
|
||||
|
||||
const testUser = `<a href=\"tg://user?id=${userId}\">${userName}</a>, please select your device:`;
|
||||
const options = {
|
||||
parse_mode: 'HTML',
|
||||
reply_to_message_id: ctx.message.message_id,
|
||||
disable_web_page_preview: true,
|
||||
reply_markup: {
|
||||
inline_keyboard: results.map(result => [{ text: result.name, callback_data: `details:${result.url}:${ctx.from.id}` }])
|
||||
}
|
||||
if (deviceSelectionCache[userId]?.timeout) {
|
||||
clearTimeout(deviceSelectionCache[userId].timeout);
|
||||
}
|
||||
deviceSelectionCache[userId] = {
|
||||
results,
|
||||
timeout: setTimeout(() => { delete deviceSelectionCache[userId]; }, 5 * 60 * 1000)
|
||||
};
|
||||
await ctx.telegram.editMessageText(ctx.chat.id, statusMsg.message_id, undefined, testUser, options);
|
||||
|
||||
if (lastSelectionMessageId[userId]) {
|
||||
try {
|
||||
await ctx.telegram.editMessageText(
|
||||
ctx.chat.id,
|
||||
lastSelectionMessageId[userId],
|
||||
undefined,
|
||||
Strings.gsmarenaSelectDevice || "[TODO: Add gsmarenaSelectDevice to locales] Please select your device:",
|
||||
{
|
||||
parse_mode: 'HTML',
|
||||
reply_to_message_id: ctx.message.message_id,
|
||||
disable_web_page_preview: true,
|
||||
reply_markup: {
|
||||
inline_keyboard: results.map((result, idx) => {
|
||||
const callbackData = `gsmadetails:${idx}:${ctx.from.id}`;
|
||||
return [{ text: result.name, callback_data: callbackData }];
|
||||
})
|
||||
}
|
||||
}
|
||||
);
|
||||
} catch (e) {
|
||||
const testUser = `<a href=\"tg://user?id=${userId}\">${userName}</a>, ${Strings.gsmarenaSelectDevice || "[TODO: Add gsmarenaSelectDevice to locales] please select your device:"}`;
|
||||
const options = {
|
||||
parse_mode: 'HTML',
|
||||
reply_to_message_id: ctx.message.message_id,
|
||||
disable_web_page_preview: true,
|
||||
reply_markup: {
|
||||
inline_keyboard: results.map((result, idx) => {
|
||||
const callbackData = `gsmadetails:${idx}:${ctx.from.id}`;
|
||||
return [{ text: result.name, callback_data: callbackData }];
|
||||
})
|
||||
}
|
||||
};
|
||||
const selectionMsg = await ctx.reply(testUser, options);
|
||||
lastSelectionMessageId[userId] = selectionMsg.message_id;
|
||||
}
|
||||
} else {
|
||||
const testUser = `<a href=\"tg://user?id=${userId}\">${userName}</a>, ${Strings.gsmarenaSelectDevice || "[TODO: Add gsmarenaSelectDevice to locales] please select your device:"}`;
|
||||
const inlineKeyboard = results.map((result, idx) => {
|
||||
const callbackData = `gsmadetails:${idx}:${ctx.from.id}`;
|
||||
return [{ text: result.name, callback_data: callbackData }];
|
||||
});
|
||||
const options = {
|
||||
parse_mode: 'HTML',
|
||||
reply_to_message_id: ctx.message.message_id,
|
||||
disable_web_page_preview: true,
|
||||
reply_markup: {
|
||||
inline_keyboard: inlineKeyboard
|
||||
}
|
||||
};
|
||||
const selectionMsg = await ctx.reply(testUser, options);
|
||||
lastSelectionMessageId[userId] = selectionMsg.message_id;
|
||||
}
|
||||
await ctx.telegram.deleteMessage(ctx.chat.id, statusMsg.message_id).catch(() => {});
|
||||
});
|
||||
|
||||
bot.action(/details:(.+):(.+)/, async (ctx) => {
|
||||
const url = ctx.match[1];
|
||||
bot.action(/gsmadetails:(\d+):(\d+)/, async (ctx) => {
|
||||
const idx = parseInt(ctx.match[1]);
|
||||
const userId = parseInt(ctx.match[2]);
|
||||
const userName = getUsername(ctx);
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
|
||||
const callbackQueryUserId = ctx.update.callback_query.from.id;
|
||||
|
||||
if (userId !== callbackQueryUserId) {
|
||||
return ctx.answerCbQuery(`${userName}, you are not allowed to interact with this.`);
|
||||
return ctx.answerCbQuery(`${userName}, ${Strings.gsmarenaNotAllowed || "[TODO: Add gsmarenaNotAllowed to locales] you are not allowed to interact with this."}`);
|
||||
}
|
||||
|
||||
ctx.answerCbQuery();
|
||||
|
||||
const cache = deviceSelectionCache[userId];
|
||||
if (!cache || !cache.results[idx]) {
|
||||
return ctx.reply(Strings.gsmarenaInvalidOrExpired || "[TODO: Add gsmarenaInvalidOrExpired to locales] Whoops, invalid or expired option. Please try again.", { ...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {}) });
|
||||
}
|
||||
const url = cache.results[idx].url;
|
||||
|
||||
const phoneDetails = await checkPhoneDetails(url);
|
||||
|
||||
if (phoneDetails.name) {
|
||||
const message = formatPhone(phoneDetails);
|
||||
ctx.editMessageText(`<b><a href="tg://user?id=${userId}">${userName}</a>, these are the details of your device:</b>` + message, { parse_mode: 'HTML', disable_web_page_preview: false });
|
||||
ctx.editMessageText(`<b><a href=\"tg://user?id=${userId}\">${userName}</a>, ${Strings.gsmarenaDeviceDetails || "[TODO: Add gsmarenaDeviceDetails to locales] these are the details of your device:"}</b>` + message, { parse_mode: 'HTML', disable_web_page_preview: false });
|
||||
} else {
|
||||
ctx.reply("Error fetching phone details.", { reply_to_message_id: ctx.message.message_id });
|
||||
ctx.reply(Strings.gsmarenaErrorFetchingDetails || "[TODO: Add gsmarenaErrorFetchingDetails to locales] Error fetching phone details.", { ...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {}) });
|
||||
}
|
||||
});
|
||||
};
|
||||
|
|
|
@ -1,21 +1,38 @@
|
|||
import { getStrings } from '../plugins/checklang';
|
||||
import { isOnSpamWatch } from '../spamwatch/spamwatch';
|
||||
import spamwatchMiddlewareModule from '../spamwatch/Middleware';
|
||||
import { languageCode } from '../utils/language-code';
|
||||
import type { Context } from 'telegraf';
|
||||
|
||||
const spamwatchMiddleware = spamwatchMiddlewareModule(isOnSpamWatch);
|
||||
|
||||
async function getUserAndStrings(ctx: Context, db?: any): Promise<{ Strings: any, languageCode: string }> {
|
||||
let languageCode = 'en';
|
||||
if (!ctx.from) {
|
||||
const Strings = getStrings(languageCode);
|
||||
return { Strings, languageCode };
|
||||
}
|
||||
const from = ctx.from;
|
||||
if (db && from.id) {
|
||||
const dbUser = await db.query.usersTable.findMany({ where: (fields, { eq }) => eq(fields.telegramId, String(from.id)), limit: 1 });
|
||||
if (dbUser.length > 0) {
|
||||
languageCode = dbUser[0].languageCode;
|
||||
}
|
||||
}
|
||||
const Strings = getStrings(languageCode);
|
||||
return { Strings, languageCode };
|
||||
}
|
||||
|
||||
interface MessageOptions {
|
||||
parse_mode: string;
|
||||
disable_web_page_preview: boolean;
|
||||
reply_markup: {
|
||||
inline_keyboard: { text: any; callback_data: string; }[][];
|
||||
inline_keyboard: { text: string; callback_data: string; }[][];
|
||||
};
|
||||
reply_to_message_id?: number;
|
||||
}
|
||||
|
||||
async function sendHelpMessage(ctx, isEditing) {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
async function sendHelpMessage(ctx, isEditing, db) {
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
const botInfo = await ctx.telegram.getMe();
|
||||
const helpText = Strings.botHelp
|
||||
.replace(/{botName}/g, botInfo.first_name)
|
||||
|
@ -33,14 +50,14 @@ async function sendHelpMessage(ctx, isEditing) {
|
|||
[{ text: Strings.interactiveEmojis, callback_data: 'helpInteractive' }, { text: Strings.funnyCommands, callback_data: 'helpFunny' }],
|
||||
[{ text: Strings.lastFm.helpEntry, callback_data: 'helpLast' }, { text: Strings.animalCommands, callback_data: 'helpAnimals' }],
|
||||
[{ text: Strings.ytDownload.helpEntry, callback_data: 'helpYouTube' }, { text: Strings.ponyApi.helpEntry, callback_data: 'helpMLP' }],
|
||||
[{ text: Strings.aiCmds, callback_data: 'helpAi' }]
|
||||
[{ text: Strings.ai.helpEntry, callback_data: 'helpAi' }]
|
||||
]
|
||||
}
|
||||
};
|
||||
if (includeReplyTo) {
|
||||
const messageId = getMessageId(ctx);
|
||||
if (messageId) {
|
||||
options.reply_to_message_id = messageId;
|
||||
(options as any).reply_parameters = { message_id: messageId };
|
||||
};
|
||||
};
|
||||
return options;
|
||||
|
@ -52,78 +69,78 @@ async function sendHelpMessage(ctx, isEditing) {
|
|||
};
|
||||
}
|
||||
|
||||
export default (bot) => {
|
||||
export default (bot, db) => {
|
||||
bot.help(spamwatchMiddleware, async (ctx) => {
|
||||
await sendHelpMessage(ctx, false);
|
||||
await sendHelpMessage(ctx, false, db);
|
||||
});
|
||||
|
||||
bot.command("about", spamwatchMiddleware, async (ctx) => {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
const aboutMsg = Strings.botAbout.replace(/{sourceLink}/g, `${process.env.botSource}`);
|
||||
ctx.reply(aboutMsg, {
|
||||
parse_mode: 'Markdown',
|
||||
disable_web_page_preview: true,
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
})
|
||||
});
|
||||
|
||||
bot.on('callback_query', async (ctx) => {
|
||||
const callbackData = ctx.callbackQuery.data;
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const options = {
|
||||
parse_mode: 'Markdown',
|
||||
disable_web_page_preview: true,
|
||||
reply_markup: JSON.stringify({
|
||||
inline_keyboard: [
|
||||
[{ text: Strings.varStrings.varBack, callback_data: 'helpBack' }],
|
||||
]
|
||||
})
|
||||
};
|
||||
const options = (Strings) => ({
|
||||
parse_mode: 'Markdown',
|
||||
disable_web_page_preview: true,
|
||||
reply_markup: JSON.stringify({
|
||||
inline_keyboard: [
|
||||
[{ text: Strings.varStrings.varBack, callback_data: 'helpBack' }],
|
||||
]
|
||||
})
|
||||
});
|
||||
|
||||
switch (callbackData) {
|
||||
case 'helpMain':
|
||||
await ctx.answerCbQuery();
|
||||
await ctx.editMessageText(Strings.mainCommandsDesc, options);
|
||||
break;
|
||||
case 'helpUseful':
|
||||
await ctx.answerCbQuery();
|
||||
await ctx.editMessageText(Strings.usefulCommandsDesc, options);
|
||||
break;
|
||||
case 'helpInteractive':
|
||||
await ctx.answerCbQuery();
|
||||
await ctx.editMessageText(Strings.interactiveEmojisDesc, options);
|
||||
break;
|
||||
case 'helpFunny':
|
||||
await ctx.answerCbQuery();
|
||||
await ctx.editMessageText(Strings.funnyCommandsDesc, options);
|
||||
break;
|
||||
case 'helpLast':
|
||||
await ctx.answerCbQuery();
|
||||
await ctx.editMessageText(Strings.lastFm.helpDesc, options);
|
||||
break;
|
||||
case 'helpYouTube':
|
||||
await ctx.answerCbQuery();
|
||||
await ctx.editMessageText(Strings.ytDownload.helpDesc, options);
|
||||
break;
|
||||
case 'helpAnimals':
|
||||
await ctx.answerCbQuery();
|
||||
await ctx.editMessageText(Strings.animalCommandsDesc, options);
|
||||
break;
|
||||
case 'helpMLP':
|
||||
await ctx.answerCbQuery();
|
||||
await ctx.editMessageText(Strings.ponyApi.helpDesc, options);
|
||||
break;
|
||||
case 'helpAi':
|
||||
await ctx.answerCbQuery();
|
||||
await ctx.editMessageText(Strings.aiCmdsDesc, options);
|
||||
break;
|
||||
case 'helpBack':
|
||||
await ctx.answerCbQuery();
|
||||
await sendHelpMessage(ctx, true);
|
||||
break;
|
||||
default:
|
||||
await ctx.answerCbQuery(Strings.errInvalidOption);
|
||||
break;
|
||||
}
|
||||
bot.action('helpMain', async (ctx) => {
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
await ctx.editMessageText(Strings.mainCommandsDesc, options(Strings));
|
||||
await ctx.answerCbQuery();
|
||||
});
|
||||
bot.action('helpUseful', async (ctx) => {
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
await ctx.editMessageText(Strings.usefulCommandsDesc, options(Strings));
|
||||
await ctx.answerCbQuery();
|
||||
});
|
||||
bot.action('helpInteractive', async (ctx) => {
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
await ctx.editMessageText(Strings.interactiveEmojisDesc, options(Strings));
|
||||
await ctx.answerCbQuery();
|
||||
});
|
||||
bot.action('helpFunny', async (ctx) => {
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
await ctx.editMessageText(Strings.funnyCommandsDesc, options(Strings));
|
||||
await ctx.answerCbQuery();
|
||||
});
|
||||
bot.action('helpLast', async (ctx) => {
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
await ctx.editMessageText(Strings.lastFm.helpDesc, options(Strings));
|
||||
await ctx.answerCbQuery();
|
||||
});
|
||||
bot.action('helpYouTube', async (ctx) => {
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
await ctx.editMessageText(Strings.ytDownload.helpDesc, options(Strings));
|
||||
await ctx.answerCbQuery();
|
||||
});
|
||||
bot.action('helpAnimals', async (ctx) => {
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
await ctx.editMessageText(Strings.animalCommandsDesc, options(Strings));
|
||||
await ctx.answerCbQuery();
|
||||
});
|
||||
bot.action('helpMLP', async (ctx) => {
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
await ctx.editMessageText(Strings.ponyApi.helpDesc, options(Strings));
|
||||
await ctx.answerCbQuery();
|
||||
});
|
||||
bot.action('helpAi', async (ctx) => {
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
await ctx.editMessageText(Strings.ai.helpDesc, options(Strings));
|
||||
await ctx.answerCbQuery();
|
||||
});
|
||||
bot.action('helpBack', async (ctx) => {
|
||||
await sendHelpMessage(ctx, true, db);
|
||||
await ctx.answerCbQuery();
|
||||
});
|
||||
}
|
||||
|
|
|
@ -5,14 +5,37 @@ import spamwatchMiddlewareModule from '../spamwatch/Middleware';
|
|||
import axios from 'axios';
|
||||
import verifyInput from '../plugins/verifyInput';
|
||||
import { Context, Telegraf } from 'telegraf';
|
||||
import * as schema from '../db/schema';
|
||||
import { languageCode } from '../utils/language-code';
|
||||
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
|
||||
|
||||
const spamwatchMiddleware = spamwatchMiddlewareModule(isOnSpamWatch);
|
||||
|
||||
export default (bot: Telegraf<Context>) => {
|
||||
async function getUserAndStrings(ctx: Context, db?: NodePgDatabase<typeof schema>): Promise<{ Strings: any, languageCode: string }> {
|
||||
let languageCode = 'en';
|
||||
if (!ctx.from) {
|
||||
const Strings = getStrings(languageCode);
|
||||
return { Strings, languageCode };
|
||||
}
|
||||
const from = ctx.from;
|
||||
if (db && from.id) {
|
||||
const dbUser = await db.query.usersTable.findMany({ where: (fields, { eq }) => eq(fields.telegramId, String(from.id)), limit: 1 });
|
||||
if (dbUser.length > 0) {
|
||||
languageCode = dbUser[0].languageCode;
|
||||
}
|
||||
}
|
||||
if (from.language_code && languageCode === 'en') {
|
||||
languageCode = from.language_code;
|
||||
console.warn('[WARN !] Falling back to Telegram language_code for user', from.id);
|
||||
}
|
||||
const Strings = getStrings(languageCode);
|
||||
return { Strings, languageCode };
|
||||
}
|
||||
|
||||
export default (bot: Telegraf<Context>, db) => {
|
||||
bot.command("http", spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
const reply_to_message_id = ctx.message.message_id;
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
const userInput = ctx.message.text.split(' ')[1];
|
||||
const apiUrl = Resources.httpApi;
|
||||
const { invalidCode } = Strings.httpCodes
|
||||
|
@ -34,19 +57,19 @@ export default (bot: Telegraf<Context>) => {
|
|||
.replace("{description}", codeInfo.description);
|
||||
await ctx.reply(message, {
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
} else {
|
||||
await ctx.reply(Strings.httpCodes.notFound, {
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
};
|
||||
} catch (error) {
|
||||
const message = Strings.httpCodes.fetchErr.replace("{error}", error);
|
||||
const message = Strings.httpCodes.fetchErr.replace('{error}', error);
|
||||
ctx.reply(message, {
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
};
|
||||
});
|
||||
|
@ -63,7 +86,7 @@ export default (bot: Telegraf<Context>) => {
|
|||
if (userInput.length !== 3) {
|
||||
ctx.reply(Strings.httpCodes.invalidCode, {
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
})
|
||||
return
|
||||
}
|
||||
|
@ -74,12 +97,12 @@ export default (bot: Telegraf<Context>) => {
|
|||
await ctx.replyWithPhoto(apiUrl, {
|
||||
caption: `🐱 ${apiUrl}`,
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
} catch (error) {
|
||||
ctx.reply(Strings.catImgErr, {
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
}
|
||||
});
|
||||
|
|
|
@ -2,64 +2,81 @@ import { getStrings } from '../plugins/checklang';
|
|||
import { isOnSpamWatch } from '../spamwatch/spamwatch';
|
||||
import spamwatchMiddlewareModule from '../spamwatch/Middleware';
|
||||
import { Context, Telegraf } from 'telegraf';
|
||||
import * as schema from '../db/schema';
|
||||
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
|
||||
|
||||
const spamwatchMiddleware = spamwatchMiddlewareModule(isOnSpamWatch);
|
||||
|
||||
async function getUserInfo(ctx: Context & { message: { text: string } }) {
|
||||
const Strings = getStrings(ctx.from?.language_code || 'en');
|
||||
async function getUserAndStrings(ctx: Context, db?: NodePgDatabase<typeof schema>): Promise<{ Strings: any, languageCode: string }> {
|
||||
let languageCode = 'en';
|
||||
if (!ctx.from) {
|
||||
const Strings = getStrings(languageCode);
|
||||
return { Strings, languageCode };
|
||||
}
|
||||
const from = ctx.from;
|
||||
if (db && from.id) {
|
||||
const dbUser = await db.query.usersTable.findMany({ where: (fields, { eq }) => eq(fields.telegramId, String(from.id)), limit: 1 });
|
||||
if (dbUser.length > 0) {
|
||||
languageCode = dbUser[0].languageCode;
|
||||
}
|
||||
}
|
||||
if (from.language_code && languageCode === 'en') {
|
||||
languageCode = from.language_code;
|
||||
console.warn('[WARN !] Falling back to Telegram language_code for user', from.id);
|
||||
}
|
||||
const Strings = getStrings(languageCode);
|
||||
return { Strings, languageCode };
|
||||
}
|
||||
|
||||
async function getUserInfo(ctx: Context & { message: { text: string } }, db: any) {
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
let lastName = ctx.from?.last_name;
|
||||
if (lastName === undefined) {
|
||||
lastName = " ";
|
||||
}
|
||||
|
||||
const userInfo = Strings.userInfo
|
||||
.replace('{userName}', `${ctx.from?.first_name} ${lastName}` || Strings.varStrings.varUnknown)
|
||||
.replace('{userId}', ctx.from?.id || Strings.varStrings.varUnknown)
|
||||
.replace('{userHandle}', ctx.from?.username ? `@${ctx.from?.username}` : Strings.varStrings.varNone)
|
||||
.replace('{userPremium}', ctx.from?.is_premium ? Strings.varStrings.varYes : Strings.varStrings.varNo)
|
||||
.replace('{userLang}', ctx.from?.language_code || Strings.varStrings.varUnknown);
|
||||
|
||||
return userInfo;
|
||||
}
|
||||
|
||||
async function getChatInfo(ctx: Context & { message: { text: string } }) {
|
||||
const Strings = getStrings(ctx.from?.language_code || 'en');
|
||||
if (ctx.chat?.type === 'group' || ctx.chat?.type === 'supergroup') {
|
||||
async function getChatInfo(ctx: Context & { message: { text: string } }, db: any) {
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
if ((ctx.chat?.type === 'group' || ctx.chat?.type === 'supergroup')) {
|
||||
const chat = ctx.chat as (typeof ctx.chat & { username?: string; is_forum?: boolean });
|
||||
const chatInfo = Strings.chatInfo
|
||||
.replace('{chatId}', ctx.chat?.id || Strings.varStrings.varUnknown)
|
||||
.replace('{chatName}', ctx.chat?.title || Strings.varStrings.varUnknown)
|
||||
// @ts-ignore
|
||||
.replace('{chatHandle}', ctx.chat?.username ? `@${ctx.chat?.username}` : Strings.varStrings.varNone)
|
||||
.replace('{chatId}', chat?.id || Strings.varStrings.varUnknown)
|
||||
.replace('{chatName}', chat?.title || Strings.varStrings.varUnknown)
|
||||
.replace('{chatHandle}', chat?.username ? `@${chat.username}` : Strings.varStrings.varNone)
|
||||
.replace('{chatMembersCount}', await ctx.getChatMembersCount())
|
||||
.replace('{chatType}', ctx.chat?.type || Strings.varStrings.varUnknown)
|
||||
// @ts-ignore
|
||||
.replace('{isForum}', ctx.chat?.is_forum ? Strings.varStrings.varYes : Strings.varStrings.varNo);
|
||||
|
||||
.replace('{chatType}', chat?.type || Strings.varStrings.varUnknown)
|
||||
.replace('{isForum}', chat?.is_forum ? Strings.varStrings.varYes : Strings.varStrings.varNo);
|
||||
return chatInfo;
|
||||
} else {
|
||||
return Strings.groupOnly
|
||||
return Strings.groupOnly;
|
||||
}
|
||||
}
|
||||
|
||||
export default (bot: Telegraf<Context>) => {
|
||||
export default (bot: Telegraf<Context>, db) => {
|
||||
bot.command('chatinfo', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
const chatInfo = await getChatInfo(ctx);
|
||||
const chatInfo = await getChatInfo(ctx, db);
|
||||
ctx.reply(
|
||||
chatInfo, {
|
||||
parse_mode: 'Markdown',
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
bot.command('userinfo', spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
const userInfo = await getUserInfo(ctx);
|
||||
const userInfo = await getUserInfo(ctx, db);
|
||||
ctx.reply(
|
||||
userInfo, {
|
||||
parse_mode: 'Markdown',
|
||||
// @ts-ignore
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
}
|
||||
);
|
||||
});
|
||||
|
|
|
@ -72,7 +72,7 @@ export default (bot) => {
|
|||
return ctx.reply(Strings.lastFm.noUser, {
|
||||
parse_mode: "Markdown",
|
||||
disable_web_page_preview: true,
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
};
|
||||
|
||||
|
@ -84,7 +84,7 @@ export default (bot) => {
|
|||
ctx.reply(message, {
|
||||
parse_mode: "Markdown",
|
||||
disable_web_page_preview: true,
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
});
|
||||
|
||||
|
@ -94,12 +94,12 @@ export default (bot) => {
|
|||
const lastfmUser = users[userId];
|
||||
const genericImg = Resources.lastFmGenericImg;
|
||||
const botInfo = await ctx.telegram.getMe();
|
||||
|
||||
|
||||
if (!lastfmUser) {
|
||||
return ctx.reply(Strings.lastFm.noUserSet, {
|
||||
parse_mode: "Markdown",
|
||||
disable_web_page_preview: true,
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
};
|
||||
|
||||
|
@ -124,7 +124,7 @@ export default (bot) => {
|
|||
return ctx.reply(noRecent, {
|
||||
parse_mode: "Markdown",
|
||||
disable_web_page_preview: true,
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
};
|
||||
|
||||
|
@ -137,8 +137,8 @@ export default (bot) => {
|
|||
|
||||
if (albumMbid) {
|
||||
imageUrl = await getFromMusicBrainz(albumMbid);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (!imageUrl) {
|
||||
imageUrl = getFromLast(track);
|
||||
}
|
||||
|
@ -166,7 +166,7 @@ export default (bot) => {
|
|||
'User-Agent': `@${botInfo.username}-node-telegram-bot`
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
num_plays = response_plays.data.track.userplaycount;
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
|
@ -176,7 +176,7 @@ export default (bot) => {
|
|||
ctx.reply(message, {
|
||||
parse_mode: "Markdown",
|
||||
disable_web_page_preview: true,
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
};
|
||||
|
||||
|
@ -200,13 +200,13 @@ export default (bot) => {
|
|||
caption: message,
|
||||
parse_mode: "Markdown",
|
||||
disable_web_page_preview: true,
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
} else {
|
||||
ctx.reply(message, {
|
||||
parse_mode: "Markdown",
|
||||
disable_web_page_preview: true,
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
};
|
||||
} catch (err) {
|
||||
|
@ -217,7 +217,7 @@ export default (bot) => {
|
|||
ctx.reply(message, {
|
||||
parse_mode: "Markdown",
|
||||
disable_web_page_preview: true,
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
...(ctx.message?.message_id ? { reply_parameters: { message_id: ctx.message.message_id } } : {})
|
||||
});
|
||||
};
|
||||
});
|
||||
|
|
|
@ -3,31 +3,390 @@ import { isOnSpamWatch } from '../spamwatch/spamwatch';
|
|||
import spamwatchMiddlewareModule from '../spamwatch/Middleware';
|
||||
import { Context, Telegraf } from 'telegraf';
|
||||
import { replyToMessageId } from '../utils/reply-to-message-id';
|
||||
import { languageCode } from '../utils/language-code';
|
||||
import * as schema from '../db/schema';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { ensureUserInDb } from '../utils/ensure-user';
|
||||
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
|
||||
import { models } from './ai';
|
||||
import { langs } from '../locales/config';
|
||||
|
||||
type UserRow = typeof schema.usersTable.$inferSelect;
|
||||
|
||||
const spamwatchMiddleware = spamwatchMiddlewareModule(isOnSpamWatch);
|
||||
|
||||
export default (bot: Telegraf<Context>) => {
|
||||
bot.start(spamwatchMiddleware, async (ctx: Context) => {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const botInfo = await ctx.telegram.getMe();
|
||||
const reply_to_message_id = replyToMessageId(ctx)
|
||||
const startMsg = Strings.botWelcome.replace(/{botName}/g, botInfo.first_name);
|
||||
async function getUserAndStrings(ctx: Context, db: NodePgDatabase<typeof schema>): Promise<{ user: UserRow | null, Strings: any, languageCode: string }> {
|
||||
let user: UserRow | null = null;
|
||||
let languageCode = 'en';
|
||||
if (!ctx.from) {
|
||||
const Strings = getStrings(languageCode);
|
||||
return { user, Strings, languageCode };
|
||||
}
|
||||
const { id, language_code } = ctx.from;
|
||||
if (id) {
|
||||
const dbUser = await db.query.usersTable.findMany({ where: (fields, { eq }) => eq(fields.telegramId, String(id)), limit: 1 });
|
||||
if (dbUser.length === 0) {
|
||||
await ensureUserInDb(ctx, db);
|
||||
const newUser = await db.query.usersTable.findMany({ where: (fields, { eq }) => eq(fields.telegramId, String(id)), limit: 1 });
|
||||
if (newUser.length > 0) {
|
||||
user = newUser[0];
|
||||
languageCode = user.languageCode;
|
||||
}
|
||||
} else {
|
||||
user = dbUser[0];
|
||||
languageCode = user.languageCode;
|
||||
}
|
||||
}
|
||||
if (!user && language_code) {
|
||||
languageCode = language_code;
|
||||
console.warn('[WARN !] Falling back to Telegram language_code for user', id);
|
||||
}
|
||||
const Strings = getStrings(languageCode);
|
||||
return { user, Strings, languageCode };
|
||||
}
|
||||
|
||||
ctx.reply(startMsg, {
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
});
|
||||
type SettingsMenu = { text: string, reply_markup: any };
|
||||
function getSettingsMenu(user: UserRow, Strings: any): SettingsMenu {
|
||||
const langObj = langs.find(l => l.code === user.languageCode);
|
||||
const langLabel = langObj ? langObj.label : user.languageCode;
|
||||
return {
|
||||
text: Strings.settings.selectSetting,
|
||||
reply_markup: {
|
||||
inline_keyboard: [
|
||||
[
|
||||
{ text: `✨ ${Strings.settings.ai.aiEnabled}: ${user.aiEnabled ? Strings.settings.enabled : Strings.settings.disabled}`, callback_data: 'settings_aiEnabled' },
|
||||
{ text: `🧠 ${Strings.settings.ai.aiModel}: ${user.customAiModel}`, callback_data: 'settings_aiModel' }
|
||||
],
|
||||
[
|
||||
{ text: `🌡️ ${Strings.settings.ai.aiTemperature}: ${user.aiTemperature}`, callback_data: 'settings_aiTemperature' },
|
||||
{ text: `🌐 ${langLabel}`, callback_data: 'settings_language' }
|
||||
]
|
||||
]
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default (bot: Telegraf<Context>, db: NodePgDatabase<typeof schema>) => {
|
||||
bot.start(spamwatchMiddleware, async (ctx: Context) => {
|
||||
const { user, Strings } = await getUserAndStrings(ctx, db);
|
||||
const botInfo = await ctx.telegram.getMe();
|
||||
const reply_to_message_id = replyToMessageId(ctx);
|
||||
const startMsg = Strings.botWelcome.replace(/{botName}/g, botInfo.first_name);
|
||||
if (!user) return;
|
||||
ctx.reply(
|
||||
startMsg.replace(
|
||||
/{aiEnabled}/g,
|
||||
user.aiEnabled ? Strings.settings.enabled : Strings.settings.disabled
|
||||
).replace(
|
||||
/{aiModel}/g,
|
||||
user.customAiModel
|
||||
).replace(
|
||||
/{aiTemperature}/g,
|
||||
user.aiTemperature.toString()
|
||||
).replace(
|
||||
/{aiRequests}/g,
|
||||
user.aiRequests.toString()
|
||||
).replace(
|
||||
/{aiCharacters}/g,
|
||||
user.aiCharacters.toString()
|
||||
).replace(
|
||||
/{languageCode}/g,
|
||||
user.languageCode
|
||||
), {
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
bot.command('privacy', spamwatchMiddleware, async (ctx: any) => {
|
||||
const Strings = getStrings(ctx.from.language_code);
|
||||
const message = Strings.botPrivacy.replace("{botPrivacy}", process.env.botPrivacy);
|
||||
bot.command(["settings"], spamwatchMiddleware, async (ctx: Context) => {
|
||||
const reply_to_message_id = replyToMessageId(ctx);
|
||||
const { user, Strings } = await getUserAndStrings(ctx, db);
|
||||
if (!user) return;
|
||||
const menu = getSettingsMenu(user, Strings);
|
||||
await ctx.reply(
|
||||
menu.text,
|
||||
{
|
||||
reply_markup: menu.reply_markup,
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
const updateSettingsKeyboard = async (ctx: Context, user: UserRow, Strings: any) => {
|
||||
const menu = getSettingsMenu(user, Strings);
|
||||
await ctx.editMessageReplyMarkup(menu.reply_markup);
|
||||
};
|
||||
|
||||
bot.action('settings_aiEnabled', async (ctx) => {
|
||||
try {
|
||||
await ctx.answerCbQuery();
|
||||
const { user, Strings } = await getUserAndStrings(ctx, db);
|
||||
if (!user) return;
|
||||
await db.update(schema.usersTable)
|
||||
.set({ aiEnabled: !user.aiEnabled })
|
||||
.where(eq(schema.usersTable.telegramId, String(user.telegramId)));
|
||||
const updatedUser = (await db.query.usersTable.findMany({ where: (fields, { eq }) => eq(fields.telegramId, String(user.telegramId)), limit: 1 }))[0];
|
||||
await updateSettingsKeyboard(ctx, updatedUser, Strings);
|
||||
} catch (err) {
|
||||
console.error('Error handling settings_aiEnabled callback:', err);
|
||||
}
|
||||
});
|
||||
|
||||
bot.action('settings_aiModel', async (ctx) => {
|
||||
try {
|
||||
await ctx.answerCbQuery();
|
||||
const { user, Strings } = await getUserAndStrings(ctx, db);
|
||||
if (!user) return;
|
||||
try {
|
||||
await ctx.editMessageText(
|
||||
`${Strings.settings.ai.selectSeries}`,
|
||||
{
|
||||
reply_markup: {
|
||||
inline_keyboard: models.map(series => [
|
||||
{ text: series.label, callback_data: `selectseries_${series.name}` }
|
||||
]).concat([[
|
||||
{ text: `⬅️ ${Strings.settings.ai.back}`, callback_data: 'settings_back' }
|
||||
]])
|
||||
}
|
||||
}
|
||||
);
|
||||
} catch (err) {
|
||||
if (
|
||||
!(
|
||||
err.response.description?.includes('query is too old') ||
|
||||
err.response.description?.includes('query ID is invalid') ||
|
||||
err.response.description?.includes('message is not modified') ||
|
||||
err.response.description?.includes('message to edit not found')
|
||||
)
|
||||
)
|
||||
console.error('Unexpected Telegram error:', err);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error handling settings_aiModel callback:', err);
|
||||
}
|
||||
});
|
||||
|
||||
bot.action(/^selectseries_.+$/, async (ctx) => {
|
||||
try {
|
||||
await ctx.answerCbQuery();
|
||||
const { user, Strings } = await getUserAndStrings(ctx, db);
|
||||
if (!user) return;
|
||||
const data = (ctx.callbackQuery as any).data;
|
||||
const seriesName = data.replace('selectseries_', '');
|
||||
const series = models.find(s => s.name === seriesName);
|
||||
if (!series) return;
|
||||
const desc = user.languageCode === 'pt' ? series.descriptionPt : series.descriptionEn;
|
||||
try {
|
||||
await ctx.editMessageText(
|
||||
`${Strings.settings.ai.seriesDescription.replace('{seriesDescription}', desc)}\n\n${Strings.settings.ai.selectParameterSize.replace('{seriesLabel}', series.label)}\n\n${Strings.settings.ai.parameterSizeExplanation}`,
|
||||
{
|
||||
reply_markup: {
|
||||
inline_keyboard: series.models.map(m => [
|
||||
{ text: `${m.label} (${m.parameterSize})`, callback_data: `setmodel_${series.name}_${m.name}` }
|
||||
]).concat([[
|
||||
{ text: `⬅️ ${Strings.settings.ai.back}`, callback_data: 'settings_aiModel' }
|
||||
]])
|
||||
}
|
||||
}
|
||||
);
|
||||
} catch (err) {
|
||||
if (
|
||||
!(
|
||||
err.response.description?.includes('query is too old') ||
|
||||
err.response.description?.includes('query ID is invalid') ||
|
||||
err.response.description?.includes('message is not modified') ||
|
||||
err.response.description?.includes('message to edit not found')
|
||||
)
|
||||
)
|
||||
console.error('Unexpected Telegram error:', err);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error handling selectseries callback:', err);
|
||||
}
|
||||
});
|
||||
|
||||
bot.action(/^setmodel_.+$/, async (ctx) => {
|
||||
try {
|
||||
await ctx.answerCbQuery();
|
||||
const { user, Strings } = await getUserAndStrings(ctx, db);
|
||||
if (!user) return;
|
||||
const data = (ctx.callbackQuery as any).data;
|
||||
const parts = data.split('_');
|
||||
const seriesName = parts[1];
|
||||
const modelName = parts.slice(2).join('_');
|
||||
const series = models.find(s => s.name === seriesName);
|
||||
const model = series?.models.find(m => m.name === modelName);
|
||||
if (!series || !model) return;
|
||||
await db.update(schema.usersTable)
|
||||
.set({ customAiModel: model.name })
|
||||
.where(eq(schema.usersTable.telegramId, String(user.telegramId)));
|
||||
const updatedUser = (await db.query.usersTable.findMany({ where: (fields, { eq }) => eq(fields.telegramId, String(user.telegramId)), limit: 1 }))[0];
|
||||
const menu = getSettingsMenu(updatedUser, Strings);
|
||||
try {
|
||||
if (ctx.callbackQuery.message) {
|
||||
await ctx.editMessageText(
|
||||
menu.text,
|
||||
{
|
||||
reply_markup: menu.reply_markup,
|
||||
parse_mode: 'Markdown'
|
||||
}
|
||||
);
|
||||
} else {
|
||||
await ctx.reply(menu.text, {
|
||||
reply_markup: menu.reply_markup,
|
||||
parse_mode: 'Markdown'
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
if (
|
||||
!(
|
||||
err.response.description?.includes('query is too old') ||
|
||||
err.response.description?.includes('query ID is invalid') ||
|
||||
err.response.description?.includes('message is not modified') ||
|
||||
err.response.description?.includes('message to edit not found')
|
||||
)
|
||||
)
|
||||
console.error('[Settings] Unexpected Telegram error:', err);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error handling setmodel callback:', err);
|
||||
}
|
||||
});
|
||||
|
||||
bot.action('settings_aiTemperature', async (ctx) => {
|
||||
try {
|
||||
await ctx.answerCbQuery();
|
||||
const { user, Strings } = await getUserAndStrings(ctx, db);
|
||||
if (!user) return;
|
||||
const temps = [0.2, 0.5, 0.7, 0.9, 1.2];
|
||||
try {
|
||||
await ctx.editMessageReplyMarkup({
|
||||
inline_keyboard: temps.map(t => [{ text: t.toString(), callback_data: `settemp_${t}` }]).concat([[{ text: `⬅️ ${Strings.settings.ai.back}`, callback_data: 'settings_back' }]])
|
||||
});
|
||||
} catch (err) {
|
||||
if (
|
||||
!(
|
||||
err.response.description?.includes('query is too old') ||
|
||||
err.response.description?.includes('query ID is invalid') ||
|
||||
err.response.description?.includes('message is not modified') ||
|
||||
err.response.description?.includes('message to edit not found')
|
||||
)
|
||||
)
|
||||
console.error('Unexpected Telegram error:', err);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error handling settings_aiTemperature callback:', err);
|
||||
}
|
||||
});
|
||||
|
||||
bot.action(/^settemp_.+$/, async (ctx) => {
|
||||
try {
|
||||
await ctx.answerCbQuery();
|
||||
const { user, Strings } = await getUserAndStrings(ctx, db);
|
||||
if (!user) return;
|
||||
const data = (ctx.callbackQuery as any).data;
|
||||
const temp = parseFloat(data.replace('settemp_', ''));
|
||||
await db.update(schema.usersTable)
|
||||
.set({ aiTemperature: temp })
|
||||
.where(eq(schema.usersTable.telegramId, String(user.telegramId)));
|
||||
const updatedUser = (await db.query.usersTable.findMany({ where: (fields, { eq }) => eq(fields.telegramId, String(user.telegramId)), limit: 1 }))[0];
|
||||
await updateSettingsKeyboard(ctx, updatedUser, Strings);
|
||||
} catch (err) {
|
||||
console.error('Error handling settemp callback:', err);
|
||||
}
|
||||
});
|
||||
|
||||
bot.action('settings_language', async (ctx) => {
|
||||
try {
|
||||
await ctx.answerCbQuery();
|
||||
const { user, Strings } = await getUserAndStrings(ctx, db);
|
||||
if (!user) return;
|
||||
try {
|
||||
await ctx.editMessageReplyMarkup({
|
||||
inline_keyboard: langs.map(l => [{ text: l.label, callback_data: `setlang_${l.code}` }]).concat([[{ text: `⬅️ ${Strings.settings.ai.back}`, callback_data: 'settings_back' }]])
|
||||
});
|
||||
} catch (err) {
|
||||
if (
|
||||
!(
|
||||
err.response.description?.includes('query is too old') ||
|
||||
err.response.description?.includes('query ID is invalid') ||
|
||||
err.response.description?.includes('message is not modified') ||
|
||||
err.response.description?.includes('message to edit not found')
|
||||
)
|
||||
)
|
||||
console.error('Unexpected Telegram error:', err);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error handling settings_language callback:', err);
|
||||
}
|
||||
});
|
||||
|
||||
bot.action('settings_back', async (ctx) => {
|
||||
try {
|
||||
await ctx.answerCbQuery();
|
||||
const { user, Strings } = await getUserAndStrings(ctx, db);
|
||||
if (!user) return;
|
||||
await updateSettingsKeyboard(ctx, user, Strings);
|
||||
} catch (err) {
|
||||
console.error('Error handling settings_back callback:', err);
|
||||
}
|
||||
});
|
||||
|
||||
bot.command('privacy', spamwatchMiddleware, async (ctx: Context) => {
|
||||
const { Strings } = await getUserAndStrings(ctx, db);
|
||||
if (!ctx.from || !ctx.message) return;
|
||||
const message = Strings.botPrivacy.replace("{botPrivacy}", process.env.botPrivacy ?? "");
|
||||
ctx.reply(message, {
|
||||
parse_mode: 'Markdown',
|
||||
disable_web_page_preview: true,
|
||||
reply_to_message_id: ctx.message.message_id
|
||||
});
|
||||
} as any);
|
||||
});
|
||||
|
||||
bot.action(/^setlang_.+$/, async (ctx) => {
|
||||
try {
|
||||
await ctx.answerCbQuery();
|
||||
const { user } = await getUserAndStrings(ctx, db);
|
||||
if (!user) {
|
||||
console.log('[Settings] No user found');
|
||||
return;
|
||||
}
|
||||
const data = (ctx.callbackQuery as any).data;
|
||||
const lang = data.replace('setlang_', '');
|
||||
await db.update(schema.usersTable)
|
||||
.set({ languageCode: lang })
|
||||
.where(eq(schema.usersTable.telegramId, String(user.telegramId)));
|
||||
const updatedUser = (await db.query.usersTable.findMany({ where: (fields, { eq }) => eq(fields.telegramId, String(user.telegramId)), limit: 1 }))[0];
|
||||
const updatedStrings = getStrings(updatedUser.languageCode);
|
||||
const menu = getSettingsMenu(updatedUser, updatedStrings);
|
||||
try {
|
||||
if (ctx.callbackQuery.message) {
|
||||
await ctx.editMessageText(
|
||||
menu.text,
|
||||
{
|
||||
reply_markup: menu.reply_markup,
|
||||
parse_mode: 'Markdown'
|
||||
}
|
||||
);
|
||||
} else {
|
||||
await ctx.reply(menu.text, {
|
||||
reply_markup: menu.reply_markup,
|
||||
parse_mode: 'Markdown'
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
if (
|
||||
!(
|
||||
err.response.description?.includes('query is too old') ||
|
||||
err.response.description?.includes('query ID is invalid') ||
|
||||
err.response.description?.includes('message is not modified') ||
|
||||
err.response.description?.includes('message to edit not found')
|
||||
)
|
||||
)
|
||||
console.error('[Settings] Unexpected Telegram error:', err);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[Settings] Error handling setlang callback:', err);
|
||||
}
|
||||
});
|
||||
};
|
|
@ -24,22 +24,17 @@ async function downloadModule(moduleId: string): Promise<ModuleResult | null> {
|
|||
method: 'GET',
|
||||
responseType: 'stream',
|
||||
});
|
||||
|
||||
const disposition = response.headers['content-disposition'];
|
||||
let fileName = moduleId;
|
||||
|
||||
if (disposition && disposition.includes('filename=')) {
|
||||
fileName = disposition
|
||||
.split('filename=')[1]
|
||||
.split(';')[0]
|
||||
.replace(/['"]/g, '');
|
||||
}
|
||||
|
||||
const filePath = path.resolve(__dirname, fileName);
|
||||
|
||||
const filePath = path.join(__dirname, fileName);
|
||||
const writer = fs.createWriteStream(filePath);
|
||||
response.data.pipe(writer);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
writer.on('finish', () => resolve({ filePath, fileName }));
|
||||
writer.on('error', reject);
|
||||
|
@ -49,39 +44,41 @@ async function downloadModule(moduleId: string): Promise<ModuleResult | null> {
|
|||
}
|
||||
}
|
||||
|
||||
export default (bot: Telegraf<Context>) => {
|
||||
bot.command(['modarchive', 'tma'], spamwatchMiddleware, async (ctx) => {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const reply_to_message_id = replyToMessageId(ctx);
|
||||
const moduleId = ctx.message?.text.split(' ')[1];
|
||||
|
||||
if (Number.isNaN(moduleId) || null) {
|
||||
return ctx.reply(Strings.maInvalidModule, {
|
||||
parse_mode: "Markdown",
|
||||
...({ reply_to_message_id })
|
||||
});
|
||||
}
|
||||
const numberRegex = /^\d+$/;
|
||||
const isNumber = numberRegex.test(moduleId);
|
||||
if (isNumber) {
|
||||
const result = await downloadModule(moduleId);
|
||||
if (result) {
|
||||
const { filePath, fileName } = result;
|
||||
const regexExtension = /\.\w+$/i;
|
||||
const hasExtension = regexExtension.test(fileName);
|
||||
if (hasExtension) {
|
||||
await ctx.replyWithDocument({ source: filePath }, {
|
||||
caption: fileName,
|
||||
...({ reply_to_message_id })
|
||||
});
|
||||
fs.unlinkSync(filePath);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
export const modarchiveHandler = async (ctx: Context) => {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const reply_to_message_id = replyToMessageId(ctx);
|
||||
const moduleId = ctx.message && 'text' in ctx.message && typeof ctx.message.text === 'string'
|
||||
? ctx.message.text.split(' ')[1]?.trim()
|
||||
: undefined;
|
||||
if (!moduleId || !/^\d+$/.test(moduleId)) {
|
||||
return ctx.reply(Strings.maInvalidModule, {
|
||||
parse_mode: "Markdown",
|
||||
...({ reply_to_message_id })
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
}
|
||||
const result = await downloadModule(moduleId);
|
||||
if (result) {
|
||||
const { filePath, fileName } = result;
|
||||
const regexExtension = /\.\w+$/i;
|
||||
const hasExtension = regexExtension.test(fileName);
|
||||
if (hasExtension) {
|
||||
try {
|
||||
await ctx.replyWithDocument({ source: filePath }, {
|
||||
caption: fileName,
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
} finally {
|
||||
try { fs.unlinkSync(filePath); } catch (e) { /* ignore */ }
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
return ctx.reply(Strings.maInvalidModule, {
|
||||
parse_mode: "Markdown",
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
};
|
||||
|
||||
export default (bot: Telegraf<Context>) => {
|
||||
bot.command(['modarchive', 'tma'], spamwatchMiddleware, modarchiveHandler);
|
||||
};
|
||||
|
|
|
@ -53,34 +53,38 @@ function capitalizeFirstLetter(letter: string) {
|
|||
return letter.charAt(0).toUpperCase() + letter.slice(1);
|
||||
}
|
||||
|
||||
function sendReply(ctx: Context, text: string, reply_to_message_id?: number) {
|
||||
return ctx.reply(text, {
|
||||
parse_mode: 'Markdown',
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
}
|
||||
|
||||
function sendPhoto(ctx: Context, photo: string, caption: string, reply_to_message_id?: number) {
|
||||
return ctx.replyWithPhoto(photo, {
|
||||
caption,
|
||||
parse_mode: 'Markdown',
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
}
|
||||
|
||||
export default (bot: Telegraf<Context>) => {
|
||||
bot.command("mlp", spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const reply_to_message_id = replyToMessageId(ctx);
|
||||
|
||||
ctx.reply(Strings.ponyApi.helpDesc, {
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id, disable_web_page_preview: true })
|
||||
});
|
||||
sendReply(ctx, Strings.ponyApi.helpDesc, reply_to_message_id);
|
||||
});
|
||||
|
||||
bot.command("mlpchar", spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
const { message } = ctx;
|
||||
const reply_to_message_id = replyToMessageId(ctx);
|
||||
const Strings = getStrings(languageCode(ctx) || 'en');
|
||||
const userInput = ctx.message.text.split(' ').slice(1).join(' ').replace(" ", "+");
|
||||
const { noCharName } = Strings.ponyApi
|
||||
const userInput = message.text.split(' ').slice(1).join(' ').trim().replace(/\s+/g, '+');
|
||||
const { noCharName } = Strings.ponyApi;
|
||||
|
||||
if (verifyInput(ctx, userInput, noCharName)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// if special characters or numbers (max 30 characters)
|
||||
if (/[^a-zA-Z\s]/.test(userInput) || userInput.length > 30) {
|
||||
ctx.reply(Strings.mlpInvalidCharacter, {
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
});
|
||||
return;
|
||||
if (verifyInput(ctx, userInput, noCharName)) return;
|
||||
if (!userInput || /[^a-zA-Z\s]/.test(userInput) || userInput.length > 30) {
|
||||
return sendReply(ctx, Strings.mlpInvalidCharacter, reply_to_message_id);
|
||||
}
|
||||
|
||||
const capitalizedInput = capitalizeFirstLetter(userInput);
|
||||
|
@ -88,62 +92,29 @@ export default (bot: Telegraf<Context>) => {
|
|||
|
||||
try {
|
||||
const response = await axios(apiUrl);
|
||||
const charactersArray: Character[] = [];
|
||||
|
||||
if (Array.isArray(response.data.data)) {
|
||||
response.data.data.forEach(character => {
|
||||
let aliases: string[] = [];
|
||||
if (character.alias) {
|
||||
if (typeof character.alias === 'string') {
|
||||
aliases.push(character.alias);
|
||||
} else if (Array.isArray(character.alias)) {
|
||||
aliases = aliases.concat(character.alias);
|
||||
}
|
||||
}
|
||||
|
||||
charactersArray.push({
|
||||
id: character.id,
|
||||
name: character.name,
|
||||
alias: aliases.length > 0 ? aliases.join(', ') : Strings.varStrings.varNone,
|
||||
url: character.url,
|
||||
sex: character.sex,
|
||||
residence: character.residence ? character.residence.replace(/\n/g, ' / ') : Strings.varStrings.varNone,
|
||||
occupation: character.occupation ? character.occupation.replace(/\n/g, ' / ') : Strings.varStrings.varNone,
|
||||
kind: character.kind ? character.kind.join(', ') : Strings.varStrings.varNone,
|
||||
image: character.image
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
if (charactersArray.length > 0) {
|
||||
const data = response.data.data;
|
||||
if (Array.isArray(data) && data.length > 0) {
|
||||
const character = data[0];
|
||||
const aliases = Array.isArray(character.alias)
|
||||
? character.alias.join(', ')
|
||||
: character.alias || Strings.varStrings.varNone;
|
||||
const result = Strings.ponyApi.charRes
|
||||
.replace("{id}", charactersArray[0].id)
|
||||
.replace("{name}", charactersArray[0].name)
|
||||
.replace("{alias}", charactersArray[0].alias)
|
||||
.replace("{url}", charactersArray[0].url)
|
||||
.replace("{sex}", charactersArray[0].sex)
|
||||
.replace("{residence}", charactersArray[0].residence)
|
||||
.replace("{occupation}", charactersArray[0].occupation)
|
||||
.replace("{kind}", charactersArray[0].kind);
|
||||
|
||||
ctx.replyWithPhoto(charactersArray[0].image[0], {
|
||||
caption: `${result}`,
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id, disable_web_page_preview: true })
|
||||
});
|
||||
.replace("{id}", character.id)
|
||||
.replace("{name}", character.name)
|
||||
.replace("{alias}", aliases)
|
||||
.replace("{url}", character.url)
|
||||
.replace("{sex}", character.sex)
|
||||
.replace("{residence}", character.residence ? character.residence.replace(/\n/g, ' / ') : Strings.varStrings.varNone)
|
||||
.replace("{occupation}", character.occupation ? character.occupation.replace(/\n/g, ' / ') : Strings.varStrings.varNone)
|
||||
.replace("{kind}", Array.isArray(character.kind) ? character.kind.join(', ') : Strings.varStrings.varNone);
|
||||
sendPhoto(ctx, character.image[0], result, reply_to_message_id);
|
||||
} else {
|
||||
ctx.reply(Strings.ponyApi.noCharFound, {
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
});
|
||||
};
|
||||
} catch (error) {
|
||||
const message = Strings.ponyApi.apiErr.replace('{error}', error.message);
|
||||
ctx.reply(message, {
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
});
|
||||
};
|
||||
sendReply(ctx, Strings.ponyApi.noCharFound, reply_to_message_id);
|
||||
}
|
||||
} catch (error: any) {
|
||||
const message = Strings.ponyApi.apiErr.replace('{error}', error.message || 'Unknown error');
|
||||
sendReply(ctx, message, reply_to_message_id);
|
||||
}
|
||||
});
|
||||
|
||||
bot.command("mlpep", spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
|
@ -157,10 +128,10 @@ export default (bot: Telegraf<Context>) => {
|
|||
return;
|
||||
}
|
||||
|
||||
if (Number(userInput) > 100) {
|
||||
if (Number(userInput) > 10000) {
|
||||
ctx.reply(Strings.mlpInvalidEpisode, {
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
@ -205,21 +176,19 @@ export default (bot: Telegraf<Context>) => {
|
|||
ctx.replyWithPhoto(episodeArray[0].image, {
|
||||
caption: `${result}`,
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id, disable_web_page_preview: true })
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
} else {
|
||||
ctx.reply(Strings.ponyApi.noEpisodeFound, {
|
||||
parse_mode: 'Markdown',
|
||||
|
||||
...({ reply_to_message_id })
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
};
|
||||
} catch (error) {
|
||||
const message = Strings.ponyApi.apiErr.replace('{error}', error.message);
|
||||
ctx.reply(message, {
|
||||
parse_mode: 'Markdown',
|
||||
|
||||
...({ reply_to_message_id })
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
};
|
||||
});
|
||||
|
@ -239,7 +208,7 @@ export default (bot: Telegraf<Context>) => {
|
|||
if (/[^a-zA-Z\s]/.test(userInput) || userInput.length > 30) {
|
||||
ctx.reply(Strings.mlpInvalidCharacter, {
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
@ -289,21 +258,19 @@ export default (bot: Telegraf<Context>) => {
|
|||
ctx.replyWithPhoto(comicArray[0].image, {
|
||||
caption: `${result}`,
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id, disable_web_page_preview: true })
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
} else {
|
||||
ctx.reply(Strings.ponyApi.noComicFound, {
|
||||
parse_mode: 'Markdown',
|
||||
|
||||
...({ reply_to_message_id })
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
};
|
||||
} catch (error) {
|
||||
const message = Strings.ponyApi.apiErr.replace('{error}', error.message);
|
||||
ctx.reply(message, {
|
||||
parse_mode: 'Markdown',
|
||||
|
||||
...({ reply_to_message_id })
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
};
|
||||
});
|
||||
|
|
|
@ -9,39 +9,40 @@ import { replyToMessageId } from '../utils/reply-to-message-id';
|
|||
|
||||
const spamwatchMiddleware = spamwatchMiddlewareModule(isOnSpamWatch);
|
||||
|
||||
export default (bot: Telegraf<Context>) => {
|
||||
// TODO: this would greatly benefit from a loading message
|
||||
bot.command(["rpony", "randompony", "mlpart"], spamwatchMiddleware, async (ctx: Context & { message: { text: string } }) => {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const reply_to_message_id = replyToMessageId(ctx);
|
||||
ctx.reply(Strings.ponyApi.searching, {
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
});
|
||||
try {
|
||||
const response = await axios(Resources.randomPonyApi);
|
||||
let tags: string[] = [];
|
||||
|
||||
if (response.data.pony.tags) {
|
||||
if (typeof response.data.pony.tags === 'string') {
|
||||
tags.push(response.data.pony.tags);
|
||||
} else if (Array.isArray(response.data.pony.tags)) {
|
||||
tags = tags.concat(response.data.pony.tags);
|
||||
}
|
||||
}
|
||||
|
||||
ctx.replyWithPhoto(response.data.pony.representations.full, {
|
||||
caption: `${response.data.pony.sourceURL}\n\n${tags.length > 0 ? tags.join(', ') : ''}`,
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
});
|
||||
} catch (error) {
|
||||
const message = Strings.ponyApi.apiErr.replace('{error}', error.message);
|
||||
ctx.reply(message, {
|
||||
parse_mode: 'Markdown',
|
||||
...({ reply_to_message_id })
|
||||
});
|
||||
return;
|
||||
}
|
||||
export const randomponyHandler = async (ctx: Context & { message: { text: string } }) => {
|
||||
const Strings = getStrings(languageCode(ctx));
|
||||
const reply_to_message_id = replyToMessageId(ctx);
|
||||
ctx.reply(Strings.ponyApi.searching, {
|
||||
parse_mode: 'Markdown',
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
try {
|
||||
const response = await axios(Resources.randomPonyApi);
|
||||
let tags: string[] = [];
|
||||
|
||||
if (response.data.pony.tags) {
|
||||
if (typeof response.data.pony.tags === 'string') {
|
||||
tags.push(response.data.pony.tags);
|
||||
} else if (Array.isArray(response.data.pony.tags)) {
|
||||
tags = tags.concat(response.data.pony.tags);
|
||||
}
|
||||
}
|
||||
|
||||
ctx.replyWithPhoto(response.data.pony.representations.full, {
|
||||
caption: `${response.data.pony.sourceURL}\n\n${tags.length > 0 ? tags.join(', ') : ''}`,
|
||||
parse_mode: 'Markdown',
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
} catch (error) {
|
||||
const message = Strings.ponyApi.apiErr.replace('{error}', error.message);
|
||||
ctx.reply(message, {
|
||||
parse_mode: 'Markdown',
|
||||
...(reply_to_message_id ? { reply_parameters: { message_id: reply_to_message_id } } : {})
|
||||
});
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
export default (bot: Telegraf<Context>) => {
|
||||
bot.command(["rpony", "randompony", "mlpart"], spamwatchMiddleware, randomponyHandler);
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue