-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprofile_music.py
More file actions
99 lines (83 loc) · 3.7 KB
/
Copy pathprofile_music.py
File metadata and controls
99 lines (83 loc) · 3.7 KB
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
# -*- coding: utf-8 -*-
"""
profile_music.py — Установка дня рождения и музыки профиля.
set_birthday(client) — ставит 11 февраля, работает для всех аккаунтов.
set_profile_music(client, mp3_path) — устанавливает профильную музыку (Telegram Premium).
Молча пропускает аккаунты без Premium.
Структура папок:
music/ ← хранилище MP3
music/{uid}/ ← временная папка пользователя, удаляется после залива
"""
import os
import shutil
import logging
import random
from telethon import TelegramClient
from telethon.tl.functions.account import UpdateBirthdayRequest, SaveRingtoneRequest
from telethon.tl.types import Birthday, InputDocument
log = logging.getLogger("profile_music")
MUSIC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "music")
os.makedirs(MUSIC_DIR, exist_ok=True)
async def _safe_log(log_func, text: str) -> None:
if log_func is None:
return
try:
res = log_func(text)
if hasattr(res, "__await__"):
await res
except Exception:
pass
async def set_birthday(client: TelegramClient, log_func=None, birthday: str = "11.02") -> bool:
"""Ставит дату рождения. birthday — строка DD.MM или DD.MM.YYYY."""
try:
parts = birthday.strip().split(".")
day = int(parts[0])
month = int(parts[1])
year = int(parts[2]) if len(parts) > 2 else None
bday = Birthday(day=day, month=month, year=year)
await client(UpdateBirthdayRequest(birthday=bday))
date_str = f"{day:02d}.{month:02d}" + (f".{year}" if year else "")
await _safe_log(log_func, f"🎂 День рождения установлен ({date_str}).")
return True
except Exception as e:
await _safe_log(log_func, f"🎂 Дата рождения: {e}")
return False
async def set_profile_music(client: TelegramClient, mp3_path: str, log_func=None) -> bool:
"""
Устанавливает MP3 как музыку профиля (Telegram Premium).
Молча пропускает аккаунты без Premium.
"""
sent = None
try:
sent = await client.send_file("me", mp3_path)
doc = sent.document
input_doc = InputDocument(
id=doc.id,
access_hash=doc.access_hash,
file_reference=doc.file_reference,
)
await client(SaveRingtoneRequest(id=input_doc, unsave=False))
await _safe_log(log_func, "🎵 Музыка профиля установлена.")
return True
except Exception as e:
err = str(e)
if "PREMIUM" in err.upper():
await _safe_log(log_func, "🎵 Пропущено: нет Telegram Premium.")
else:
await _safe_log(log_func, f"🎵 Музыка профиля: {e}")
return False
finally:
if sent is not None:
try:
await sent.delete()
except Exception:
pass
def get_user_music_dir(uid: int) -> str:
"""Возвращает путь к временной папке пользователя."""
return os.path.join(MUSIC_DIR, str(uid))
def cleanup_user_music(uid: int) -> None:
"""Удаляет временную папку пользователя после завершения массового залива."""
user_dir = get_user_music_dir(uid)
if os.path.isdir(user_dir):
shutil.rmtree(user_dir, ignore_errors=True)
log.debug("music dir removed: %s", user_dir)