-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
407 lines (355 loc) · 13.5 KB
/
__init__.py
File metadata and controls
407 lines (355 loc) · 13.5 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
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# OreO - UserBot
import asyncio
import os
import re
import traceback
from time import time
from traceback import format_exc
from pytgcalls import GroupCallFactory
from pytgcalls.exceptions import GroupCallNotFoundError
from telethon.errors.rpcerrorlist import (
ParticipantJoinMissingError,
ChatSendMediaForbiddenError,
)
from pyOreo import HNDLR, LOGS, asst, udB, vcClient
from pyOreo._misc._decorators import compile_pattern
from pyOreo.fns.helper import (
bash,
downloader,
inline_mention,
mediainfo,
time_formatter,
)
from pyOreo.fns.admins import admin_check
from pyOreo.fns.tools import is_url_ok
from pyOreo.fns.ytdl import get_videos_link
from pyOreo._misc import owner_and_sudos, sudoers
from pyOreo._misc._assistant import in_pattern
from pyOreo._misc._wrappers import eod, eor
from pyOreo.version import __version__ as OreVer
from telethon import events
from telethon.tl import functions, types
from telethon.utils import get_display_name
try:
from yt_dlp import YoutubeDL
except ImportError:
YoutubeDL = None
LOGS.error("'yt-dlp' not found!")
try:
from youtubesearchpython import VideosSearch
except ImportError:
VideosSearch = None
from strings import get_string
asstUserName = asst.me.username
LOG_CHANNEL = udB.get_key("LOG_CHANNEL")
ACTIVE_CALLS, VC_QUEUE = [], {}
MSGID_CACHE, VIDEO_ON = {}, {}
CLIENTS = {}
def VC_AUTHS():
_vcsudos = udB.get_key("VC_SUDOS") or []
return [int(a) for a in [*owner_and_sudos(), *_vcsudos]]
class Player:
def __init__(self, chat, event=None, video=False):
self._chat = chat
self._current_chat = event.chat_id if event else LOG_CHANNEL
self._video = video
if CLIENTS.get(chat):
self.group_call = CLIENTS[chat]
else:
_client = GroupCallFactory(
vcClient, GroupCallFactory.MTPROTO_CLIENT_TYPE.TELETHON,
)
self.group_call = _client.get_group_call()
CLIENTS.update({chat: self.group_call})
async def make_vc_active(self):
try:
await vcClient(
functions.phone.CreateGroupCallRequest(
self._chat, title="🎧 Oreo Music 🎶"
)
)
except Exception as e:
LOGS.exception(e)
return False, e
return True, None
async def startCall(self):
if VIDEO_ON:
for chats in VIDEO_ON:
await VIDEO_ON[chats].stop()
VIDEO_ON.clear()
await asyncio.sleep(3)
if self._video:
for chats in list(CLIENTS):
if chats != self._chat:
await CLIENTS[chats].stop()
del CLIENTS[chats]
VIDEO_ON.update({self._chat: self.group_call})
if self._chat not in ACTIVE_CALLS:
try:
self.group_call.on_network_status_changed(self.on_network_changed)
self.group_call.on_playout_ended(self.playout_ended_handler)
await self.group_call.join(self._chat)
except GroupCallNotFoundError as er:
LOGS.info(er)
dn, err = await self.make_vc_active()
if err:
return False, err
except Exception as e:
LOGS.exception(e)
return False, e
return True, None
async def on_network_changed(self, call, is_connected):
chat = self._chat
if is_connected:
if chat not in ACTIVE_CALLS:
ACTIVE_CALLS.append(chat)
elif chat in ACTIVE_CALLS:
ACTIVE_CALLS.remove(chat)
async def playout_ended_handler(self, call, source, mtype):
if os.path.exists(source):
os.remove(source)
await self.play_from_queue()
async def play_from_queue(self):
chat_id = self._chat
if chat_id in VIDEO_ON:
await self.group_call.stop_video()
VIDEO_ON.pop(chat_id)
try:
song, title, link, thumb, from_user, pos, dur = await get_from_queue(
chat_id
)
try:
await self.group_call.start_audio(song)
except ParticipantJoinMissingError:
await self.vc_joiner()
await self.group_call.start_audio(song)
if MSGID_CACHE.get(chat_id):
await MSGID_CACHE[chat_id].delete()
del MSGID_CACHE[chat_id]
text = f"<strong>🎧 Now playing #{pos}: <a href={link}>{title}</a>\n⏰ Duration:</strong> <code>{dur}</code>\n👤 <strong>Requested by:</strong> {from_user}"
try:
xx = await vcClient.send_message(
self._current_chat,
f"<strong>🎧 Now playing #{pos}: <a href={link}>{title}</a>\n⏰ Duration:</strong> <code>{dur}</code>\n👤 <strong>Requested by:</strong> {from_user}",
file=thumb,
link_preview=False,
parse_mode="html",
)
except ChatSendMediaForbiddenError:
xx = await vcClient.send_message(
self._current_chat, text, link_preview=False, parse_mode="html"
)
MSGID_CACHE.update({chat_id: xx})
VC_QUEUE[chat_id].pop(pos)
if not VC_QUEUE[chat_id]:
VC_QUEUE.pop(chat_id)
except (IndexError, KeyError):
await self.group_call.stop()
del CLIENTS[self._chat]
await vcClient.send_message(
self._current_chat,
f"• Successfully Left Vc : <code>{chat_id}</code> •",
parse_mode="html",
)
except Exception as er:
LOGS.exception(er)
await vcClient.send_message(
self._current_chat,
f"<strong>ERROR:</strong> <code>{format_exc()}</code>",
parse_mode="html",
)
async def vc_joiner(self):
chat_id = self._chat
done, err = await self.startCall()
if done:
await vcClient.send_message(
self._current_chat,
f"• Joined VC in <code>{chat_id}</code>",
parse_mode="html",
)
return True
await vcClient.send_message(
self._current_chat,
f"<strong>ERROR while Joining Vc -</strong> <code>{chat_id}</code> :\n<code>{err}</code>",
parse_mode="html",
)
return False
# --------------------------------------------------
def vc_asst(dec, **kwargs):
def ore(func):
kwargs["func"] = (
lambda e: not e.is_private and not e.via_bot_id and not e.fwd_from
)
handler = udB.get_key("VC_HNDLR") or HNDLR
kwargs["pattern"] = compile_pattern(dec, handler)
vc_auth = kwargs.get("vc_auth", True)
key = udB.get_key("VC_AUTH_GROUPS") or {}
if "vc_auth" in kwargs:
del kwargs["vc_auth"]
async def vc_handler(e):
VCAUTH = list(key.keys())
if not (
(e.out)
or (e.sender_id in VC_AUTHS())
or (vc_auth and e.chat_id in VCAUTH)
):
return
elif vc_auth and key.get(e.chat_id):
cha, adm = key.get(e.chat_id), key[e.chat_id]["admins"]
if adm and not (await admin_check(e)):
return
try:
await func(e)
except Exception:
LOGS.exception(Exception)
await asst.send_message(
LOG_CHANNEL,
f"VC Error - <code>{OreVer}</code>\n\n<code>{e.text}</code>\n\n<code>{format_exc()}</code>",
parse_mode="html",
)
vcClient.add_event_handler(
vc_handler,
events.NewMessage(**kwargs),
)
return ore
# --------------------------------------------------
def add_to_queue(chat_id, song, song_name, link, thumb, from_user, duration):
try:
n = sorted(list(VC_QUEUE[chat_id].keys()))
play_at = n[-1] + 1
except BaseException:
play_at = 1
stuff = {
play_at: {
"song": song,
"title": song_name,
"link": link,
"thumb": thumb,
"from_user": from_user,
"duration": duration,
}
}
if VC_QUEUE.get(chat_id):
VC_QUEUE[int(chat_id)].update(stuff)
else:
VC_QUEUE.update({chat_id: stuff})
return VC_QUEUE[chat_id]
def list_queue(chat):
if VC_QUEUE.get(chat):
txt, n = "", 0
for x in list(VC_QUEUE[chat].keys())[:18]:
n += 1
data = VC_QUEUE[chat][x]
txt += f'<strong>{n}. <a href={data["link"]}>{data["title"]}</a> :</strong> <i>By: {data["from_user"]}</i>\n'
txt += "\n\n....."
return txt
async def get_from_queue(chat_id):
play_this = list(VC_QUEUE[int(chat_id)].keys())[0]
info = VC_QUEUE[int(chat_id)][play_this]
song = info.get("song")
title = info["title"]
link = info["link"]
thumb = info["thumb"]
from_user = info["from_user"]
duration = info["duration"]
if not song:
song = await get_stream_link(link)
return song, title, link, thumb, from_user, play_this, duration
# --------------------------------------------------
async def download(query):
if query.startswith("https://") and "youtube" not in query.lower():
thumb, duration = None, "Unknown"
title = link = query
else:
search = VideosSearch(query, limit=1).result()
data = search["result"][0]
link = data["link"]
title = data["title"]
duration = data.get("duration") or "♾"
thumb = f"https://i.ytimg.com/vi/{data['id']}/hqdefault.jpg"
dl = await get_stream_link(link)
return dl, thumb, title, link, duration
async def get_stream_link(ytlink):
"""
info = YoutubeDL({}).extract_info(url=ytlink, download=False)
k = ""
for x in info["formats"]:
h, w = ([x["height"], x["width"]])
if h and w:
if h <= 720 and w <= 1280:
k = x["url"]
return k
"""
stream = await bash(f'yt-dlp -g -f "best[height<=?720][width<=?1280]" {ytlink}')
return stream[0]
async def vid_download(query):
search = VideosSearch(query, limit=1).result()
data = search["result"][0]
link = data["link"]
video = await get_stream_link(link)
title = data["title"]
thumb = f"https://i.ytimg.com/vi/{data['id']}/hqdefault.jpg"
duration = data.get("duration") or "♾"
return video, thumb, title, link, duration
async def dl_playlist(chat, from_user, link):
# untill issue get fix
# https://github.com/alexmercerind/youtube-search-python/issues/107
"""
vids = Playlist.getVideos(link)
try:
vid1 = vids["videos"][0]
duration = vid1["duration"] or "♾"
title = vid1["title"]
song = await get_stream_link(vid1['link'])
thumb = f"https://i.ytimg.com/vi/{vid1['id']}/hqdefault.jpg"
return song[0], thumb, title, vid1["link"], duration
finally:
vids = vids["videos"][1:]
for z in vids:
duration = z["duration"] or "♾"
title = z["title"]
thumb = f"https://i.ytimg.com/vi/{z['id']}/hqdefault.jpg"
add_to_queue(chat, None, title, z["link"], thumb, from_user, duration)
"""
links = await get_videos_link(link)
try:
search = VideosSearch(links[0], limit=1).result()
vid1 = search["result"][0]
duration = vid1.get("duration") or "♾"
title = vid1["title"]
song = await get_stream_link(vid1["link"])
thumb = f"https://i.ytimg.com/vi/{vid1['id']}/hqdefault.jpg"
return song, thumb, title, vid1["link"], duration
finally:
for z in links[1:]:
try:
search = VideosSearch(z, limit=1).result()
vid = search["result"][0]
duration = vid.get("duration") or "♾"
title = vid["title"]
thumb = f"https://i.ytimg.com/vi/{vid['id']}/hqdefault.jpg"
add_to_queue(chat, None, title, vid["link"], thumb, from_user, duration)
except Exception as er:
LOGS.exception(er)
async def file_download(event, reply, fast_download=True):
thumb = "https://graph.org/file/65f90b37a6d97e236354c.jpg"
title = reply.file.title or reply.file.name or f"{str(time())}.mp4"
file = reply.file.name or f"{str(time())}.mp4"
if fast_download:
dl = await downloader(
f"vcbot/downloads/{file}",
reply.media.document,
event,
time(),
f"Downloading {title}...",
)
dl = dl.name
else:
dl = await reply.download_media()
duration = (
time_formatter(reply.file.duration * 1000) if reply.file.duration else "🤷♂️"
)
if reply.document.thumbs:
thumb = await reply.download_media("vcbot/downloads/", thumb=-1)
return dl, thumb, title, reply.message_link, duration
# --------------------------------------------------