[FEATURE] Add AI-based /ask command (complementing #54) #56

Merged
lucmsilva651 merged 14 commits from ai-features into main 2025-06-28 19:22:15 +00:00
5 changed files with 59 additions and 20 deletions
Showing only changes of commit f57901ff6b - Show all commits

View file

@ -14,21 +14,18 @@ interface Device {
brand: string;
codename: string;
model: string;
name: string;
}
async function getDeviceList({ Strings, ctx }: { Strings: any, ctx: Context & { message: { text: string } } }) {
const reply_to_message_id = replyToMessageId(ctx);
export async function getDeviceByCodename(codename: string): Promise<Device | null> {
try {
const response = await axios.get(Resources.codenameApi);
return response.data
const jsonRes = response.data;
const deviceDetails = jsonRes[codename];
if (!deviceDetails) return null;
return deviceDetails.find((item: Device) => item.brand) || deviceDetails[0];
} catch (error) {
const message = Strings.codenameCheck.apiErr
.replace('{error}', error.message);
return ctx.reply(message, {
parse_mode: "Markdown",
...({ reply_to_message_id })
});
return null;
}
}
@ -43,18 +40,15 @@ export default (bot: Telegraf<Context>) => {
return;
}
const jsonRes = await getDeviceList({ Strings, ctx })
const phoneSearch = Object.keys(jsonRes).find((codename) => codename === userInput);
const device = await getDeviceByCodename(userInput);
if (!phoneSearch) {
if (!device) {
return ctx.reply(Strings.codenameCheck.notFound, {
parse_mode: "Markdown",
...({ reply_to_message_id })
});
}
const deviceDetails = jsonRes[phoneSearch];
const device = deviceDetails.find((item: Device) => item.brand) || deviceDetails[0];
const message = Strings.codenameCheck.resultMsg
.replace('{brand}', device.brand)
.replace('{codename}', userInput)

View file

@ -8,6 +8,7 @@ import { isOnSpamWatch } from '../spamwatch/spamwatch';
import spamwatchMiddlewareModule from '../spamwatch/Middleware';
import axios from 'axios';
import { parse } from 'node-html-parser';
import { getDeviceByCodename } from './codename';
const spamwatchMiddleware = spamwatchMiddlewareModule(isOnSpamWatch);
@ -216,12 +217,27 @@ export default (bot) => {
return ctx.reply("Please provide the phone name.", { reply_to_message_id: ctx.message.message_id });
}
const results = await searchPhone(phone);
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' });
let results = await searchPhone(phone);
if (results.length === 0) {
return ctx.reply("No phones found.", { reply_to_message_id: ctx.message.message_id });
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' });
return;
}
await ctx.telegram.editMessageText(ctx.chat.id, statusMsg.message_id, undefined, `Searching for ${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' });
return;
}
results = nameResults;
}
const testUser = `<a href="tg://user?id=${userId}">${userName}</a>, please select your device:`;
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,
@ -230,8 +246,7 @@ export default (bot) => {
inline_keyboard: results.map(result => [{ text: result.name, callback_data: `details:${result.url}:${ctx.from.id}` }])
}
};
ctx.reply(testUser, options);
await ctx.telegram.editMessageText(ctx.chat.id, statusMsg.message_id, undefined, testUser, options);
});
bot.action(/details:(.+):(.+)/, async (ctx) => {

View file

@ -74,6 +74,15 @@ export default (bot: Telegraf<Context>) => {
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;
}
const capitalizedInput = capitalizeFirstLetter(userInput);
const apiUrl = `${Resources.ponyApi}/character/${capitalizedInput}`;
@ -148,6 +157,14 @@ export default (bot: Telegraf<Context>) => {
return;
}
if (Number(userInput) > 100) {
ctx.reply(Strings.mlpInvalidEpisode, {
parse_mode: 'Markdown',
...({ reply_to_message_id })
});
return;
}
const apiUrl = `${Resources.ponyApi}/episode/by-overall/${userInput}`;
try {
@ -218,6 +235,15 @@ export default (bot: Telegraf<Context>) => {
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;
}
const apiUrl = `${Resources.ponyApi}/comics-story/${userInput}`;
try {

View file

@ -86,6 +86,8 @@
"catImgErr": "Sorry, but I couldn't get the cat photo you wanted.",
"catGifErr": "Sorry, but I couldn't get the cat GIF you wanted.",
"dogImgErr": "Sorry, but I couldn't get the dog photo you wanted.",
"mlpInvalidCharacter": "Please provide a valid character name.",
"mlpInvalidEpisode": "Please provide a valid episode number.",
"foxApiErr": "An error occurred while fetching data from the API.\n\n`{error}`",
"duckApiErr": "An error occurred while fetching data from the API.\n\n`{error}`",
"httpCodes": {

View file

@ -86,6 +86,8 @@
"catImgErr": "Desculpe, mas não consegui obter a foto do gato que você queria.",
"catGifErr": "Desculpe, mas não consegui obter o GIF do gato que você queria.",
"dogImgErr": "Desculpe, mas não consegui obter a foto do cacbhorro que você queria.",
"mlpInvalidCharacter": "Por favor, forneça um nome de personagem válido.",
"mlpInvalidEpisode": "Por favor, forneça um número de episódio válido.",
"foxApiErr": "Ocorreu um erro ao buscar dados da API.\n\n`{error}`",
"duckApiErr": "Ocorreu um erro ao buscar dados da API.\n\n`{error}`",
"httpCodes": {