Исправь ошибку любым способом даже можешь заменить зависимость даже видоизменить
вот ошибка такая "[INFO] hikka.modules.loader: Module loading failed, attemping dependency installation (pytgcalls)
[WARNING] hikka.modules.loader: No valid pip packages specified in code, attemping installation from error"
а вот код
"from .. import loader, utils
import logging
import random
import asyncio
import time
import os
import tempfile
from gtts import gTTS
from telethon import events, Button
from pytgcalls import PyTgCalls
from pytgcalls.types import InputAudioStream, InputVideoStream
from pytgcalls.types import StreamType
from telethon.tl.functions.phone import CreateGroupCallRequest
@loader.tds
class MafiaGame(loader.Module):
"""Мафия: с ролями, голосом, победой, голосованием и историей"""
strings = {"name": "MafiaGame"}
def __init__(self):
self.games = {}
self.logger = logging.getLogger(__name__)
self.voice_client = None
self.roles_config = {
"👨🏼🌾 Мирный житель": {"faction": "town", "description": "Простой житель.", "unique": False, "chance": 30},
"🤞🏼 Счастливчик": {"faction": "town", "description": "50% шанс выжить при убийстве.", "unique": False, "chance": 7},
"🕵🏻♂️ Комиссар": {"faction": "town", "description": "Проверяет игроков ночью.", "unique": True, "chance": 8},
"👮🏻♀️ Сержант": {"faction": "town", "description": "Заменяет комиссара после его смерти.", "unique": True, "chance": 5},
"👨🏼⚕️ Доктор": {"faction": "town", "description": "Лечит игроков, себя — 1 раз.", "unique": True, "chance": 8},
"💃🏼 Любовница": {"faction": "town", "description": "Блокирует действия ролей ночью.", "unique": True, "chance": 5},
"💣 Камикадзе": {"faction": "town", "description": "Убивает убийцу при своей смерти.", "unique": True, "chance": 5},
"🧙🏼♂️ Бомж": {"faction": "town", "description": "Может стать свидетелем убийства.", "unique": True, "chance": 4},
"🕶 Телохранитель": {"faction": "town", "description": "Умирает вместо цели.", "unique": True, "chance": 4},
"🤵🏻♂️ Дон": {"faction": "mafia", "description": "Главарь мафии.", "unique": True, "chance": 5},
"🤵🏼 Мафия": {"faction": "mafia", "description": "Работает с Доном.", "unique": False, "chance": 15},
"👨🏼💼 Адвокат": {"faction": "mafia", "description": "Скрывает мафию.", "unique": True, "chance": 5},
"🔪 Маньяк": {"faction": "neutral", "description": "Убивает каждую ночь.", "unique": True, "chance": 6},
"🎙 Журналист": {"faction": "neutral", "description": "Публикует посетителей.", "unique": True, "chance": 4},
"🤦🏼♂️ Самоубийца": {"faction": "neutral", "description": "Побеждает, если его повесят.", "unique": True, "chance": 3},
"🐺 Оборотень": {"faction": "neutral", "description": "Крадёт роль, убивает жертву.", "unique": True, "chance": 3},
"⚗️ Химик": {"faction": "neutral", "description": "Может лечить, убивать или проверять.", "unique": True, "chance": 4},
}
self.active_roles = ["🕵🏻♂️ Комиссар", "👨🏼⚕️ Доктор", "🔪 Маньяк", "💃🏼 Любовница", "🧙🏼♂️ Бомж"]
self.night_actions = {}
self.doctor_heals = {}
self.blocked_players = set()
self.protected_players = set()
self.killed_players = []
self.check_results = {}
self.nominations = {}
self.confirm_votes = {}
self.vote_message_ids = {}
self.game_start_time = {}
async def client_ready(self, client, db):
self.client = client
self.db = db
self.voice_client = PyTgCalls(client)
await self.voice_client.start()
@client.on(events.CallbackQuery)
async def handle_buttons(event):
data = event.data.decode("utf-8")
parts = data.split("|")
if len(parts) < 3:
return
action, chat_id, target = parts[0], int(parts[1]), parts[2]
sender = await event.get_sender()
voter = sender.username or sender.first_name
if action == "nominate":
self.nominations.setdefault(chat_id, {})[voter] = target
await event.answer(f"Вы выставили {target}")
elif action == "confirm":
vote_type = parts[2]
candidate = parts[3]
self.confirm_votes.setdefault(chat_id, {"yes": set(), "no": set()})
self.confirm_votes[chat_id][vote_type].add(voter)
await event.answer(f"Ваш голос засчитан: {vote_type}")
elif action == "night":
self.night_actions.setdefault(chat_id, {})[target] = voter
await event.answer(f"Вы выбрали {target}")
await event.edit(f"🌙 Вы выбрали {target} как цель.")
async def stream_voice(self, chat_id, text):
try:
with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as f:
gTTS(text=text, lang='ru').save(f.name)
audio_path = f.name
try:
await self.client(CreateGroupCallRequest(
peer=await self.client.get_entity(chat_id),
random_id=utils.rand(64)
))
except Exception:
pass # уже создан
await self.voice_client.join_group_call(
chat_id,
AudioPiped(audio_path),
stream_type=StreamType().local_stream,
)
await asyncio.sleep(5)
await self.voice_client.leave_group_call(chat_id)
os.unlink(audio_path)
except Exception as e:
await self.client.send_message(chat_id, f"Ошибка озвучки: {e}")
async def mstartcmd(self, message):
chat_id = message.chat_id
if chat_id in self.games:
await utils.answer(message, "<b>Игра уже запущена.</b>")
return
self.games[chat_id] = {
"players": [],
"phase": "setup",
"roles": {},
}
await utils.answer(message, "<b>🕹 Лобби создано! Используйте .mjoin</b>")
async def mjoincmd(self, message):
chat_id = message.chat_id
user = message.sender
username = user.username or user.first_name
if chat_id not in self.games:
await utils.answer(message, "<b>Сначала создайте игру: .mstart</b>")
return
if username in self.games[chat_id]["players"]:
await utils.answer(message, "<b>Вы уже в игре.</b>")
return
self.games[chat_id]["players"].append(username)
await utils.answer(message, f"<b>{username} присоединился к игре!</b>")
async def mbegincmd(self, message):
chat_id = message.chat_id
if chat_id not in self.games or self.games[chat_id]["phase"] != "setup":
await utils.answer(message, "<b>Сначала создайте игру: .mstart</b>")
return
players = self.games[chat_id]["players"]
if len(players) < 5:
await utils.answer(message, "<b>Нужно минимум 5 игроков для начала игры.</b>")
return
roles = self.assign_roles(players)
self.games[chat_id]["roles"] = roles
self.games[chat_id]["phase"] = "night"
self.game_start_time[chat_id] = time.time()
for player in players:
role_data = roles[player]
msg = f"<b>🎭 Ваша роль:</b> {role_data['role']}\n{role_data['description']}"
try:
await self.client.send_message(player, msg)
except Exception:
await utils.answer(message, f"<b>Не удалось отправить роль игроку {player} (возможно, закрыт ЛС).</b>")
await utils.answer(message, "<b>🎮 Игра началась! Наступает ночь...</b>")
await self.stream_voice(chat_id, "Игра началась. Наступает ночь.")
await self.start_night_phase(chat_id, message)
def assign_roles(self, players):
assigned = {}
roles_pool = list(self.roles_config.items())
unique_roles = set()
while len(assigned) < len(players):
player = players[len(assigned)]
role_name, role_data = random.choices(
roles_pool,
weights=[r[1]["chance"] for r in roles_pool],
k=1
)[0]
if role_data["unique"] and role_name in unique_roles:
continue
assigned[player] = {
"role": role_name,
"faction": role_data["faction"],
"description": role_data["description"],
"dead": False
}
if role_data["unique"]:
unique_roles.add(role_name)
return assigned
async def start_night_phase(self, chat_id, message):
self.games[chat_id]["phase"] = "night"
self.night_actions[chat_id] = {}
roles = self.games[chat_id]["roles"]
players = list(roles.keys())
for actor in players:
role = roles[actor]["role"]
if role in self.active_roles and not roles[actor]["dead"]:
await self.send_night_action(actor, players, role, chat_id)
await utils.answer(message, "<b>🌃 Ночь наступила. Активные роли получают инструкции в ЛС.</b>")
await self.stream_voice(chat_id, "Наступает ночь. Роли делают свои выборы.")
await asyncio.sleep(60)
await self.finish_night(chat_id, message)
async def send_night_action(self, actor, players, role, chat_id):
buttons = []
row = []
for i, p in enumerate(players):
if p == actor:
continue
row.append(Button.inline(p, data=f"night|{chat_id}|{actor}|{p}".encode()))
if len(row) == 3:
buttons.append(row)
row = []
if row:
buttons.append(row)
text = f"🌙 Ваша роль: {role}\nВыберите цель на эту ночь:"
try:
await self.client.send_message(actor, text, buttons=buttons)
except: pass
async def finish_night(self, chat_id, message):
actions = self.night_actions.get(chat_id, {})
game = self.games[chat_id]
roles = game["roles"]
self.blocked_players.clear()
self.protected_players.clear()
self.killed_players.clear()
self.check_results.clear()
for actor, target in actions.items():
if roles[actor]["role"] == "💃🏼 Любовница":
self.blocked_players.add(target)
for actor, target in actions.items():
if roles[actor]["role"] == "👨🏼⚕️ Доктор":
if actor == target:
used = self.doctor_heals.get(actor, [])
if "self" in used:
continue
self.doctor_heals.setdefault(actor, []).append("self")
else:
self.doctor_heals.setdefault(actor, []).append("other")
self.protected_players.add(target)
for actor, target in actions.items():
if roles[actor]["role"] == "🕵🏻♂️ Комиссар":
if actor in self.blocked_players:
continue
faction = roles[target]["faction"]
emoji = "✅" if faction == "town" else "❌"
self.check_results[actor] = (target, emoji)
for actor, target in actions.items():
if roles[actor]["role"] == "🔪 Маньяк":
if actor in self.blocked_players:
continue
if target not in self.protected_players:
self.killed_players.append(target)
mafia_votes = [
target for actor, target in actions.items()
if roles[actor]["faction"] == "mafia" and roles[actor]["role"] in ["🤵🏻♂️ Дон", "🤵🏼 Мафия"]
and actor not in self.blocked_players
]
if mafia_votes:
from collections import Counter
target = Counter(mafia_votes).most_common(1)[0][0]
if target not in self.protected_players:
self.killed_players.append(target)
result_text = "🏙 <b>Утро наступает...</b>\n"
for name in self.killed_players:
if roles[name].get("dead"): continue
roles[name]["dead"] = True
role = roles[name]["role"]
result_text += f"☠️ <b>{name}</b> был убит ночью. Роль: {role}\n"
await self.stream_voice(chat_id, f"{name} был убит этой ночью.")
if not self.killed_players:
result_text += "🌙 Ночь прошла спокойно.\n"
await self.stream_voice(chat_id, "Ночь прошла спокойно.")
for commissar, (target, emoji) in self.check_results.items():
try:
await self.client.send_message(commissar, f"👁 Проверка: {target} — {emoji}")
except: pass
alive = [p for p in roles if not roles[p].get("dead")]
result_text += "\n<b>Живые игроки:</b>\n" + "\n".join(f"• {p}" for p in alive)
await utils.answer(message, result_text)
await self.check_victory(chat_id, message)
await self.start_day_phase(chat_id, message)
async def start_day_phase(self, chat_id, message):
self.games[chat_id]["phase"] = "day"
self.nominations[chat_id] = {}
roles = self.games[chat_id]["roles"]
alive_players = [p for p in roles if not roles[p]["dead"]]
buttons = []
row = []
for i, p in enumerate(alive_players):
row.append(Button.inline(p, data=f"nominate|{chat_id}|{p}".encode()))
if len(row) == 3:
buttons.append(row)
row = []
if row:
buttons.append(row)
text = "🗳️ <b>Пришло время определить и наказать виновных.</b>\nНажмите на игрока, чтобы выставить его на голосование.\n<code>45 секунд на выбор</code>."
msg = await self.client.send_message(chat_id, text, buttons=buttons)
self.vote_message_ids[chat_id] = msg.id
await self.stream_voice(chat_id, "Наступает день. Обсуждаем события ночью.")
await asyncio.sleep(45)
from collections import Counter
counter = Counter(self.nominations.get(chat_id, {}).values())
if not counter:
await self.client.send_message(chat_id, "⚖️ Никто не был выставлен. Никто не казнён.")
await asyncio.sleep(1)
await self.start_night_phase(chat_id, msg)
return
candidate, votes = counter.most_common(1)[0]
await self.start_confirmation(chat_id, candidate, msg)
async def start_confirmation(self, chat_id, candidate, base_message):
self.confirm_votes[chat_id] = {"yes": set(), "no": set()}
msg = await self.client.send_message(
chat_id,
f"<b>⚖️ Вы точно хотите линчевать {candidate}?</b>\nГолосование за/против длится 30 секунд.",
buttons=[
[Button.inline("👍", data=f"confirm|{chat_id}|yes|{candidate}".encode()),
Button.inline("👎", data=f"confirm|{chat_id}|no|{candidate}".encode())]
]
)
self.vote_message_ids[chat_id] = msg.id
await asyncio.sleep(30)
await self.finalize_vote(chat_id, candidate, msg)
async def finalize_vote(self, chat_id, candidate, message):
yes_votes = self.confirm_votes[chat_id]["yes"]
no_votes = self.confirm_votes[chat_id]["no"]
result_text = (
f"📊 <b>Результаты голосования:</b>\n"
f"{len(yes_votes)} 👍 | {len(no_votes)} 👎\n\n"
)
if len(yes_votes) > len(no_votes):
self.games[chat_id]["roles"][candidate]["dead"] = True
role = self.games[chat_id]["roles"][candidate]["role"]
result_text += f"☠️ <b>{candidate} был казнён!</b>\nРоль: {role}"
await self.stream_voice(chat_id, f"{candidate} был казнён.")
else:
result_text += f"🕊 <b>{candidate} был пощажён.</b>"
await self.stream_voice(chat_id, f"{candidate} был пощажён.")
await self.client.send_message(chat_id, result_text)
await self.check_victory(chat_id, message)
await self.start_night_phase(chat_id, message)
async def check_victory(self, chat_id, message):
roles = self.games[chat_id]["roles"]
alive = [p for p in roles if not roles[p].get("dead")]
mafia = [p for p in alive if roles[p]["faction"] == "mafia"]
town = [p for p in alive if roles[p]["faction"] == "town"]
neutral = [p for p in alive if roles[p]["faction"] == "neutral"]
winners = []
winner_faction = None
if len(alive) == 1 and roles[alive[0]]["role"] == "🔪 Маньяк":
winner_faction = "Маньяк"
winners = [alive[0]]
elif len(mafia) >= len(town):
winner_faction = "Мафия"
winners = mafia
elif not mafia and not neutral:
winner_faction = "Мирные жители"
winners = [p for p in alive if roles[p]["faction"] == "town"]
else:
return # Игра продолжается
# Победа самоубийцы, если его повесили
for p in roles:
if roles[p]["role"] == "🤦🏼♂️ Самоубийца" and roles[p].get("dead"):
winners.append(p)
# Победа камикадзе, если умер
for p in roles:
if roles[p]["role"] == "💣 Камикадзе" and roles[p].get("dead"):
winners.append(p)
# Финальное сообщение
text = f"<b>🎉 Игра окончена!</b>\n<b>Победила {winner_faction}</b>\n\n"
text += "<b>🏆 Победители:</b>\n"
for p in set(winners):
text += f" {p} — {roles[p]['role']}\n"
others = [p for p in roles if p not in winners]
if others:
text += "\n<b>👥 Остальные участники:</b>\n"
for p in others:
text += f" {p} — {roles[p]['role']}\n"
# Время игры
duration = time.time() - self.game_start_time.get(chat_id, time.time())
minutes = int(duration // 60)
seconds = int(duration % 60)
text += f"\n<b>🕰 Игра длилась:</b> {minutes} мин. {seconds} сек."
await self.stream_voice(chat_id, f"Игра окончена. Победила {winner_faction}")
await self.client.send_message(chat_id, text)
# История партии
history = "<b>📜 История партии:</b>\n"
for p in roles:
role = roles[p]["role"]
status = "☠️ мёртв" if roles[p].get("dead") else "✅ жив"
history += f"• {p} — {role} — {status}\n"
await self.client.send_message(chat_id, history)
# Очистка данных игры
self.games.pop(chat_id, None)
self.night_actions.pop(chat_id, None)
self.nominations.pop(chat_id, None)
self.confirm_votes.pop(chat_id, None)
self.vote_message_ids.pop(chat_id, None)
self.game_start_time.pop(chat_id, None)"