Download modules/werewolf.py from ABO3MR/df: direct link, hf CLI and curl.
- Browser
- Download file 38.3 kB
-
https://huggingface.co/spaces/ABO3MR/df/resolve/main/modules/werewolf.py
- Command line
-
hf download hf://spaces/ABO3MR/df/modules/werewolf.py
-
curl -L -o werewolf.py https://huggingface.co/spaces/ABO3MR/df/resolve/main/modules/werewolf.py
38.3 kB
| """لعبة المستذئب المصرية الكاملة (مدمجة مباشرة داخل البوت باستخدام python-telegram-bot + SQLite).""" | |
| import asyncio | |
| import html | |
| import random | |
| import sqlite3 | |
| import threading | |
| import time | |
| from collections import Counter | |
| from telegram import InlineKeyboardButton, InlineKeyboardMarkup | |
| from telegram.ext import CallbackQueryHandler | |
| from core.router import exact | |
| from core import ranks as R | |
| from config import STATE | |
| MIN_PLAYERS = 4 | |
| MAX_PLAYERS = 20 | |
| LOBBY_TIME = 60 | |
| NIGHT_TIME = 45 | |
| DAY_TIME = 45 | |
| LYNCH_TIME = 45 | |
| HUNTER_TIME = 20 | |
| DB_FILE = str(STATE / "werewolf_eg.db") | |
| ROLES = { | |
| "villager": {"name": "قروي غلبان 🧑🌾", "team": "village", "desc": "إنت قروي على باب الله.. شغلتك ترغي الصبح وتشك في الناس وتصوّت عشان تشنقوا الديابة قبل ما يتعشوا بيكم!"}, | |
| "wolf": {"name": "ديب 🐺", "team": "wolves", "desc": "إنت ديب جعان! كل ليلة بتختار واحد من أهل البلد تتعشى بيه لحد ما تسيطروا على البلد كلها."}, | |
| "seer": {"name": "العرّاف 🔮", "team": "village", "desc": "عندك الحاسة السادسة! كل ليلة بتختار لاعب وتعرف دوره الحقيقي في السر عشان تفضح الديابة الصبح."}, | |
| "fool": {"name": "المخرّف 🤪", "team": "village", "desc": "فاكر نفسه عرّاف! البوت بيقوله إنه عرّاف بس كل ليلة بيديله كشف غلط عشان الدنيا تولّع!"}, | |
| "guardian": {"name": "الحارس 🛡", "team": "village", "desc": "إنت البودي جارد بتاع البلد! كل ليلة بتحمي لاعب من هجوم الديابة أو السفاح (مينفعش تحمي نفس الشخص ليلتين ورا بعض)."}, | |
| "hunter": {"name": "الصياد 🔫", "team": "village", "desc": "ماشي ببندقيتك في جيبك.. لو الديابة أكلوك أو البلد شنقوك، بتضرب آخر طلقة وتاخد واحد معاك!"}, | |
| "mayor": {"name": "العمدة 🎩", "team": "village", "desc": "كبير البلد وكلمتك مسموعة! صوتك في تصويت الشنق الصبح بيتحسب بـ صوتين في السر."}, | |
| "tanner": {"name": "المجنون 🃏", "team": "tanner", "desc": "إنت بايعها خالص! هدفك الوحيد تخلي أهل البلد يتجننوا ويشنقوك الصبح.. لو اتشنقت تكسب اللعبة لوحدك فوراً!"}, | |
| "cupid": {"name": "كيوبيد 💘", "team": "village", "desc": "في أول ليلة بس بتربط اتنين ببعض بسهم الحب.. لو واحد فيهم مات التاني بيموت وراه من الحسرة فوراً!"}, | |
| "traitor": {"name": "الخاين 🐍", "team": "village", "desc": "إنت قروي في البطاقة وبتظهر للعرّاف كقروي.. بس أول ما كل الديابة يموتوا بتتحول لديب وتكمل مكانهم!"}, | |
| "serial_killer": {"name": "السفاح 🔪", "team": "sk", "desc": "إنت ماشي بمزاجك وفريق لوحدك! كل ليلة بتقتل لاعب.. ولو الديابة هجموا عليك بتقتل واحد منهم وتفلت!"}, | |
| } | |
| WOLF_DEATH_LINES = [ | |
| "🩸 لقينا {victim} متقطع حتت قدام بيته.. الديابة اتعشوا بيه ومسابوش فتفوتة!", | |
| "🩸 صحينا على صويت.. الديابة دخلوا على {victim} بالليل وخلّصوا عليه!", | |
| "🩸 {victim} نسي يقفل الشباك بالليل، والديابة قاموا معاه بالواجب وزيادة!", | |
| ] | |
| SK_DEATH_LINES = [ | |
| "🔪 لقينا {victim} مقتول بدم بارد ومكتوب جنبه توقيع <b>السفاح</b>!", | |
| "🔪 السفاح كان ليه مزاج يقتل الليلة.. وضحيته كان {victim}!", | |
| ] | |
| def esc(text): | |
| return html.escape(str(text or "")) | |
| def mention(uid, name): | |
| return f'<a href="tg://user?id={uid}">{esc(name)}</a>' | |
| class WWDatabase: | |
| def __init__(self, path): | |
| self.path = path | |
| self.lock = threading.Lock() | |
| with self.lock, sqlite3.connect(self.path) as conn: | |
| conn.execute(""" | |
| CREATE TABLE IF NOT EXISTS users ( | |
| user_id INTEGER PRIMARY KEY, | |
| name TEXT, | |
| games_played INTEGER DEFAULT 0, | |
| games_won INTEGER DEFAULT 0, | |
| games_survived INTEGER DEFAULT 0 | |
| ) | |
| """) | |
| conn.commit() | |
| def touch(self, uid, name): | |
| with self.lock, sqlite3.connect(self.path) as conn: | |
| conn.execute( | |
| "INSERT INTO users (user_id, name) VALUES (?, ?) ON CONFLICT(user_id) DO UPDATE SET name = excluded.name", | |
| (uid, name), | |
| ) | |
| conn.commit() | |
| def record(self, uid, name, won, survived): | |
| with self.lock, sqlite3.connect(self.path) as conn: | |
| conn.execute( | |
| """INSERT INTO users (user_id, name, games_played, games_won, games_survived) | |
| VALUES (?, ?, 1, ?, ?) | |
| ON CONFLICT(user_id) DO UPDATE SET | |
| name = excluded.name, games_played = games_played + 1, | |
| games_won = games_won + excluded.games_won, | |
| games_survived = games_survived + excluded.games_survived""", | |
| (uid, name, 1 if won else 0, 1 if survived else 0), | |
| ) | |
| conn.commit() | |
| def stats(self, uid): | |
| with self.lock, sqlite3.connect(self.path) as conn: | |
| return conn.execute( | |
| "SELECT name, games_played, games_won, games_survived FROM users WHERE user_id = ?", (uid,) | |
| ).fetchone() | |
| def top(self, limit=10): | |
| with self.lock, sqlite3.connect(self.path) as conn: | |
| return conn.execute( | |
| "SELECT user_id, name, games_won, games_played FROM users WHERE games_played > 0 ORDER BY games_won DESC, games_played ASC LIMIT ?", | |
| (limit,), | |
| ).fetchall() | |
| def total_users(self): | |
| with self.lock, sqlite3.connect(self.path) as conn: | |
| row = conn.execute("SELECT COUNT(*) FROM users").fetchone() | |
| return row[0] if row else 0 | |
| class Player: | |
| def __init__(self, uid, name): | |
| self.id = uid | |
| self.name = name | |
| self.role = "villager" | |
| self.alive = True | |
| self.lover_id = None | |
| def link(self): | |
| return mention(self.id, self.name) | |
| db = WWDatabase(DB_FILE) | |
| games = {} | |
| class WerewolfGame: | |
| def __init__(self, bot, bot_username, chat_id, creator_id): | |
| self.bot = bot | |
| self.bot_username = bot_username | |
| self.chat_id = chat_id | |
| self.creator_id = creator_id | |
| self.phase_event = asyncio.Event() | |
| self.hunter_event = asyncio.Event() | |
| self.cancel_event = asyncio.Event() | |
| self.state = "LOBBY" | |
| self.phase_id = 0 | |
| self.day_num = 0 | |
| self.cancelled = False | |
| self.force_start_flag = False | |
| self.lobby_end_time = time.time() + LOBBY_TIME | |
| self.players = {} | |
| self.player_order = [] | |
| self.wolf_votes = {} | |
| self.seer_targets = {} | |
| self.guardian_target = None | |
| self.last_guardian_target = None | |
| self.sk_target = None | |
| self.cupid_picks = [] | |
| self.lynch_votes = {} | |
| self.active_hunter_id = None | |
| self.hunter_target = None | |
| async def send(self, chat_id, text, reply_markup=None): | |
| try: | |
| return await self.bot.send_message( | |
| chat_id, text, parse_mode="HTML", reply_markup=reply_markup, disable_web_page_preview=True | |
| ) | |
| except Exception: | |
| return None | |
| def alive_players(self): | |
| return [self.players[uid] for uid in self.player_order if self.players[uid].alive] | |
| def by_role(self, role, alive_only=True): | |
| return [self.players[u] for u in self.player_order if self.players[u].role == role and (not alive_only or self.players[u].alive)] | |
| def join_kb(self): | |
| return InlineKeyboardMarkup([[InlineKeyboardButton("🐺 ادخل اللعبة حالاً", url=f"https://t.me/{self.bot_username}?start=join_{self.chat_id}")]]) | |
| def _kb(self, targets, action, include_skip=False): | |
| rows = [] | |
| for i in range(0, len(targets), 2): | |
| row = [InlineKeyboardButton(targets[i].name, callback_data=f"ww:{self.chat_id}:{self.phase_id}:{action}:{targets[i].id}")] | |
| if i + 1 < len(targets): | |
| row.append(InlineKeyboardButton(targets[i + 1].name, callback_data=f"ww:{self.chat_id}:{self.phase_id}:{action}:{targets[i + 1].id}")) | |
| rows.append(row) | |
| if include_skip: | |
| rows.append([InlineKeyboardButton("⏭ مش هصوّت (تخطي)", callback_data=f"ww:{self.chat_id}:{self.phase_id}:{action}:0")]) | |
| return InlineKeyboardMarkup(rows) | |
| async def add_player(self, uid, name): | |
| if self.state != "LOBBY": | |
| return "STARTED" | |
| if uid in self.players: | |
| return "ALREADY" | |
| if len(self.players) >= MAX_PLAYERS: | |
| return "FULL" | |
| pm = await self.send(uid, "✅ <b>منوّر يا بطل!</b> دخلت لعبة <b>المستذئب</b> بنجاح.\nاستنى لحد ما نبدأ وهبعتلك دورك هنا في السر 🤫") | |
| if not pm: | |
| return "NO_PM" | |
| if self.state != "LOBBY" or uid in self.players: | |
| return "ALREADY" | |
| self.players[uid] = Player(uid, name) | |
| self.player_order.append(uid) | |
| db.touch(uid, name) | |
| await self.send(self.chat_id, f"🙋♂️ {mention(uid, name)} دخل البلد! (العدد دلوقتي: <b>{len(self.players)}/{MAX_PLAYERS}</b>)") | |
| return "OK" | |
| async def remove_player(self, uid): | |
| if self.state != "LOBBY" or uid not in self.players: | |
| return False | |
| p = self.players.pop(uid) | |
| self.player_order.remove(uid) | |
| await self.send(self.chat_id, f"🏃 {p.link()} خلع من اللعبة قبل ما تبدأ! (الباقيين: <b>{len(self.players)}</b>)") | |
| return True | |
| async def extend(self, sec=30): | |
| if self.state != "LOBBY": | |
| return False | |
| self.lobby_end_time = min(self.lobby_end_time + sec, time.time() + 180) | |
| rem = max(0, int(self.lobby_end_time - time.time())) | |
| await self.send(self.chat_id, f"⏳ زوّدنا الوقت! فاضل <b>{rem} ثانية</b> على البداية.") | |
| return True | |
| def force_start(self): | |
| if self.state != "LOBBY": | |
| return "NOT_LOBBY" | |
| if len(self.players) < MIN_PLAYERS: | |
| return "NOT_ENOUGH" | |
| self.force_start_flag = True | |
| return "OK" | |
| def cancel(self): | |
| self.cancelled = True | |
| self.state = "ENDED" | |
| self.cancel_event.set() | |
| self.phase_event.set() | |
| self.hunter_event.set() | |
| def start(self): | |
| asyncio.create_task(self._run()) | |
| async def _assign_roles(self): | |
| uids = list(self.player_order) | |
| random.shuffle(uids) | |
| n = len(uids) | |
| if n == 4: | |
| pool = ["wolf", "seer", "villager", "villager"] | |
| elif n == 5: | |
| pool = ["wolf", "seer", "guardian", "villager", "villager"] | |
| elif n == 6: | |
| pool = ["wolf", "seer", "guardian", "hunter", "villager", "villager"] | |
| elif n == 7: | |
| pool = ["wolf", "wolf", "seer", "guardian", "hunter", "tanner", "villager"] | |
| elif n == 8: | |
| pool = ["wolf", "wolf", "seer", "guardian", "hunter", "tanner", "mayor", "villager"] | |
| elif n == 9: | |
| pool = ["wolf", "wolf", "seer", "guardian", "hunter", "tanner", "cupid", "mayor", "fool"] | |
| else: | |
| pool = ["wolf"] * max(2, n // 4) | |
| for sp in ["seer", "guardian", "hunter", "tanner", "cupid", "mayor", "serial_killer", "traitor", "fool"]: | |
| if len(pool) < n - 1: | |
| pool.append(sp) | |
| while len(pool) < n: | |
| pool.append("villager") | |
| random.shuffle(pool) | |
| for u, r in zip(uids, pool): | |
| self.players[u].role = r | |
| wolves = self.by_role("wolf", alive_only=False) | |
| for p in self.players.values(): | |
| shown = "seer" if p.role == "fool" else p.role | |
| info = ROLES[shown] | |
| extra = "" | |
| if p.role == "wolf" and len(wolves) > 1: | |
| others = "، ".join(w.link() for w in wolves if w.id != p.id) | |
| extra = f"\n\n🐾 إخواتك في القطيع: {others}" | |
| await self.send(p.id, f"🎭 <b>دورك في الجولة دي: {info['name']}</b>\n\n{info['desc']}{extra}") | |
| def _night_done(self): | |
| if any(w.id not in self.wolf_votes for w in self.by_role("wolf")): | |
| return False | |
| if any(s.id not in self.seer_targets for s in (self.by_role("seer") + self.by_role("fool"))): | |
| return False | |
| if self.by_role("guardian") and self.guardian_target is None: | |
| return False | |
| if self.by_role("serial_killer") and self.sk_target is None: | |
| return False | |
| if self.day_num == 1 and self.by_role("cupid") and len(self.cupid_picks) < 2: | |
| return False | |
| return True | |
| async def _run_lobby(self): | |
| await self.send( | |
| self.chat_id, | |
| f"🌕 <b>يا أهل البلد اصحوا! لعبة مستذئب جديدة بدأت حالاً!</b>\n\n" | |
| f"دوس على الزر تحت عشان تنضم (أقل عدد <b>{MIN_PLAYERS}</b> لاعبين).\n" | |
| f"⏱ قدامكم <b>{LOBBY_TIME} ثانية</b> قبل ما نقفل الباب.\n" | |
| f"الأوامر: <code>زود الوقت</code> | <code>ابدأ</code> | <code>اقفل اللعبة</code>", | |
| reply_markup=self.join_kb(), | |
| ) | |
| r30 = r10 = False | |
| while not self.cancelled: | |
| rem = self.lobby_end_time - time.time() | |
| if self.force_start_flag or rem <= 0: | |
| break | |
| if rem <= 30 and not r30: | |
| r30 = True | |
| await self.send(self.chat_id, f"⏰ فاضل <b>30 ثانية</b> ونبدأ (المنضمين: <b>{len(self.players)}</b>)", reply_markup=self.join_kb()) | |
| elif rem <= 10 and not r10: | |
| r10 = True | |
| await self.send(self.chat_id, "⏰ آخر <b>10 ثواني</b>.. اللي هيدخل يلحق!", reply_markup=self.join_kb()) | |
| await asyncio.sleep(1) | |
| if self.cancelled: | |
| return False | |
| if len(self.players) < MIN_PLAYERS: | |
| await self.send(self.chat_id, f"❌ اللعبة اتلغت عشان العدد مكملش ({len(self.players)}/{MIN_PLAYERS} لاعبين).") | |
| return False | |
| return True | |
| async def _run_night(self): | |
| self.day_num += 1 | |
| self.state = "NIGHT" | |
| self.phase_id += 1 | |
| self.phase_event.clear() | |
| self.wolf_votes, self.seer_targets, self.guardian_target, self.sk_target, self.cupid_picks = {}, {}, None, None, [] | |
| await self.send(self.chat_id, f"🌃 <b>الليل رقم {self.day_num} دخل والبلد هُسسس...</b>\n📩 اللي ليهم أدوار بالليل افتحوا الخاص حالاً! ({NIGHT_TIME} ثانية)") | |
| alive = self.alive_players() | |
| non_w = [p for p in alive if p.role != "wolf"] | |
| for w in self.by_role("wolf"): | |
| if non_w: | |
| await self.send(w.id, f"🐺 <b>الليلة {self.day_num}:</b> هتتعشى بمين؟", reply_markup=self._kb(non_w, "wolf")) | |
| for s in (self.by_role("seer") + self.by_role("fool")): | |
| t = [p for p in alive if p.id != s.id] | |
| if t: | |
| await self.send(s.id, f"🔮 <b>الليلة {self.day_num}:</b> شاكك في مين؟", reply_markup=self._kb(t, "seer")) | |
| for g in self.by_role("guardian"): | |
| gt = [p for p in alive if p.id != self.last_guardian_target] or alive | |
| await self.send(g.id, f"🛡 <b>الليلة {self.day_num}:</b> مين هتحميه الليلة؟", reply_markup=self._kb(gt, "guardian")) | |
| for sk in self.by_role("serial_killer"): | |
| skt = [p for p in alive if p.id != sk.id] | |
| if skt: | |
| await self.send(sk.id, f"🔪 <b>الليلة {self.day_num}:</b> هتخلص على مين؟", reply_markup=self._kb(skt, "sk")) | |
| if self.day_num == 1: | |
| for c in self.by_role("cupid"): | |
| await self.send(c.id, "💘 <b>أول ليلة يا كيوبيد:</b> اختار أول طرف:", reply_markup=self._kb(alive, "cupid")) | |
| try: | |
| await asyncio.wait_for(self.phase_event.wait(), timeout=NIGHT_TIME) | |
| except asyncio.TimeoutError: | |
| pass | |
| if self.cancelled: | |
| return | |
| self.last_guardian_target = self.guardian_target | |
| # كيوبيد | |
| if self.day_num == 1 and self.by_role("cupid") and len(alive) >= 2: | |
| if len(self.cupid_picks) < 2: | |
| rem = [p.id for p in alive if p.id not in self.cupid_picks] | |
| random.shuffle(rem) | |
| while len(self.cupid_picks) < 2 and rem: | |
| self.cupid_picks.append(rem.pop()) | |
| if len(self.cupid_picks) == 2: | |
| u1, u2 = self.cupid_picks | |
| self.players[u1].lover_id, self.players[u2].lover_id = u2, u1 | |
| await self.send(u1, f"💘 سهم كيوبيد ربطك بـ {self.players[u2].link()}!") | |
| await self.send(u2, f"💘 سهم كيوبيد ربطك بـ {self.players[u1].link()}!") | |
| # العراف والمخرف | |
| for s in self.by_role("seer"): | |
| tid = self.seer_targets.get(s.id) | |
| if tid and tid in self.players: | |
| tgt = self.players[tid] | |
| shown = "villager" if tgt.role == "traitor" else tgt.role | |
| await self.send(s.id, f"🔮 {tgt.link()} طلع: <b>{ROLES[shown]['name']}</b>.") | |
| for f in self.by_role("fool"): | |
| tid = self.seer_targets.get(f.id) | |
| if tid and tid in self.players: | |
| tgt = self.players[tid] | |
| fake = random.choice([r for r in ROLES if r not in (tgt.role, "fool")]) | |
| await self.send(f.id, f"🔮 {tgt.link()} طلع: <b>{ROLES[fake]['name']}</b>.") | |
| dawn, dead = [], [] | |
| w_vid = None | |
| if self.wolf_votes: | |
| cnt = Counter(self.wolf_votes.values()) | |
| mv = max(cnt.values()) | |
| w_vid = random.choice([tid for tid, c in cnt.items() if c == mv]) | |
| if w_vid and w_vid in self.players and self.players[w_vid].alive: | |
| if w_vid == self.guardian_target: | |
| dawn.append("🛡 الديابة هجموا بالليل بس <b>الحارس</b> أنقذ الضحية!") | |
| elif self.players[w_vid].role == "serial_killer": | |
| att = [self.players[w] for w in self.wolf_votes if self.players[w].alive] | |
| if att: | |
| cv = random.choice(att) | |
| cv.alive = False | |
| dead.append(cv) | |
| dawn.append(f"😱 الديابة هجموا على <b>السفاح</b> فقتل الديب {cv.link()}!") | |
| else: | |
| v = self.players[w_vid] | |
| v.alive = False | |
| dead.append(v) | |
| dawn.append(f"{random.choice(WOLF_DEATH_LINES).format(victim=v.link())}\nدوره كان: <b>{ROLES[v.role]['name']}</b>.") | |
| if self.sk_target and self.sk_target in self.players and self.players[self.sk_target].alive: | |
| if self.sk_target == self.guardian_target: | |
| dawn.append("🛡 السفاح حاول يغدر بحد بس <b>الحارس</b> صدّه!") | |
| else: | |
| v = self.players[self.sk_target] | |
| v.alive = False | |
| dead.append(v) | |
| dawn.append(f"{random.choice(SK_DEATH_LINES).format(victim=v.link())}\nدوره كان: <b>{ROLES[v.role]['name']}</b>.") | |
| await self.send(self.chat_id, ("🌅 <b>طلع النهار!</b>\n\n" + "\n\n".join(dawn)) if dawn else "🌅 <b>صباح الفل!</b> الليلة عدت على خير ومحدش مات.") | |
| for dp in dead: | |
| await self._on_death(dp) | |
| async def _on_death(self, dp): | |
| if dp.lover_id and dp.lover_id in self.players and self.players[dp.lover_id].alive: | |
| lv = self.players[dp.lover_id] | |
| lv.alive = False | |
| await self.send(self.chat_id, f"💔 {lv.link()} مات من الحسرة ورا حبيبه {dp.link()}! دوره كان: <b>{ROLES[lv.role]['name']}</b>.") | |
| if lv.role == "hunter": | |
| await self._hunter_shot(lv) | |
| if dp.role == "hunter": | |
| await self._hunter_shot(dp) | |
| async def _hunter_shot(self, hunter): | |
| targets = [p for p in self.alive_players() if p.id != hunter.id] | |
| if not targets or self.cancelled: | |
| return | |
| prev = self.state | |
| self.state = "HUNTER_SHOT" | |
| self.phase_id += 1 | |
| self.active_hunter_id, self.hunter_target = hunter.id, None | |
| self.hunter_event.clear() | |
| await self.send(self.chat_id, f"🔫 {hunter.link()} طلع <b>الصياد</b>! قدامه {HUNTER_TIME} ثانية يضرب آخر رصاصة...") | |
| await self.send(hunter.id, f"🔫 اختار مين هتاخده معاك في خلال {HUNTER_TIME} ثانية:", reply_markup=self._kb(targets, "hunter")) | |
| try: | |
| await asyncio.wait_for(self.hunter_event.wait(), timeout=HUNTER_TIME) | |
| except asyncio.TimeoutError: | |
| pass | |
| tid = self.hunter_target | |
| self.active_hunter_id, self.state = None, prev | |
| if tid and tid in self.players and self.players[tid].alive: | |
| shot = self.players[tid] | |
| shot.alive = False | |
| await self.send(self.chat_id, f"💥 طاخ! الصياد {hunter.link()} جاب {shot.link()} الأرض! دوره كان: <b>{ROLES[shot.role]['name']}</b>.") | |
| await self._on_death(shot) | |
| else: | |
| await self.send(self.chat_id, f"🔫 الصياد {hunter.link()} مات قبل ما يضرب الرصاصة!") | |
| async def _run_day(self): | |
| self.state = "DAY" | |
| alive = self.alive_players() | |
| names = "\n".join(f"• {p.link()}" for p in alive) | |
| await self.send(self.chat_id, f"☀️ <b>وقت النقاش (اليوم {self.day_num}) — {DAY_TIME} ثانية</b>\n\n👥 <b>العايشين ({len(alive)}):</b>\n{names}") | |
| try: | |
| await asyncio.wait_for(self.cancel_event.wait(), timeout=DAY_TIME) | |
| except asyncio.TimeoutError: | |
| pass | |
| if self.cancelled: | |
| return None | |
| self.state = "LYNCH" | |
| self.phase_id += 1 | |
| self.lynch_votes = {} | |
| self.phase_event.clear() | |
| await self.send(self.chat_id, f"⚖️ <b>وقت التصويت على المشنقة!</b> افتحوا الخاص خلال {LYNCH_TIME} ثانية!") | |
| alive = self.alive_players() | |
| for p in alive: | |
| others = [x for x in alive if x.id != p.id] | |
| await self.send(p.id, f"⚖️ <b>تصويت اليوم {self.day_num}:</b> شاكك في مين؟", reply_markup=self._kb(others, "lynch", include_skip=True)) | |
| try: | |
| await asyncio.wait_for(self.phase_event.wait(), timeout=LYNCH_TIME) | |
| except asyncio.TimeoutError: | |
| pass | |
| if self.cancelled or not self.lynch_votes: | |
| if not self.cancelled: | |
| await self.send(self.chat_id, "🤷♂️ محدش صوّت النهاردة.. مفيش شنق!") | |
| return None | |
| cnt = Counter() | |
| for vid, tid in self.lynch_votes.items(): | |
| w = 2 if (self.players.get(vid) and self.players[vid].role == "mayor" and tid != 0) else 1 | |
| cnt[tid] += w | |
| ranked = cnt.most_common() | |
| top_c, top_v = ranked[0] | |
| if top_c == 0 or (len(ranked) > 1 and ranked[1][1] == top_v): | |
| await self.send(self.chat_id, "⚖️ تعادل في الأصوات.. مفيش شنق النهاردة!") | |
| return None | |
| ly = self.players[top_c] | |
| ly.alive = False | |
| await self.send(self.chat_id, f"🪢 البلد اتفقت وشنقت {ly.link()} بـ <b>{top_v}</b> صوت!\nدوره كان: <b>{ROLES[ly.role]['name']}</b>.") | |
| if ly.role == "tanner": | |
| return "tanner" | |
| await self._on_death(ly) | |
| return None | |
| async def _check_winner(self): | |
| if len(self.by_role("wolf")) == 0 and self.by_role("traitor"): | |
| t = self.by_role("traitor")[0] | |
| t.role = "wolf" | |
| await self.send(t.id, "🐍➡️🐺 كل الديابة ماتوا! اتحولت رسمي لـ <b>ديب 🐺</b>!") | |
| await self.send(self.chat_id, "🌑 الجو اتقلب.. الخيانة لسه عايشة وسط البلد!") | |
| alive = self.alive_players() | |
| if not alive: | |
| return "draw" | |
| if len(alive) == 2 and alive[0].lover_id == alive[1].id: | |
| return "lovers" | |
| w = [p for p in alive if p.role == "wolf"] | |
| sk = [p for p in alive if p.role == "serial_killer"] | |
| nw = [p for p in alive if p.role != "wolf"] | |
| if sk and len(alive) <= 2: | |
| return "sk" | |
| if not w and not sk: | |
| return "village" | |
| if len(w) >= len(nw) and not sk: | |
| return "wolves" | |
| return None | |
| async def _finish(self, winner): | |
| self.state = "ENDED" | |
| headers = { | |
| "village": "🏆 <b>مبروك يا أهل البلد! القرية كسبت!</b> 🎉", | |
| "wolves": "🐺 <b>الديابة كسبوا وأكلوا البلد كلها!</b> 🩸", | |
| "tanner": "🃏 <b>المجنون لبّسكم في الحيط وكسب لوحده!</b> 😈", | |
| "sk": "🔪 <b>السفاح خلّص على الكل وكسب لوحده!</b> 😱", | |
| "lovers": "💘 <b>الحب انتصر! العشاق كسبوا مع بعض!</b> ❤️", | |
| "draw": "💀 <b>البلد كلها ماتت! مفيش فايز.</b>", | |
| } | |
| lines = [] | |
| for uid in self.player_order: | |
| p = self.players[uid] | |
| won = ( | |
| (winner == "lovers" and p.alive and p.lover_id is not None) | |
| or (winner == "village" and ROLES[p.role]["team"] == "village") | |
| or (winner == "wolves" and p.role == "wolf") | |
| or (winner == "tanner" and p.role == "tanner") | |
| or (winner == "sk" and p.role == "serial_killer") | |
| ) | |
| db.record(p.id, p.name, won, p.alive) | |
| lines.append(f"• {p.link()}{' 💘' if p.lover_id else ''} — {ROLES[p.role]['name']} ({'❤️ حي' if p.alive else '💀 ميت'}) {'🏆' if won else ''}") | |
| await self.send(self.chat_id, f"{headers[winner]}\n\n📋 <b>كشف الأدوار:</b>\n" + "\n".join(lines)) | |
| async def _run(self): | |
| try: | |
| if not await self._run_lobby(): | |
| return | |
| await self._assign_roles() | |
| await self.send(self.chat_id, f"🎬 <b>اللعبة بدأت بـ {len(self.players)} لاعبين!</b> افتحوا الخاص شوفوا أدواركم.") | |
| await asyncio.sleep(2) | |
| while not self.cancelled: | |
| await self._run_night() | |
| if self.cancelled: | |
| break | |
| w = await self._check_winner() | |
| if w: | |
| await self._finish(w) | |
| break | |
| lw = await self._run_day() | |
| if self.cancelled: | |
| break | |
| w = lw or await self._check_winner() | |
| if w: | |
| await self._finish(w) | |
| break | |
| await asyncio.sleep(2) | |
| finally: | |
| games.pop(self.chat_id, None) | |
| async def handle_cb(self, q, ph_id, action, tid): | |
| uid = q.from_user.id | |
| if ph_id != self.phase_id or uid not in self.players: | |
| await q.answer("الوقت خلص للاختيار ده!") | |
| return | |
| p = self.players[uid] | |
| if action == "hunter" and self.state == "HUNTER_SHOT" and uid == self.active_hunter_id: | |
| if tid in self.players and self.players[tid].alive: | |
| self.hunter_target = tid | |
| self.hunter_event.set() | |
| await q.answer("طاخ!") | |
| await q.edit_message_text(f"🔫 ضربت <b>{esc(self.players[tid].name)}</b>!", parse_mode="HTML") | |
| return | |
| if not p.alive: | |
| await q.answer("إنت ميت! 😂", show_alert=True) | |
| return | |
| if self.state == "NIGHT": | |
| if action == "wolf" and p.role == "wolf" and tid in self.players: | |
| self.wolf_votes[uid] = tid | |
| await q.answer("تم") | |
| await q.edit_message_text(f"🐺 اخترت تتعشى بـ <b>{esc(self.players[tid].name)}</b>.", parse_mode="HTML") | |
| elif action == "seer" and p.role in ("seer", "fool") and tid in self.players: | |
| self.seer_targets[uid] = tid | |
| await q.answer("تم") | |
| await q.edit_message_text(f"🔮 هنكشفلك سر <b>{esc(self.players[tid].name)}</b> الفجر.", parse_mode="HTML") | |
| elif action == "guardian" and p.role == "guardian" and tid in self.players: | |
| self.guardian_target = tid | |
| await q.answer("تم") | |
| await q.edit_message_text(f"🛡 هتحرس بيت <b>{esc(self.players[tid].name)}</b>.", parse_mode="HTML") | |
| elif action == "sk" and p.role == "serial_killer" and tid in self.players: | |
| self.sk_target = tid | |
| await q.answer("تم") | |
| await q.edit_message_text(f"🔪 جهّزت سكينتك لـ <b>{esc(self.players[tid].name)}</b>!", parse_mode="HTML") | |
| elif action == "cupid" and p.role == "cupid" and self.day_num == 1 and tid in self.players and tid not in self.cupid_picks: | |
| self.cupid_picks.append(tid) | |
| if len(self.cupid_picks) == 1: | |
| rem = [x for x in self.alive_players() if x.id != tid] | |
| await q.answer("اختار التاني") | |
| await q.edit_message_text(f"💘 اخترت الأول: <b>{esc(self.players[tid].name)}</b>. اختار التاني:", reply_markup=self._kb(rem, "cupid"), parse_mode="HTML") | |
| else: | |
| await q.answer("تم الربط!") | |
| await q.edit_message_text("💘 تم الربط بسهم الحب!", parse_mode="HTML") | |
| if self._night_done(): | |
| self.phase_event.set() | |
| return | |
| if self.state == "LYNCH" and action == "lynch": | |
| self.lynch_votes[uid] = tid | |
| if tid == 0: | |
| await q.answer("تخطيت") | |
| await q.edit_message_text("⏭ تخطيت التصويت.") | |
| elif tid in self.players: | |
| await q.answer("تم التصويت") | |
| await q.edit_message_text(f"⚖️ صوّت ضد <b>{esc(self.players[tid].name)}</b>.", parse_mode="HTML") | |
| await self.send(self.chat_id, f"🗳 {p.link()} صوّت ضد {self.players[tid].link()}!") | |
| if len(self.lynch_votes) >= len(self.alive_players()): | |
| self.phase_event.set() | |
| # ---------- أوامر اللعبة داخل البوت ---------- | |
| async def ww_new(update, ctx, arg=""): | |
| if update.effective_chat.type == "private": | |
| await update.message.reply_text("🐺 ابدأ لعبة المستذئب داخل جروب مع صحابك!") | |
| return | |
| cid = update.effective_chat.id | |
| if cid in games: | |
| await update.message.reply_text("⚠️ في لعبة مستذئب شغالة بالفعل في الجروب!") | |
| return | |
| me = await ctx.bot.get_me() | |
| g = WerewolfGame(ctx.bot, me.username, cid, update.effective_user.id) | |
| games[cid] = g | |
| g.start() | |
| res = await g.add_player(update.effective_user.id, update.effective_user.full_name) | |
| if res == "NO_PM": | |
| await update.message.reply_text("📩 دوس على الزر تحت عشان تفعّل الخاص معايا وتدخل اللعبة:", reply_markup=g.join_kb()) | |
| async def ww_join(update, ctx, arg=""): | |
| g = games.get(update.effective_chat.id) | |
| if not g: | |
| await update.message.reply_text("❌ مفيش لعبة مستذئب مفتوحة — اكتب (لعبه جديده).") | |
| return | |
| res = await g.add_player(update.effective_user.id, update.effective_user.full_name) | |
| if res == "NO_PM": | |
| await update.message.reply_text("📩 دوس على الزر تحت عشان تفعّل الخاص وتدخل تلقائي:", reply_markup=g.join_kb()) | |
| elif res == "ALREADY": | |
| await update.message.reply_text("ℹ️ إنت جوه اللعبة أصلاً!") | |
| elif res == "STARTED": | |
| await update.message.reply_text("⏳ اللعبة بدأت خلاص!") | |
| async def ww_flee(update, ctx, arg=""): | |
| g = games.get(update.effective_chat.id) | |
| if not g or not await g.remove_player(update.effective_user.id): | |
| await update.message.reply_text("❌ تقدر تنسحب بس قبل ما اللعبة تبدأ.") | |
| async def ww_extend(update, ctx, arg=""): | |
| g = games.get(update.effective_chat.id) | |
| if g: | |
| await g.extend(30) | |
| async def ww_force(update, ctx, arg=""): | |
| g = games.get(update.effective_chat.id) | |
| if not g: | |
| return | |
| if update.effective_user.id != g.creator_id and await R.effective_level(update) < R.level("ادمن"): | |
| await update.message.reply_text("⛔ الأمر ده لصاحب اللعبة أو أدمن الجروب بس.") | |
| return | |
| if g.force_start() == "NOT_ENOUGH": | |
| await update.message.reply_text(f"⚠️ لازم على الأقل {MIN_PLAYERS} لاعبين عشان نبدأ!") | |
| async def ww_stop(update, ctx, arg=""): | |
| g = games.get(update.effective_chat.id) | |
| if not g: | |
| return | |
| if update.effective_user.id != g.creator_id and await R.effective_level(update) < R.level("ادمن"): | |
| await update.message.reply_text("⛔ الأمر ده لصاحب اللعبة أو أدمن الجروب بس.") | |
| return | |
| g.cancel() | |
| await update.message.reply_text("🛑 تم إغلاق لعبة المستذئب الحالية.") | |
| async def ww_players(update, ctx, arg=""): | |
| g = games.get(update.effective_chat.id) | |
| if not g: | |
| await update.message.reply_text("❌ مفيش لعبة مستذئب شغالة دلوقتي.") | |
| return | |
| lines = [f"• {g.players[u].link()} ({'❤️ حي' if g.players[u].alive else '💀 ميت'})" for u in g.player_order] | |
| await update.message.reply_text("👥 <b>اللاعبين في المستذئب:</b>\n" + "\n".join(lines), parse_mode="HTML") | |
| async def ww_roles(update, ctx, arg=""): | |
| lines = [f"• <b>{r['name']}</b>: {r['desc']}" for r in ROLES.values()] | |
| await update.message.reply_text("📜 <b>أدوار لعبة المستذئب:</b>\n\n" + "\n\n".join(lines), parse_mode="HTML") | |
| async def ww_stats(update, ctx, arg=""): | |
| u = update.effective_user | |
| row = db.stats(u.id) | |
| if not row or row[1] == 0: | |
| await update.message.reply_text("📊 لسه ملعبتش ولا جولة مستذئب كاملة!") | |
| return | |
| _, played, won, surv = row | |
| rate = round((won / played) * 100, 1) | |
| await update.message.reply_text(f"📊 <b>أرقام المستذئب لـ {esc(u.first_name)}:</b>\n🎮 جولات: {played}\n🏆 فوز: {won} ({rate}%)\n❤️ نجاة: {surv}", parse_mode="HTML") | |
| async def ww_top(update, ctx, arg=""): | |
| rows = db.top(10) | |
| if not rows: | |
| await update.message.reply_text("🏆 لسه مفيش متصدرين في المستذئب.") | |
| return | |
| medals = ["🥇", "🥈", "🥉"] | |
| lines = [f"{medals[i] if i < 3 else str(i+1)+'.'} {mention(u, n)} — <b>{w}</b> فوز (من {p})" for i, (u, n, w, p) in enumerate(rows)] | |
| await update.message.reply_text("🏆 <b>أبطال المستذئب:</b>\n\n" + "\n".join(lines), parse_mode="HTML") | |
| async def handle_start_deeplink(update, ctx, payload): | |
| if not payload.startswith("join_"): | |
| return False | |
| try: | |
| cid = int(payload[5:]) | |
| except ValueError: | |
| return True | |
| g = games.get(cid) | |
| if not g: | |
| await update.message.reply_text("❌ مفيش لعبة مستذئب مفتوحة حالياً في الجروب ده.") | |
| return True | |
| res = await g.add_player(update.effective_user.id, update.effective_user.full_name) | |
| if res == "ALREADY": | |
| await update.message.reply_text("ℹ️ إنت جوه اللعبة أصلاً!") | |
| elif res == "STARTED": | |
| await update.message.reply_text("⏳ اللعبة بدأت خلاص!") | |
| elif res == "FULL": | |
| await update.message.reply_text("🚫 العدد اكتمل في الجولة دي.") | |
| return True | |
| async def cb(update, ctx): | |
| q = update.callback_query | |
| parts = q.data.split(":") | |
| if len(parts) != 5: | |
| await q.answer() | |
| return | |
| _, cid_s, ph_s, action, tid_s = parts | |
| g = games.get(int(cid_s)) | |
| if not g: | |
| await q.answer("اللعبة انتهت!") | |
| return | |
| await g.handle_cb(q, int(ph_s), action, int(tid_s)) | |
| HANDLERS = [CallbackQueryHandler(cb, pattern=r"^ww:")] | |