Download modules/music.py from ABO3MR/df: direct link, hf CLI and curl.
- Browser
- Download file 14.2 kB
-
https://huggingface.co/spaces/ABO3MR/df/resolve/main/modules/music.py
- Command line
-
hf download hf://spaces/ABO3MR/df/modules/music.py
-
curl -L -o music.py https://huggingface.co/spaces/ABO3MR/df/resolve/main/modules/music.py
14.2 kB
| """الموسيقى والتحكم في الكول + تصميم كارت تشغيل احترافي يدمج صورة السورس (assets/music_bg.png) مع غلاف الأغنية | |
| + أوامر التحكم (شغل/تشغيل/تخطي/استكمال/ايقاف مؤقت/تكرار/خلط/ايقاف/شغال/القائمة/مين مشغل/مين في الكول).""" | |
| import asyncio | |
| import io | |
| import os | |
| import random | |
| import urllib.request | |
| from PIL import Image, ImageDraw, ImageFont | |
| from telegram import InlineKeyboardButton, InlineKeyboardMarkup | |
| from telegram.ext import CallbackQueryHandler | |
| from core.router import exact, prefix | |
| from core import ranks as R | |
| from core.store import settings | |
| from strings_ar import S | |
| import config | |
| _client = None | |
| _calls = None | |
| _ready = False | |
| _queues = {} # chat_id -> list of {url, title, duration, thumb, requester} | |
| _current = {} # chat_id -> {url, title, duration, thumb, requester, loop} | |
| def _make_now_playing_card(title, duration, requester, thumb_url=None): | |
| """ينشئ كارت تشغيل احترافي يدمج assets/music_bg.png مع غلاف الأغنية.""" | |
| bg_path = config.ASSETS / "music_bg.png" | |
| if bg_path.exists(): | |
| canvas = Image.open(bg_path).convert("RGBA").resize((1280, 720)) | |
| else: | |
| canvas = Image.new("RGBA", (1280, 720), (18, 20, 32, 255)) | |
| # طبقة تعتيم خفيفة لوضوح النص | |
| overlay = Image.new("RGBA", (1280, 720), (0, 0, 0, 125)) | |
| canvas = Image.alpha_composite(canvas, overlay) | |
| draw = ImageDraw.Draw(canvas) | |
| # جلب غلاف الأغنية وإضافته داخل إطار أبيض أنيق على اليسار | |
| if thumb_url: | |
| try: | |
| req = urllib.request.Request(thumb_url, headers={"User-Agent": "Mozilla/5.0"}) | |
| with urllib.request.urlopen(req, timeout=6) as resp: | |
| cover = Image.open(io.BytesIO(resp.read())).convert("RGBA") | |
| w, h = cover.size | |
| side = min(w, h) | |
| cover = cover.crop(((w - side) // 2, (h - side) // 2, (w + side) // 2, (h + side) // 2)).resize((430, 430)) | |
| draw.rectangle([72, 132, 526, 586], fill=(255, 255, 255, 240)) | |
| canvas.paste(cover, (84, 144), cover) | |
| except Exception: | |
| pass | |
| # شريط التقدم (Progress Bar) | |
| draw.line([(580, 470), (1180, 470)], fill=(210, 210, 220, 220), width=6) | |
| draw.ellipse([760, 456, 788, 484], fill=(255, 255, 255, 255)) | |
| # كتابة العنوان والمدة | |
| try: | |
| font_lg = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 44) | |
| font_md = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 30) | |
| except Exception: | |
| font_lg = ImageFont.load_default() | |
| font_md = ImageFont.load_default() | |
| bot_title = settings.get("global", "bot_name", "") or config.BOT_NAME | |
| draw.text((580, 180), f"{bot_title} PLAYING", fill=(255, 255, 255, 255), font=font_lg) | |
| draw.text((580, 260), (title or "Audio")[:34], fill=(235, 235, 245, 240), font=font_md) | |
| draw.text((580, 325), f"By: {(requester or '')[:26]}", fill=(195, 200, 220, 220), font=font_md) | |
| draw.text((580, 500), "00:00", fill=(230, 230, 230, 255), font=font_md) | |
| draw.text((1090, 500), str(duration or "LIVE"), fill=(230, 230, 230, 255), font=font_md) | |
| buf = io.BytesIO() | |
| canvas.convert("RGB").save(buf, format="JPEG", quality=90) | |
| buf.seek(0) | |
| buf.name = "now_playing.jpg" | |
| return buf | |
| def _player_kb(bot_username=""): | |
| rows = [ | |
| [ | |
| InlineKeyboardButton("▷", callback_data="ms:resume"), | |
| InlineKeyboardButton("❚❚", callback_data="ms:pause"), | |
| InlineKeyboardButton("↻", callback_data="ms:loop"), | |
| InlineKeyboardButton("⏭", callback_data="ms:skip"), | |
| InlineKeyboardButton("▢", callback_data="ms:stop"), | |
| ] | |
| ] | |
| if bot_username: | |
| rows.append([InlineKeyboardButton("➕ أضفني لمجموعتك", url=f"https://t.me/{bot_username}?startgroup=true")]) | |
| return InlineKeyboardMarkup(rows) | |
| async def start_music(): | |
| global _client, _calls, _ready | |
| if not (config.API_ID and config.API_HASH and config.ASSISTANT_SESSION): | |
| return | |
| try: | |
| from pyrogram import Client | |
| from pytgcalls import PyTgCalls | |
| _client = Client("assistant", api_id=config.API_ID, api_hash=config.API_HASH, | |
| session_string=config.ASSISTANT_SESSION) | |
| _calls = PyTgCalls(_client) | |
| await _calls.start() | |
| _ready = True | |
| except Exception: | |
| _ready = False | |
| def _yt_search(query): | |
| if "://" in query or query.startswith("-"): | |
| raise ValueError("search_only") | |
| import yt_dlp | |
| with yt_dlp.YoutubeDL({"format": "bestaudio/best", "quiet": True, "noplaylist": True}) as y: | |
| info = y.extract_info(f"ytsearch1:{query}", download=False)["entries"][0] | |
| dur_s = int(info.get("duration") or 0) | |
| dur = f"{dur_s // 60}:{dur_s % 60:02d}" if dur_s else "LIVE" | |
| return { | |
| "url": info["url"], | |
| "title": info.get("title", query), | |
| "duration": dur, | |
| "thumb": info.get("thumbnail"), | |
| } | |
| async def _can_play(update): | |
| if settings.get(update.effective_chat.id, "music_admin_only", False): | |
| if await R.effective_level(update) < R.level("ادمن"): | |
| await update.message.reply_text("✧︙التشغيل متاح للمشرفين فقط في المجموعه.") | |
| return False | |
| return True | |
| async def play(update, ctx, arg): | |
| if not await _can_play(update): | |
| return | |
| if not _ready: | |
| await update.message.reply_text(S["music_off"]) | |
| return | |
| if not arg.strip(): | |
| await update.message.reply_text("✧︙اكتب: شغل + اسم الأغنية 🎶") | |
| return | |
| msg = await update.message.reply_text("🔍 جاري البحث والتجهيز...") | |
| try: | |
| info = await asyncio.wait_for(asyncio.to_thread(_yt_search, arg.strip()), timeout=40) | |
| except Exception: | |
| await msg.edit_text(S["music_fail"]) | |
| return | |
| info["requester"] = update.effective_user.first_name | |
| cid = update.effective_chat.id | |
| q = _queues.setdefault(cid, []) | |
| q.append(info) | |
| if len(q) == 1: | |
| from pytgcalls.types import MediaStream | |
| await _calls.play(cid, MediaStream(info["url"])) | |
| _current[cid] = {**info, "loop": False} | |
| me = await ctx.bot.get_me() | |
| cap = ( | |
| f"🎧 <b>STARTED STREAMING</b>\n\n" | |
| f"▸ <b>TITLE:</b> {info['title']}\n" | |
| f"▸ <b>DURATION:</b> {info['duration']}\n" | |
| f"▸ <b>REQUESTED BY:</b> {info['requester']}" | |
| ) | |
| try: | |
| card = await asyncio.to_thread( | |
| _make_now_playing_card, info["title"], info["duration"], info["requester"], info.get("thumb") | |
| ) | |
| await msg.delete() | |
| await update.message.reply_photo(card, caption=cap, parse_mode="HTML", reply_markup=_player_kb(me.username)) | |
| except Exception: | |
| await msg.edit_text(cap, parse_mode="HTML", reply_markup=_player_kb(me.username)) | |
| else: | |
| await msg.edit_text(S["music_queue_added"].format(title=info["title"])) | |
| async def stop(update, ctx, arg=""): | |
| if not _ready: | |
| await update.message.reply_text(S["music_off"]) | |
| return | |
| cid = update.effective_chat.id | |
| _queues.pop(cid, None) | |
| _current.pop(cid, None) | |
| try: | |
| await _calls.leave_call(cid) | |
| except Exception: | |
| pass | |
| await update.message.reply_text(S["music_stopped"]) | |
| async def pause(update, ctx, arg=""): | |
| if not _ready: | |
| await update.message.reply_text(S["music_off"]) | |
| return | |
| await _calls.pause_stream(update.effective_chat.id) | |
| await update.message.reply_text(S["music_paused"]) | |
| async def resume(update, ctx, arg=""): | |
| if not _ready: | |
| await update.message.reply_text(S["music_off"]) | |
| return | |
| await _calls.resume_stream(update.effective_chat.id) | |
| await update.message.reply_text(S["music_resumed"]) | |
| async def skip(update, ctx, arg=""): | |
| if not _ready: | |
| await update.message.reply_text(S["music_off"]) | |
| return | |
| cid = update.effective_chat.id | |
| q = _queues.get(cid, []) | |
| if len(q) > 1: | |
| q.pop(0) | |
| nxt = q[0] | |
| from pytgcalls.types import MediaStream | |
| await _calls.play(cid, MediaStream(nxt["url"])) | |
| _current[cid] = {**nxt, "loop": False} | |
| await update.message.reply_text(S["music_play"].format(title=nxt["title"])) | |
| else: | |
| await stop(update, ctx) | |
| async def toggle_loop(update, ctx, arg=""): | |
| cid = update.effective_chat.id | |
| cur = _current.get(cid) | |
| if not cur: | |
| await update.message.reply_text("✧︙لا يوجد مقطع قيد التشغيل حالياً.") | |
| return | |
| cur["loop"] = not cur.get("loop", False) | |
| await update.message.reply_text(f"🔁 التكرار: {'مفعل ✓' if cur['loop'] else 'معطل ✗'}") | |
| async def shuffle_q(update, ctx, arg=""): | |
| q = _queues.get(update.effective_chat.id, []) | |
| if len(q) <= 2: | |
| await update.message.reply_text("✧︙القائمة قصيرة جداً للخلط.") | |
| return | |
| head, rest = q[0], q[1:] | |
| random.shuffle(rest) | |
| _queues[update.effective_chat.id] = [head] + rest | |
| await update.message.reply_text("🔀 تم خلط قائمة التشغيل ✅") | |
| async def now_playing(update, ctx, arg=""): | |
| cur = _current.get(update.effective_chat.id) | |
| if not cur: | |
| await update.message.reply_text("✧︙لا يوجد شيء شغال حالياً.") | |
| return | |
| await update.message.reply_text(f"🎵 الشغال حالياً: {cur['title']}\n⏱ المدة: {cur['duration']}\n👤 بواسطة: {cur['requester']}") | |
| async def show_queue(update, ctx, arg=""): | |
| q = _queues.get(update.effective_chat.id, []) | |
| if not q: | |
| await update.message.reply_text("✧︙قائمة التشغيل فارغة.") | |
| return | |
| lines = ["📜 قائمة التشغيل:"] + [f"{i}. {x['title']} ({x['duration']})" for i, x in enumerate(q[:15], 1)] | |
| await update.message.reply_text("\n".join(lines)) | |
| async def play_for_all(update, ctx, arg=""): | |
| if await R.effective_level(update) < R.level("ادمن"): | |
| await update.message.reply_text(S["need_rank"]) | |
| return | |
| settings.set(update.effective_chat.id, "music_admin_only", False) | |
| await update.message.reply_text("🎶 التشغيل متاح الآن للجميع ✅") | |
| async def play_for_admin(update, ctx, arg=""): | |
| if await R.effective_level(update) < R.level("ادمن"): | |
| await update.message.reply_text(S["need_rank"]) | |
| return | |
| settings.set(update.effective_chat.id, "music_admin_only", True) | |
| await update.message.reply_text("🎶 التشغيل متاح الآن للمشرفين فقط ✅") | |
| async def who_in_call(update, ctx, arg=""): | |
| if not _ready or not _calls: | |
| await update.message.reply_text("⌯ لا توجد مكالمة نشطة مربوطة بالبوت حالياً.") | |
| return | |
| try: | |
| parts = await _calls.get_participants(update.effective_chat.id) | |
| if not parts: | |
| await update.message.reply_text("⌯ المكالمة الصوتية فارغة حالياً.") | |
| return | |
| lines = ["⌯ الاعضاء الموجودين في المكالمة :\n"] | |
| for i, p in enumerate(parts, 1): | |
| st = "يتكلم 🎙️" if not getattr(p, "muted", True) else "ساكت" | |
| lines.append(f"⌯ {i} - `{p.user_id}` › {st}") | |
| lines.append(f"\n⌯ عدد الموجودين : {len(parts)}") | |
| await update.message.reply_text("\n".join(lines), parse_mode="Markdown") | |
| except Exception: | |
| await update.message.reply_text("⌯ تعذّر قراءة أعضاء المكالمة حالياً.") | |
| async def open_call(update, ctx, arg=""): | |
| await update.message.reply_text(S["call_opened"]) | |
| async def close_call(update, ctx, arg=""): | |
| await stop(update, ctx) | |
| async def cb(update, ctx): | |
| q = update.callback_query | |
| act = q.data.split(":")[1] | |
| if not _ready: | |
| await q.answer("خدمة الكول غير مفعلة.", show_alert=True) | |
| return | |
| cid = q.message.chat.id | |
| try: | |
| if act == "pause": | |
| await _calls.pause_stream(cid) | |
| await q.answer("⏸️ إيقاف مؤقت") | |
| elif act == "resume": | |
| await _calls.resume_stream(cid) | |
| await q.answer("▶️ استكمال") | |
| elif act == "loop": | |
| if cid in _current: | |
| _current[cid]["loop"] = not _current[cid].get("loop", False) | |
| await q.answer("🔁 تم تبديل التكرار") | |
| elif act == "skip": | |
| await q.answer("⏭️ تخطي") | |
| q_list = _queues.get(cid, []) | |
| if len(q_list) > 1: | |
| q_list.pop(0) | |
| from pytgcalls.types import MediaStream | |
| await _calls.play(cid, MediaStream(q_list[0]["url"])) | |
| _current[cid] = {**q_list[0], "loop": False} | |
| else: | |
| await _calls.leave_call(cid) | |
| _queues.pop(cid, None) | |
| _current.pop(cid, None) | |
| elif act == "stop": | |
| await _calls.leave_call(cid) | |
| _queues.pop(cid, None) | |
| _current.pop(cid, None) | |
| await q.answer("⏹️ تم الإيقاف") | |
| except Exception: | |
| await q.answer("تعذّر تنفيذ الأمر.", show_alert=True) | |
| HANDLERS = [CallbackQueryHandler(cb, pattern=r"^ms:")] | |