Python

Программирование бота Funny Cites для Max и для Telegram

Поставил себе небольшую задачу по программированию бота, который выдает цитаты на русском языке по запросу. Программную часть бота сначала написал для Telegram, а затем сделал копию функционала, но для работы в Max.

Результат работы:

Для Telegram: @funnycitesbot

Для MAX: @id781615914025_1_bot

Для генерации цитат использовал программу fortune для linux с ключом «ru». Код бота для Telegram занял всего 60 строк кода.

import telebot
from telebot.types import ReplyKeyboardMarkup, KeyboardButton
import os
import subprocess
from dotenv import load_dotenv

dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
if os.path.exists(dotenv_path):
    load_dotenv(dotenv_path)


class TelegramBot:
    def __init__(self, token):
        self.bot = telebot.TeleBot(token)
        self.init_keyboards()
        self.register_handlers()

    def init_keyboards(self):
        self.keyboard_start = ReplyKeyboardMarkup(resize_keyboard=True)
        button_another = KeyboardButton('ЕЩЁ')
        self.keyboard_start.add(button_another)

    def register_handlers(self):

        @self.bot.message_handler(commands=['start'])
        def handle_start(message):
            self.bot.send_message(message.chat.id, 'При нажатии на кнопку ЕЩЁ появляется новая цитата', 
                                  reply_markup=self.keyboard_start)
        

        @self.bot.message_handler(content_types=["text"])
        def handle_text(message):
            result = subprocess.run(['/usr/games/fortune', 'ru'], capture_output=True, text=True)
            self.bot.send_message(message.chat.id, 
                result.stdout, 
                reply_markup=self.keyboard_start)
                
                
    def run(self):
        print("Бот запущен...")
        self.bot.polling(none_stop=True, interval=0)


class BotManager:
    
    @staticmethod
    def create_and_run():
        token = os.getenv('TOKEN')
        if not token:
            raise ValueError("Токен не найден. Проверьте файл .env")
        
        bot = TelegramBot(token)
        bot.run()


if __name__ == '__main__':
    try:
        BotManager.create_and_run()
    except Exception as e:
        print(f"Ошибка при запуске бота: {e}")

Код аналогичного бота для MAX оказался немного длиннее — 88 строк кода.

from maxapi import Bot, Dispatcher, F
from maxapi.utils.inline_keyboard import InlineKeyboardBuilder
from maxapi.types import (
    CallbackButton,
    BotStarted,
    Command,
    MessageCreated,
    MessageCallback
)
import asyncio
import os
import subprocess
from dotenv import load_dotenv

dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
if os.path.exists(dotenv_path):
    load_dotenv(dotenv_path)


class MaxBot:
    def __init__(self, token):
        self.bot = Bot(token)
        self.dp = Dispatcher()
        self.init_keyboards()
        self.register_handlers()

    def init_keyboards(self):
        self.keyboard_start = InlineKeyboardBuilder()
        self.keyboard_start.row(
            CallbackButton(
                text='ЕЩЁ',
                payload='another'
            ),
        )

    def register_handlers(self):

        @self.dp.bot_started()
        async def bot_started(event: BotStarted):
            await event.bot.send_message(
                chat_id=event.chat_id,
                text='Привет! Отправь мне /start'
            )

        @self.dp.message_created(Command('start'))
        async def handle_start(event: MessageCreated):
            await event.message.answer(
                text='При нажатии на кнопку ЕЩЁ появляется новая цитата', 
                attachments=[
                    self.keyboard_start.as_markup(),
                ]
            )

        @self.dp.message_callback(F.callback.payload == 'another')
        async def anotherCallback(event: MessageCallback):
            result = subprocess.run(['/usr/games/fortune', 'ru'], capture_output=True, text=True)
            await event.message.answer(
                text=result.stdout, 
                attachments=[
                    self.keyboard_start.as_markup(),
                ]
            )  
  
    async def run(self):
        print("Бот запущен...")
        await self.dp.start_polling(self.bot)


class BotManager:
    
    @staticmethod
    async def create_and_run():
        token = os.getenv('TOKEN')
        if not token:
            raise ValueError("Токен не найден. Проверьте файл .env")
        
        bot = MaxBot(token)
        await bot.run()
        


async def main():
    try:
        await BotManager.create_and_run()
    except Exception as e:
        print(f"❌ Ошибка при запуске бота: {e}")

if __name__ == '__main__':
    asyncio.run(main())

Я постарался повторить функционал в точности как в Telegram.

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *

двадцать − 12 =