From 275470f174aaaa7bdc10acae6d54b777835290af Mon Sep 17 00:00:00 2001 From: Dmitry Afanasyev <71835315+Balshgit@users.noreply.github.com> Date: Tue, 26 Sep 2023 22:04:45 +0300 Subject: [PATCH] add keyboard (#13) --- README.md | 2 +- bot_microservice/constants.py | 14 ++++++++- bot_microservice/core/commands.py | 49 +++++++++++++++++++++++++++--- bot_microservice/core/handlers.py | 34 +++++++++++++++++++-- bot_microservice/core/keyboards.py | 13 ++++++++ 5 files changed, 103 insertions(+), 9 deletions(-) create mode 100644 bot_microservice/core/keyboards.py diff --git a/README.md b/README.md index 2a035a4..d2f0b79 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ install service - sudo cp scripts/chat-gpt.service /etc/systemd/system + sudo cp scripts/gpt_chat_bot.service /etc/systemd/system ```bash cd ~/PycharmProjects/chat_gpt_bot diff --git a/bot_microservice/constants.py b/bot_microservice/constants.py index 5612e69..18c206a 100644 --- a/bot_microservice/constants.py +++ b/bot_microservice/constants.py @@ -1,4 +1,4 @@ -from enum import StrEnum +from enum import IntEnum, StrEnum, auto AUDIO_SEGMENT_DURATION = 120 * 1000 @@ -6,6 +6,18 @@ API_PREFIX = "/api" CHAT_GPT_BASE_URL = "http://chat_service:8858/backend-api/v2/conversation" +class BotStagesEnum(IntEnum): + about_me = auto() + website = auto() + help = auto() + about_bot = auto() + + +class BotEntryPoints(IntEnum): + start_routes = auto() + end = auto() + + class LogLevelEnum(StrEnum): CRITICAL = "critical" ERROR = "error" diff --git a/bot_microservice/core/commands.py b/bot_microservice/core/commands.py index 9e84437..7cc9e6a 100644 --- a/bot_microservice/core/commands.py +++ b/bot_microservice/core/commands.py @@ -1,27 +1,66 @@ import asyncio import random import tempfile +from urllib.parse import urljoin from uuid import uuid4 import httpx -from constants import CHAT_GPT_BASE_URL +from constants import CHAT_GPT_BASE_URL, BotEntryPoints +from core.keyboards import main_keyboard from core.utils import SpeechToTextService from httpx import AsyncClient, AsyncHTTPTransport from loguru import logger from settings.config import settings -from telegram import Update +from telegram import InlineKeyboardMarkup, Update from telegram.ext import ContextTypes +async def main_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: + """Send message on `/start`.""" + if not update.message: + return BotEntryPoints.end + reply_markup = InlineKeyboardMarkup(main_keyboard) + await update.message.reply_text("Выберете команду:", reply_markup=reply_markup) + return BotEntryPoints.start_routes + + +async def about_me(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: + if not update.effective_message: + return None + await update.effective_message.reply_text( + 'Автор бота: *Дмитрий Афанасьев*\n\nTg nickname: *Balshtg*', parse_mode='MarkdownV2' + ) + + +async def about_bot(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: + if not update.effective_message: + return None + await update.effective_message.reply_text( + "Бот использует бесплатную модель Chat-GPT3.5 для ответов на вопросы. " + "Принимает запросы на разных языках. \n\n Бот так же умеет переводить голосовые сообщения в текст" + "просто пришлите голосовуху и получите поток сознания без запятых в виде текста", + parse_mode='MarkdownV2', + ) + + +async def website(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: + if not update.effective_message: + return None + website = urljoin(settings.DOMAIN, f"{settings.URL_PREFIX}/chat") + await update.effective_message.reply_text(f"Веб версия: {website}") + + async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """Send a message when the command /help is issued.""" - if not update.message: + if not update.effective_message: return None - await update.message.reply_text( + reply_markup = InlineKeyboardMarkup(main_keyboard) + await update.effective_message.reply_text( "Help!", disable_notification=True, - api_kwargs={"text": "Hello World"}, + api_kwargs={"text": "Список основных команд:"}, + reply_markup=reply_markup, ) diff --git a/bot_microservice/core/handlers.py b/bot_microservice/core/handlers.py index 0712005..40d5e46 100644 --- a/bot_microservice/core/handlers.py +++ b/bot_microservice/core/handlers.py @@ -1,8 +1,22 @@ from dataclasses import dataclass, field from typing import Any -from core.commands import ask_question, help_command, voice_recognize -from telegram.ext import CommandHandler, MessageHandler, filters +from constants import BotEntryPoints, BotStagesEnum +from core.commands import ( + about_me, + ask_question, + help_command, + main_command, + voice_recognize, + website, +) +from telegram.ext import ( + CallbackQueryHandler, + CommandHandler, + ConversationHandler, + MessageHandler, + filters, +) @dataclass @@ -18,3 +32,19 @@ bot_event_handlers = BotEventHandlers() bot_event_handlers.add_handler(CommandHandler("help", help_command)) bot_event_handlers.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, ask_question)) bot_event_handlers.add_handler(MessageHandler(filters.VOICE | filters.AUDIO, voice_recognize)) +bot_event_handlers.add_handler( + ConversationHandler( + entry_points=[CommandHandler("start", main_command)], + states={ + BotEntryPoints.start_routes: [ + CallbackQueryHandler(about_me, pattern="^" + str(BotStagesEnum.about_me) + "$"), + CallbackQueryHandler(website, pattern="^" + str(BotStagesEnum.website) + "$"), + CallbackQueryHandler(help_command, pattern="^" + str(BotStagesEnum.help) + "$"), + ], + }, + fallbacks=[CommandHandler("start", main_command)], + ) +) +bot_event_handlers.add_handler(CallbackQueryHandler(about_me, pattern="^" + str(BotStagesEnum.about_me) + "$")) +bot_event_handlers.add_handler(CallbackQueryHandler(website, pattern="^" + str(BotStagesEnum.website) + "$")) +bot_event_handlers.add_handler(CallbackQueryHandler(help_command, pattern="^" + str(BotStagesEnum.help) + "$")) diff --git a/bot_microservice/core/keyboards.py b/bot_microservice/core/keyboards.py new file mode 100644 index 0000000..c295ff1 --- /dev/null +++ b/bot_microservice/core/keyboards.py @@ -0,0 +1,13 @@ +from constants import BotStagesEnum +from telegram import InlineKeyboardButton + +main_keyboard = [ + [ + InlineKeyboardButton("Обо мне", callback_data=str(BotStagesEnum.about_me)), + InlineKeyboardButton("Веб версия", callback_data=str(BotStagesEnum.website)), + ], + [ + InlineKeyboardButton("Помощь", callback_data=str(BotStagesEnum.help)), + InlineKeyboardButton("О боте", callback_data=str(BotStagesEnum.help)), + ], +]