Skip to content

Commit

Permalink
Merge pull request #70 from harmony-one/image-bot-refactoring
Browse files Browse the repository at this point in the history
Image bot menu refactoring + isValidCommand method + conversations upgrades + help command + minor changes
  • Loading branch information
theofandrich authored Aug 9, 2023
2 parents c3cb4b7 + c883ec7 commit 4a5a975
Show file tree
Hide file tree
Showing 18 changed files with 4,523 additions and 173 deletions.
72 changes: 46 additions & 26 deletions src/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { BotPayments } from "./modules/payment";
import { BotSchedule } from "./modules/schedule";
import { ConversationHandler } from "./modules/conversation-handler/";
import config from "./config";
import { commandHelpText } from "./constants";

const logger = pino({
name: "bot",
Expand All @@ -37,6 +38,8 @@ const logger = pino({
},
});



export const bot = new Bot<BotContext>(config.telegramBotAuthToken);

function createInitialSessionData(): BotSessionData {
Expand Down Expand Up @@ -118,35 +121,44 @@ const onMessage = async (ctx: OnMessageContext) => {
}
} else {
ctx.reply("Bot disabled");
return
return;
}
}
if (conversationHandler.isSupportedEvent(ctx)) {
if (ctx.session.openAi.chatGpt.isEnabled) {
const price = conversationHandler.getEstimatedPrice(ctx);
if (price > 0) {
await ctx.reply(`Processing withdraw for ${price.toFixed(2)}¢...`);
}
const isPaid = await payments.pay(ctx, price);
if (isPaid) {
return conversationHandler.onEvent(ctx)
if (conversationHandler.isValidCommand(ctx)) {
const price = conversationHandler.getEstimatedPrice(ctx);
if (price > 0) {
await ctx.reply(`Processing withdraw for ${price.toFixed(2)}¢...`);
}
const isPaid = await payments.pay(ctx, price);
if (isPaid) {
return conversationHandler
.onEvent(ctx)
.catch((e) => payments.refundPayment(e, ctx, price));
}
return;
} else {
ctx.reply("Error: Missing prompt");
return
}
} else {
ctx.reply("Bot disabled");
return
}
}
if (oneCountryBot.isSupportedEvent(ctx)) {
const price = oneCountryBot.getEstimatedPrice(ctx);
if (price > 0) {
await ctx.reply(`Processing withdraw for ${price.toFixed(2)}¢...`);
}
const isPaid = await payments.pay(ctx, price);
if (isPaid) {
return oneCountryBot
.onEvent(ctx)
return;
}
}
// if (oneCountryBot.isSupportedEvent(ctx)) {
// const price = oneCountryBot.getEstimatedPrice(ctx);
// if (price > 0) {
// await ctx.reply(`Processing withdraw for ${price.toFixed(2)}¢...`);
// }
// const isPaid = await payments.pay(ctx, price);
// if (isPaid) {
// return oneCountryBot
// .onEvent(ctx)
// .catch((e) => payments.refundPayment(e, ctx, price));
// }
// }
if (wallet.isSupportedEvent(ctx)) {
return wallet.onEvent(ctx);
}
Expand All @@ -159,14 +171,19 @@ const onMessage = async (ctx: OnMessageContext) => {
if (schedule.isSupportedEvent(ctx)) {
return schedule.onEvent(ctx);
}
// if (ctx.update.message.text && ctx.update.message.text.startsWith("/", 0)) {
// const command = ctx.update.message.text.split(' ')[0].slice(1)
// onlfy for private chats
if (ctx.update.message.chat && ctx.chat.type === 'private') {
ctx.reply(
"Command not supported.\nWrite */menu* to learn available commands",
`Command not supported.\nWrite */menu* to learn available commands`,
{
parse_mode: "Markdown",
}
);
return;
}
if (ctx.update.message.chat) {
logger.info(`Received message in chat id: ${ctx.update.message.chat.id}`);
}
};
Expand All @@ -186,12 +203,15 @@ const onCallback = async (ctx: OnCallBackQueryData) => {
};

bot.command("start", (ctx) =>
ctx.reply(`
🌟 Welcome to the Harmony One Bot! 🤖
📋 Explore all services with /menu! 📋
ctx.reply(commandHelpText,{
parse_mode: "Markdown",
})
);

💲 Send money to your /balance to start! 🚀`)
bot.command("help", (ctx) =>
ctx.reply(commandHelpText,{
parse_mode: "Markdown",
})
);

bot.command("menu", async (ctx) => {
Expand Down
3 changes: 2 additions & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ export default {
},
chatGpt: {
isEnabled: Boolean(parseInt(process.env.CHAT_GPT_ENABLED || "1")),
model: process.env.CHATGPT_MODEL || "gpt-3.5-turbo",
//hard coded gpt-4
model: "gpt-4",
},
},
country: {
Expand Down
49 changes: 48 additions & 1 deletion src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export enum MenuIds {
MAIN_MENU = "main-menu",
IMAGE_MENU = 'image-menu-main',
QR_BOT_MAIN = "qrbot-menu-main",
QR_BOT_CHANGE_OPTIONS = "qrbot-menu-change-options",
QR_BOT_CHANGE_MARGIN = "qrbot-menu-change-margin",
Expand All @@ -20,4 +21,50 @@ export const menuText = {
backButton: 'Back to Main Menu',
menuName: 'Main Menu',
},
}
imageMenu: {
menuName: '👨‍🎨 Image Generation',
backButton: 'Back to previous menu',
helpText: `👨‍🎨 Image Generation
Help text for this menu
`,

}
}

export const commandHelpText = `*Commands*
/start - Begin interaction with the bot
/help - Access help information
*Wallet*
/botfund check funds available for services
/wallet
/wallet send <ADDRESS> <AMOUNT>** to send ONE
/walletconnect
*Voice Memo*
Send or forward a voice message (.m4a) to @HarmonyOneAIBot for a full transcript and summary
*QR Code Generation*
/qr <LINK> <PROMPTS>
*ChatGPT*
/chat <TEXT>
*Image Generation*
/image <PROMPT>
/images <PROMPT>
`


// /help - this help message
// /wallet - 🏦 Wallet
// /ask - 🖋️ ChatGPT 4
// /images - 🎨 Image Generation
// /qr - 📷 QR Generation
// /register - 🌐 1.country

// *EVENTS*
// The bot will produce a summary audio transcript when uploading a voice message.
4 changes: 3 additions & 1 deletion src/modules/1country/pages/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,7 @@ export const oneCountryMainMenu = new Menu<BotContext>(MenuIds.ONE_COUNTRY_MAIN)
.url("Go to 1.country", "https://1.country")
.row()
.back(menuText.mainMenu.backButton, (ctx) => {
ctx.editMessageText(menuText.mainMenu.menuName);
ctx.editMessageText(menuText.mainMenu.menuName).catch((ex) => {
console.log('### ex', ex);
});
});
12 changes: 12 additions & 0 deletions src/modules/1country/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import config from "../../../config";
import { OnCallBackQueryData, OnMessageContext } from "../../types";

export const formatONEAmount = (num: number | string) => {
const twoDecimalsFormatter = new Intl.NumberFormat("en-US", {
Expand Down Expand Up @@ -30,3 +31,14 @@ export const getUrl = (url: string, fullUrl = true) => {
? url.concat(config.country.tld)
: url;
};

export const getCommandNamePrompt = (
ctx: OnMessageContext | OnCallBackQueryData
) => {
const commandName = ctx.message?.text?.split(" ")[0].slice(1) || "";
const prompt = ctx.match as string;
return {
commandName,
prompt,
};
};
30 changes: 23 additions & 7 deletions src/modules/conversation-handler/conversationCountry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,13 @@ export async function conversationDomainName(
let helpCommand = false;
let domainAvailable = false;
let msgId = 0;
msgId = (await ctx.reply("Checking name...")).message_id;
msgId = (
await ctx.reply(
domain !== "" ? "Checking name..." : "Write a domain name"
)
).message_id;
while (true) {
if (!helpCommand) {
if (!helpCommand && domain !== "") {
const validate = validateDomainName(domain);
if (!validate.valid) {
ctx.reply(validate.error, {
Expand Down Expand Up @@ -69,7 +73,11 @@ export async function conversationDomainName(
// maxMilliseconds: 60000
// });
const userPrompt = cleanInput(userInput.msg.text);
if (userPrompt.toLocaleLowerCase().includes("rent") && domainAvailable) {
if (
(userPrompt.toLocaleLowerCase().includes("rent") ||
userPrompt.toLocaleLowerCase().includes("/rent")) &&
domainAvailable
) {
let keyboard = new InlineKeyboard()
.webApp(
"Rent in 1.country",
Expand All @@ -84,17 +92,26 @@ export async function conversationDomainName(
reply_markup: keyboard,
});
break;
} else if (userPrompt.toLocaleLowerCase().includes("rent")) {
} else if (
userPrompt.toLocaleLowerCase().includes("rent") ||
userPrompt.toLocaleLowerCase().includes("/rent")
) {
ctx.reply("Keep writing options", {
parse_mode: "Markdown",
});
helpCommand = true;
} else if (userPrompt.toLocaleLowerCase().includes("end")) {
} else if (
userPrompt.toLocaleLowerCase().includes("end") ||
userPrompt.toLocaleLowerCase().includes("/end")
) {
ctx.reply(appText.endChat, {
parse_mode: "Markdown",
});
break;
} else if (userPrompt.toLocaleLowerCase().includes("help")) {
} else if (
userPrompt.toLocaleLowerCase().includes("help") ||
userPrompt.toLocaleLowerCase().includes("/help")
) {
helpCommand = true;
ctx.reply(`${appText.gptHelpText}`, {
parse_mode: "Markdown",
Expand All @@ -111,4 +128,3 @@ export async function conversationDomainName(
logger.error("##conversationGountry Error:", e);
}
}

44 changes: 30 additions & 14 deletions src/modules/conversation-handler/conversationGpt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,22 +34,30 @@ export async function conversationGpt(
}
);
let chat: ChatConversation[] = [];
// console.log('prompt', ctx.match)
// console.log('CTX', ctx.chat)
const initialPrompt = ctx.match as string;
if (initialPrompt) {
chat.push({ content: initialPrompt, role: "user" });
} else {
chat = [...conversation.session.openAi.chatGpt.chatConversation]
chat = [...conversation.session.openAi.chatGpt.chatConversation];
}
let usage = 0;
let price = 0;
let totalPrice = 0
let totalPrice = 0;
let helpCommand = false;
let msgId = 0;
msgId = (await ctx.reply(appText.generatingText,{
parse_mode: "Markdown",
})).message_id;
msgId = (
await ctx.reply(
chat.length > 0 ? appText.generatingText : appText.introText,
{
parse_mode: "Markdown",
}
)
).message_id;
// console.log('messageID', msgId)
while (true) {
if (!helpCommand) {
if (!helpCommand && chat.length > 0) {
const response = await conversation.external(() => {
const payload = {
conversation: chat,
Expand All @@ -61,11 +69,11 @@ export async function conversationGpt(
chat.push({ content: response.completion, role: "system" });
usage += response.usage;
price = response.price;
totalPrice += price
totalPrice += price;
ctx.api.editMessageText(ctx.chat?.id!, msgId, response.completion!, {
parse_mode: "Markdown",
});

// await ctx.reply();
conversation.session.openAi.chatGpt.chatConversation = [...chat];
const isPay = await conversation.external(() => {
Expand All @@ -74,7 +82,7 @@ export async function conversationGpt(
if (!isPay) {
ctx.reply(appText.gptChatPaymentIssue, {
parse_mode: "Markdown",
})
});
break;
}
}
Expand All @@ -84,14 +92,20 @@ export async function conversationGpt(
// maxMilliseconds: 300000 // 5min
// });
const userPrompt = userInput?.msg?.text;
if (userPrompt.toLocaleLowerCase().includes("end")) {
if (
userPrompt.toLocaleLowerCase().includes("end") ||
userPrompt.toLocaleLowerCase().includes("/end")
) {
conversation.session.openAi.chatGpt.chatConversation = [];
await ctx.reply(
`${appText.gptChatEnd} ${usage} (${totalPrice.toFixed(2)}¢)`
);
break;
}
if (userPrompt.toLocaleLowerCase().includes("help")) {
if (
userPrompt.toLocaleLowerCase().includes("help") ||
userPrompt.toLocaleLowerCase().includes("/help")
) {
await ctx.reply(`${appText.gptHelpText}`, {
parse_mode: "Markdown",
});
Expand All @@ -102,9 +116,11 @@ export async function conversationGpt(
content: userPrompt!,
role: "user",
});
msgId = (await ctx.reply(appText.generatingText,{
parse_mode: "Markdown",
})).message_id;
msgId = (
await ctx.reply(appText.generatingText, {
parse_mode: "Markdown",
})
).message_id;
}
}
return;
Expand Down
Loading

0 comments on commit 4a5a975

Please sign in to comment.