userbotsaskeds / plugins /quotes_cmd.py
saske560's picture
Upload 18 files
5321464 verified
Raw History Blame Contribute Delete
11.1 kB
"""
plugins/quotes_cmd.py β€” Citas con imagen generada por PIL.
Genera una imagen 1080x1080 con la cita en inglΓ©s y espaΓ±ol,
fondo oscuro con degradado y tipografΓ­a centrada.
Comandos:
.quote β€” Cita aleatoria como imagen
.quotetxt β€” Cita aleatoria solo como texto
.quotedaily β€” Activa/desactiva citas automΓ‘ticas cada 8 horas
Opcionales:
pip install pillow deep-translator aiohttp
"""
import asyncio
import io
import os
import textwrap
import time
from pathlib import Path
import aiohttp
from pyrogram import filters
from pyrogram.types import Message
from bot import app
from config import Config
P = Config.CMD_PREFIX
QUOTE_API = "https://zenquotes.io/api/random"
OUT_DIR = Path("output"); OUT_DIR.mkdir(exist_ok=True)
_daily_task: asyncio.Task | None = None
_daily_chat: int | None = None
_daily_on: bool = False
# ── API / TraducciΓ³n ──────────────────────────────────────────────────────────
async def _fetch_quote() -> tuple[str, str]:
async with aiohttp.ClientSession() as s:
async with s.get(QUOTE_API, timeout=aiohttp.ClientTimeout(total=10)) as r:
data = await r.json(content_type=None)
item = data[0]
return item.get("q", ""), item.get("a", "Unknown")
async def _translate(text: str) -> str:
try:
from deep_translator import GoogleTranslator
loop = asyncio.get_event_loop()
return await loop.run_in_executor(
None,
lambda: GoogleTranslator(source="auto", target="es").translate(text) or text
)
except Exception:
return text
# ── GeneraciΓ³n de imagen PIL ───────────────────────────────────────────────────
def _make_quote_image(quote_en: str, quote_es: str, author: str) -> bytes:
"""
Genera imagen 1080x1080 con:
- Fondo oscuro degradado
- Cita en espaΓ±ol (grande, blanca, centrada)
- Autor (separador + nombre)
- Cita en inglΓ©s (pequeΓ±a, gris)
Sin dependencia de fuentes externas (usa PIL default).
"""
from PIL import Image, ImageDraw, ImageFont
W, H = 1080, 1080
MARGIN = 90
MAX_W = W - MARGIN * 2
# ── Fondo degradado oscuro ────────────────────────────────────────────────
img = Image.new("RGB", (W, H), (18, 18, 28))
draw = ImageDraw.Draw(img)
# Degradado radial simulado con rectΓ‘ngulos alpha blend
for i in range(200):
alpha = int(30 * (1 - i / 200))
r = int(W / 2 * (i / 200))
cx, cy = W // 2, H // 2
draw.ellipse(
[cx - r, cy - r, cx + r, cy + r],
fill=(40, 20, 80),
outline=None,
)
# LΓ­nea decorativa izquierda
draw.rectangle([MARGIN - 6, 80, MARGIN - 2, H - 80], fill=(120, 80, 220))
# ── Fuentes ────────────────────────────────────────────────────────────────
# Intenta cargar TTF desde assets/, si no usa la default escalada
def _font(size: int):
for candidate in [
"assets/PlayfairDisplay-VariableFont_wght.ttf",
"assets/font.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf",
"/usr/share/fonts/truetype/freefont/FreeSerif.ttf",
]:
if os.path.exists(candidate):
try:
return ImageFont.truetype(candidate, size)
except Exception:
pass
return ImageFont.load_default()
font_quote = _font(46)
font_author = _font(34)
font_small = _font(28)
# ── Wrapping de texto ─────────────────────────────────────────────────────
def _wrap(text: str, font, max_w: int) -> list[str]:
words = text.split()
lines = []
cur = ""
for w in words:
test = (cur + " " + w).strip()
try:
bbox = draw.textbbox((0, 0), test, font=font)
tw = bbox[2] - bbox[0]
except Exception:
tw = len(test) * 20
if tw <= max_w:
cur = test
else:
if cur:
lines.append(cur)
cur = w
if cur:
lines.append(cur)
return lines
def _text_h(lines: list, font, spacing: int = 12) -> int:
total = 0
for ln in lines:
try:
bbox = draw.textbbox((0, 0), ln, font=font)
total += (bbox[3] - bbox[1]) + spacing
except Exception:
total += 50 + spacing
return total
lines_es = _wrap(f'"{quote_es}"', font_quote, MAX_W)
lines_en = _wrap(quote_en, font_small, MAX_W)
h_es = _text_h(lines_es, font_quote, 14)
h_sep = 60 # separador
h_aut = 50 # autor
h_en = _text_h(lines_en, font_small, 10)
h_tot = h_es + h_sep + h_aut + 30 + h_en
# ── Dibujar centrado vertical ──────────────────────────────────────────────
y = (H - h_tot) // 2
# Cita ES
for ln in lines_es:
try:
bbox = draw.textbbox((0, 0), ln, font=font_quote)
lw = bbox[2] - bbox[0]
lh = bbox[3] - bbox[1]
except Exception:
lw, lh = len(ln) * 22, 50
draw.text(((W - lw) // 2, y), ln, fill=(255, 255, 255), font=font_quote)
y += lh + 14
# Separador
y += 20
sep_w = 160
draw.rectangle([(W - sep_w) // 2, y, (W + sep_w) // 2, y + 3], fill=(140, 90, 240))
y += h_sep - 20
# Autor
aut_txt = f"β€” {author}"
try:
bbox = draw.textbbox((0, 0), aut_txt, font=font_author)
aw = bbox[2] - bbox[0]
ah = bbox[3] - bbox[1]
except Exception:
aw, ah = len(aut_txt) * 16, 40
draw.text(((W - aw) // 2, y), aut_txt, fill=(190, 150, 255), font=font_author)
y += ah + 30
# Cita EN
for ln in lines_en:
try:
bbox = draw.textbbox((0, 0), ln, font=font_small)
lw = bbox[2] - bbox[0]
lh = bbox[3] - bbox[1]
except Exception:
lw, lh = len(ln) * 12, 30
draw.text(((W - lw) // 2, y), ln, fill=(140, 140, 160), font=font_small)
y += lh + 10
# Firma abajo
firma = "πŸ€– UserBot | Quotes"
try:
bbox = draw.textbbox((0, 0), firma, font=font_small)
fw = bbox[2] - bbox[0]
except Exception:
fw = len(firma) * 12
draw.text(((W - fw) // 2, H - 55), firma, fill=(80, 80, 100), font=font_small)
# Exportar a bytes
buf = io.BytesIO()
img.save(buf, format="PNG")
return buf.getvalue()
# ── Enviar cita ───────────────────────────────────────────────────────────────
async def _send_quote_image(client, chat_id: int):
try:
quote_en, author = await _fetch_quote()
quote_es = await _translate(quote_en)
loop = asyncio.get_event_loop()
img_buf = await loop.run_in_executor(
None, _make_quote_image, quote_en, quote_es, author
)
caption = (
f"πŸ’¬ **{author}**\n\n"
f"_{quote_es}_\n\n"
f"━━━━━━━━━━\n"
f"πŸ‡¬πŸ‡§ _{quote_en}_"
)
path = OUT_DIR / f"quote_{int(time.time())}.png"
path.write_bytes(img_buf)
await client.send_photo(chat_id, str(path), caption=caption)
path.unlink(missing_ok=True)
except Exception as e:
try:
await client.send_message(chat_id, f"❌ Error generando cita: `{e}`")
except Exception:
pass
async def _daily_loop(client, chat_id: int):
while _daily_on:
await _send_quote_image(client, chat_id)
await asyncio.sleep(8 * 3600)
# ── .quote ────────────────────────────────────────────────────────────────────
@app.on_message(filters.me & filters.command("quote", prefixes=P))
async def cmd_quote(client, msg: Message):
await msg.delete()
status = await client.send_message(msg.chat.id, "πŸ–ΌοΈ **Generando cita...**")
try:
await _send_quote_image(client, msg.chat.id)
await status.delete()
except Exception as e:
await status.edit(f"❌ `{e}`")
# ── .quotetxt ─────────────────────────────────────────────────────────────────
@app.on_message(filters.me & filters.command("quotetxt", prefixes=P))
async def cmd_quotetxt(client, msg: Message):
await msg.delete()
status = await client.send_message(msg.chat.id, "πŸ“– **Buscando cita...**")
try:
quote_en, author = await _fetch_quote()
quote_es = await _translate(quote_en)
await status.edit(
f"πŸ’¬ **Cita**\n\n"
f"_{quote_es}_\n\n"
f"**β€” {author}**\n\n"
f"━━━━━━━━━━\n"
f"πŸ‡¬πŸ‡§ _{quote_en}_"
)
except Exception as e:
await status.edit(f"❌ `{e}`")
# ── .quotedaily ───────────────────────────────────────────────────────────────
@app.on_message(filters.me & filters.command("quotedaily", prefixes=P))
async def cmd_quotedaily(client, msg: Message):
global _daily_task, _daily_chat, _daily_on
await msg.delete()
if _daily_on:
_daily_on = False
if _daily_task and not _daily_task.done():
_daily_task.cancel()
try:
await _daily_task
except asyncio.CancelledError:
pass
_daily_task = None
m = await client.send_message(msg.chat.id, "⏹️ **Citas diarias desactivadas.**")
else:
_daily_on = True
_daily_chat = msg.chat.id
_daily_task = asyncio.create_task(_daily_loop(client, msg.chat.id))
m = await client.send_message(msg.chat.id,
"βœ… **Citas diarias activadas** (cada 8 h).\n"
"Primera cita en camino...")
await asyncio.sleep(5)
await m.delete()