Files
myfirstprogram/addons/send_message/handlers.py
T

134 lines
5.4 KiB
Python

from config import Config
import aiohttp
from aiogram.types import BufferedInputFile
from utils.antispam import admin_required
from aiogram import Dispatcher, Bot
from aiogram.types import Message
from models.state import BotState
from aiogram.filters import Command
from logging import getLogger
logger = getLogger(__name__)
API_URL = "http://127.0.0.1:7700/speak"
def register_handlers(dp: Dispatcher, state: BotState, bot: Bot):
@dp.message(Command("vadmin"))
@admin_required(0)
async def vadmin(message: Message):
parts = message.text.split(maxsplit=1)
if len(parts) < 2:
await message.reply("❗ Укажи текст после /vadmin")
return
phrase = parts[1]
# Запрос к TTS API
async with aiohttp.ClientSession() as session:
async with session.post(API_URL, json={"text": phrase}) as resp:
if resp.status != 200:
await message.reply("Ошибка генерации аудио")
return
audio_bytes = await resp.read()
audio_file = BufferedInputFile(audio_bytes, filename="speech.wav")
# Рассылка в чаты
for chat_id in Config.CHAT_IDS:
try:
await bot.send_audio(chat_id, audio=audio_file, caption="🎙 Текст")
except Exception as e:
await message.reply(f"Не удалось отправить в {chat_id}: {e}")
await message.reply("✅ Озвучка разослана.")
@dp.message(Command("admin"))
@admin_required(0)
async def admin(message: Message):
raw_text = message.text or message.caption
if not raw_text and not (message.photo or message.document or message.audio or message.video):
await message.reply("❌ Укажи текст или прикрепи файл/медиа: /admin <сообщение>")
return
# Отрезаем саму команду (/admin)
args = raw_text.split(maxsplit=1) if raw_text else []
text_to_send = args[1] if len(args) > 1 else ""
for chat_id in Config.CHAT_IDS:
try:
if message.photo:
# Фото
photo = message.photo[-1].file_id
await bot.send_photo(chat_id, photo, caption=text_to_send)
elif message.document:
# Документ
await bot.send_document(chat_id, message.document.file_id, caption=text_to_send)
elif message.audio:
# Аудио (музыка)
await bot.send_audio(chat_id, message.audio.file_id, caption=text_to_send)
elif message.video:
# Видео
await bot.send_video(chat_id, message.video.file_id, caption=text_to_send)
else:
# Только текст
await bot.send_message(chat_id, text_to_send)
logger.info(f"Сообщение отправлено в чат {chat_id}")
except Exception as e:
logger.error(f"Ошибка при отправке в чат {chat_id}: {e}")
await message.answer("✅ Сообщение отправлено.")
@dp.message(Command("iadmin"))
@admin_required(0)
async def id_admin(message: Message):
raw_text = message.text or message.caption
if not raw_text and not (message.photo or message.document or message.audio or message.video):
await message.reply("❌ Укажи ID чата и текст или прикрепи файл/медиа: /iadmin <chat_id> <сообщение>")
return
# Отрезаем саму команду (/iadmin)
args = raw_text.split(maxsplit=2) if raw_text else []
if len(args) < 2:
await message.reply("❌ Укажи ID чата: /iadmin <chat_id> <сообщение>")
return
try:
chat_id = int(args[1]) # первый аргумент — ID чата
except ValueError:
await message.reply("❌ Неверный формат chat_id")
return
text_to_send = args[2] if len(args) > 2 else ""
try:
if message.photo:
# Фото
photo = message.photo[-1].file_id
await bot.send_photo(chat_id, photo, caption=text_to_send)
elif message.document:
# Документ
await bot.send_document(chat_id, message.document.file_id, caption=text_to_send)
elif message.audio:
# Аудио (музыка)
await bot.send_audio(chat_id, message.audio.file_id, caption=text_to_send)
elif message.video:
# Видео
await bot.send_video(chat_id, message.video.file_id, caption=text_to_send)
else:
# Только текст
await bot.send_message(chat_id, text_to_send)
logger.info(f"Сообщение отправлено в чат {chat_id}")
await message.answer("✅ Сообщение отправлено.")
except Exception as e:
logger.error(f"Ошибка при отправке в чат {chat_id}: {e}")
await message.answer(f"❌ Ошибка при отправке: {e}")