Spaces:
Paused
Paused
File size: 11,069 Bytes
5321464 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 | """
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()
|