-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathvoicechat.py
791 lines (701 loc) · 29.4 KB
/
voicechat.py
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
__version__ = (2, 0, 0)
# █ █ ▀ █▄▀ ▄▀█ █▀█ ▀
# █▀█ █ █ █ █▀█ █▀▄ █
# © Copyright 2022
# https://t.me/hikariatama
#
# 🔒 Licensed under the GNU AGPLv3
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# meta pic: https://static.dan.tatar/voicechat_icon.png
# meta banner: https://mods.hikariatama.ru/badges/voicechat.jpg
# meta developer: @hikarimods
# requires: py-tgcalls youtube_dl
# scope: hikka_only
# scope: hikka_min 1.2.10
import asyncio
import atexit
import contextlib
import logging
import os
import re
import shutil
import tempfile
from pytgcalls import PyTgCalls, StreamType, types
from pytgcalls.binding import Binding
from pytgcalls.environment import Environment
from pytgcalls.exceptions import AlreadyJoinedError, NoActiveGroupCall
from pytgcalls.handlers import HandlersHolder
from pytgcalls.methods import Methods
from pytgcalls.mtproto import MtProtoClient
from pytgcalls.scaffold import Scaffold
from pytgcalls.types import Cache
from pytgcalls.types.call_holder import CallHolder
from pytgcalls.types.update_solver import UpdateSolver
from telethon.tl.functions.phone import CreateGroupCallRequest
from telethon.tl.types import DocumentAttributeFilename, Message
from youtube_dl import YoutubeDL
from .. import loader, utils
from ..inline.types import InlineCall
from ..tl_cache import CustomTelegramClient
logging.getLogger("pytgcalls").setLevel(logging.ERROR)
@loader.tds
class VoiceChatMod(loader.Module):
"""
Toolkit for VoiceChats handling
DISCLAIMER: THIS MODULE MAY CAUSE MEMORY LEAK AND CORRUPT YOUR SERVER DUE TO PYTGCALLS BUG
USE WITH CAUTION. DON'T FORGET TO LIMIT YOUR HIKKA DAEMON BY RAM AND CPU USAGE!
"""
strings = {
"name": "VoiceChat",
"already_joined": "🚫 <b>You are already in VoiceChat</b>",
"joined": "🎙 <b>Joined VoiceChat</b>",
"no_reply": "🚫 <b>Reply to a message</b>",
"no_queue": "🚫 <b>No queue</b>",
"queue": "🎙 <b>Queue</b>:\n\n{}",
"queueadd": "🎧 <b>{} added to queue</b>",
"queueaddv": "🎬 <b>{} added to queue</b>",
"downloading": "📥 <b>Downloading...</b>",
"playing": "🎶 <b>Playing {}</b>",
"playing_with_next": "🎶 <b>Playing {}</b>\n➡️ <b>Next: {}</b>",
"pause": "🎵 Pause",
"play": "🎵 Play",
"mute": "🔇 Mute",
"unmute": "🔈 Unmute",
"next": "➡️ Next",
"stopped": "🚨 <b>Stopped</b>",
"stop": "🚨 Stop",
"choose_delete": "♻️ <b>Choose a queue item to delete</b>",
}
strings_ru = {
"already_joined": "🚫 <b>Уже в голосовом чате</b>",
"joined": "🎙 <b>Присоединился к голосовому чату</b>",
"no_reply": "🚫 <b>Ответьте на сообщение</b>",
"no_queue": "🚫 <b>Очередь пуста</b>",
"queue": "🎙 <b>Очередь</b>:\n\n{}",
"queueadd": "🎧 <b>{} добавлен в очередь</b>",
"queueaddv": "📼 <b>{} добавлен в очередь</b>",
"downloading": "📥 <b>Загрузка...</b>",
"playing": "🎶 <b>Играет {}</b>",
"playing_with_next": "🎶 <b>Играет {}</b>\n➡️ <b>Далее: {}</b>",
"pause": "🎵 Пауза",
"play": "🎵 Играть",
"mute": "🔇 Заглушить",
"unmute": "🔈 Включить",
"next": "➡️ Далее",
"stopped": "🚨 <b>Остановлено</b>",
"stop": "🚨 Остановить",
"choose_delete": "♻️ <b>Выберите элемент очереди для удаления</b>",
}
strings_de = {
"already_joined": "🚫 <b>Du bist bereits in einem Sprachchat</b>",
"joined": "🎙 <b>In Sprachchat beigetreten</b>",
"no_reply": "🚫 <b>Antworte auf eine Nachricht</b>",
"no_queue": "🚫 <b>Keine Warteschlange</b>",
"queue": "🎙 <b>Warteschlange</b>:\n\n{}",
"queueadd": "🎧 <b>{} zur Warteschlange hinzugefügt</b>",
"queueaddv": "📼 <b>{} zur Warteschlange hinzugefügt</b>",
"downloading": "📥 <b>Herunterladen...</b>",
"playing": "🎶 <b>Spiele {}</b>",
"playing_with_next": "🎶 <b>Spiele {}</b>\n➡️ <b>Nächster: {}</b>",
"pause": "🎵 Pause",
"play": "🎵 Spielen",
"mute": "🔇 Stumm",
"unmute": "🔈 Ton",
"next": "➡️ Nächster",
"stopped": "🚨 <b>Gestoppt</b>",
"stop": "🚨 Stoppen",
"choose_delete": (
"♻️ <b>Wähle einen Eintrag aus der Warteschlange zum Löschen</b>"
),
}
strings_tr = {
"already_joined": "🚫 <b>Zaten sesli sohbette</b>",
"joined": "🎙 <b>Sesli sohbete katıldı</b>",
"no_reply": "🚫 <b>Bir mesaja yanıt verin</b>",
"no_queue": "🚫 <b>Kuyruk yok</b>",
"queue": "🎙 <b>Kuyruk</b>:\n\n{}",
"queueadd": "🎧 <b>{} kuyruğa eklendi</b>",
"queueaddv": "📼 <b>{} kuyruğa eklendi</b>",
"downloading": "📥 <b>İndiriliyor...</b>",
"playing": "🎶 <b>Oynatılıyor {}</b>",
"playing_with_next": "🎶 <b>Oynatılıyor {}</b>\n➡️ <b>Sonraki: {}</b>",
"pause": "🎵 Duraklat",
"play": "🎵 Oynat",
"mute": "🔇 Sessiz",
"unmute": "🔈 Sesi aç",
"next": "➡️ Sonraki",
"stopped": "🚨 <b>Durduruldu</b>",
"stop": "🚨 Durdur",
"choose_delete": "♻️ <b>Silinecek kuyruk öğesini seçin</b>",
}
strings_uz = {
"already_joined": "🚫 <b>Siz allaqachon g‘ovushda</b>",
"joined": "🎙 <b>G‘ovushga qo‘shildi</b>",
"no_reply": "🚫 <b>Xabarga javob bering</b>",
"no_queue": "🚫 <b>Navbat yo‘q</b>",
"queue": "🎙 <b>Navbat</b>:\n\n{}",
"queueadd": "🎧 <b>{} navbatga qo‘shildi</b>",
"queueaddv": "📼 <b>{} navbatga qo‘shildi</b>",
"downloading": "📥 <b>Yuklanmoqda...</b>",
"playing": "🎶 <b>O‘ynatilmoqda {}</b>",
"playing_with_next": "🎶 <b>O‘ynatilmoqda {}</b>\n➡️ <b>Keyingi: {}</b>",
"pause": "🎵 To‘xtatish",
"play": "🎵 O‘ynatish",
"mute": "🔇 Sessiz",
"unmute": "🔈 Suv",
"next": "➡️ Keyingi",
"stopped": "🚨 <b>To‘xtatildi</b>",
"stop": "🚨 To‘xtatish",
"choose_delete": "♻️ <b>O‘chirish uchun navbatdagi elementni tanlang</b>",
}
strings_hi = {
"already_joined": "🚫 <b>आप पहले से ही एक वाणिज्यिक चैट में हैं</b>",
"joined": "🎙 <b>वाणिज्यिक चैट में शामिल हो गए</b>",
"no_reply": "🚫 <b>एक संदेश पर उत्तर दें</b>",
"no_queue": "🚫 <b>कोई पंक्ति नहीं</b>",
"queue": "🎙 <b>पंक्ति</b>:\n\n{}",
"queueadd": "🎧 <b>{} पंक्ति में जोड़ा गया</b>",
"queueaddv": "📼 <b>{} पंक्ति में जोड़ा गया</b>",
"downloading": "📥 <b>डाउनलोड हो रहा है...</b>",
"playing": "🎶 <b>खेला जा रहा है {}</b>",
"playing_with_next": "🎶 <b>खेला जा रहा है {}</b>\n➡️ <b>अगला: {}</b>",
"pause": "🎵 रोकें",
"play": "🎵 खेलो",
"mute": "🔇 मौन",
"unmute": "🔈 आवाज",
"next": "➡️ अगला",
"stopped": "🚨 <b>रोक दिया</b>",
"stop": "🚨 रोकें",
"choose_delete": "♻️ <b>हटाने के लिए पंक्ति आइटम का चयन करें</b>",
}
_calls = {}
_muted = {}
_forms = {}
_queue = {}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"silent_queue",
False,
"Do not notify about track changes in chat",
validator=loader.validators.Boolean(),
)
)
async def client_ready(self, client, db):
# Monkeypatch pytgcalls MtProtoClient to support hikka's custom one
class HikkaTLClient(MtProtoClient):
def __init__(
self,
cache_duration: int,
client: CustomTelegramClient,
):
self._bind_client = None
from pytgcalls.mtproto.telethon_client import TelethonClient
self._bind_client = TelethonClient(
cache_duration,
client,
)
class CustomPyTgCalls(PyTgCalls):
def __init__(
self,
app: CustomTelegramClient,
cache_duration: int = 120,
overload_quiet_mode: bool = False,
# BETA SUPPORT, BY DEFAULT IS DISABLED
multi_thread: bool = False,
):
Methods.__init__(self)
Scaffold.__init__(self)
self._app = HikkaTLClient(
cache_duration,
app,
)
self._is_running = False
self._env_checker = Environment(
self._REQUIRED_NODEJS_VERSION,
self._REQUIRED_PYROGRAM_VERSION,
self._REQUIRED_TELETHON_VERSION,
self._app.client,
)
self._call_holder = CallHolder()
self._cache_user_peer = Cache()
self._wait_result = UpdateSolver()
self._on_event_update = HandlersHolder()
self._binding = Binding(
overload_quiet_mode,
multi_thread,
)
def cleanup():
if self._async_core is not None:
self._async_core.cancel()
atexit.register(cleanup)
# //
self._app = CustomPyTgCalls(client)
self._dir = tempfile.mkdtemp()
await self._app.start()
self._app._on_event_update.add_handler("STREAM_END_HANDLER", self.stream_ended)
self.musicdl = await self.import_lib(
"https://libs.hikariatama.ru/musicdl.py",
suspend_on_error=True,
)
async def stream_ended(self, client: PyTgCalls, update: types.Update):
chat_id = update.chat_id
with contextlib.suppress(IndexError):
self._queue[chat_id].pop(0)
if not self._queue.get(chat_id):
with contextlib.suppress(Exception):
await client.leave_group_call(chat_id)
return
self._queue[chat_id][0]["playing"] = True
if self._queue[chat_id][0]["audio"]:
await self.play(chat_id, self._queue[chat_id][0]["data"])
else:
if self._queue[chat_id][0]["youtube"]:
await self.play_video_yt(chat_id, self._queue[chat_id][0]["data"])
else:
await self.play_video(chat_id, self._queue[chat_id][0]["data"])
async def _play(
self,
chat_id: int,
stream,
stream_type,
reattempt: bool = False,
):
self._muted.setdefault(chat_id, False)
try:
await self._app.join_group_call(
chat_id,
stream,
stream_type=stream_type,
)
except AlreadyJoinedError:
await self._app.change_stream(chat_id, stream)
except NoActiveGroupCall:
if reattempt:
raise
await self._client(CreateGroupCallRequest(chat_id))
await self._play(chat_id, stream, stream_type, True)
def _get_fn(self, message: Message) -> str:
filename = None
with contextlib.suppress(Exception):
attr = next(
attr for attr in getattr(message, "document", message).attributes
)
filename = (
getattr(attr, "performer", "") + " - " + getattr(attr, "title", "")
)
if not filename:
with contextlib.suppress(Exception):
filename = next(
attr
for attr in getattr(message, "document", message).attributes
if isinstance(attr, DocumentAttributeFilename)
).file_name
return filename
@loader.command(
ru_doc=(
"<ответ на песню или ее имя> - Добавить песню в очередь прослушивания чата"
),
de_doc=(
"<auf eine Musik oder ihren Namen antworten> - Fügen Sie eine Musik in die"
" Warteschlange für die Wiedergabe im Chat hinzu"
),
tr_doc="<şarkıya veya adına yanıt> - Sohbette dinleme sırasına şarkı ekleyin",
hi_doc=(
"<एक गाने या उसके नाम पर उत्तर> - चैट में प्लेबैक के लिए गाने को लंबित करने"
" के लिए गाने को लंबित करें"
),
uz_doc=(
"<musiqaga yoki uning nomiga javob> - Chatda o'qish uchun musiqani qo'shing"
),
)
async def qadd(self, message: Message):
"""<reply to song or its name> - Add song to chat's voicechat queue"""
reply = await message.get_reply_message()
song = utils.get_args_raw(message)
if (not reply or not reply.media) and not song:
await utils.answer(message, self.strings("no_reply"))
return
message = await utils.answer(message, self.strings("downloading"))
filename = None
if not reply or not reply.media and song:
song, filename = await self._download_audio(song, message)
if not song:
await utils.answer(message, self.strings("no_reply"))
return
if song:
raw_data = song
else:
raw_data = await self._client.download_file(reply.document, bytes)
filename = self._get_fn(reply)
if not filename:
filename = "Some cool song"
filename = re.sub(r"\(.*?\)", "", filename)
chat_id = utils.get_chat_id(message)
self._queue.setdefault(chat_id, []).append(
{"data": raw_data, "filename": filename, "playing": False, "audio": True}
)
if not any(i["playing"] for i in self._queue[chat_id]):
self._queue[chat_id][-1]["playing"] = True
await self.play(chat_id, raw_data)
await utils.answer(message, self.strings("queueadd").format(filename))
@loader.command(
ru_doc="<ответ на видео или ссылка на YouTube> - Добавить видео в очередь чата",
de_doc=(
"<auf ein Video oder einen YouTube-Link antworten> - Fügen Sie ein Video in"
" die Warteschlange des Chats ein"
),
tr_doc=(
"<bir videoya veya YouTube bağlantısına yanıt> - Bir videoyu sohbet"
" sırasına ekleyin"
),
hi_doc="<एक वीडियो या YouTube लिंक पर उत्तर> - चैट की लंबित को एक वीडियो जोड़ें",
uz_doc=(
"<videoga yoki YouTube havolasiga javob> - Chatni qo'shish uchun video"
" qo'shing"
),
)
async def qaddv(self, message: Message):
"""<reply to video or yt link> - Add video to chat's voicechat queue"""
reply = await message.get_reply_message()
link = utils.get_args_raw(message)
if (not reply or not reply.media) and not link:
await utils.answer(message, self.strings("no_reply"))
return
filename = None
message = await utils.answer(message, self.strings("downloading"))
if reply and reply.media:
raw_data = await self._client.download_file(reply.document, bytes)
filename = self._get_fn(reply)
else:
raw_data = link
with contextlib.suppress(Exception):
with YoutubeDL() as ydl:
filename = ydl.extract_info(link, download=False).get(
"title",
None,
)
if not filename:
filename = "Some cool video"
filename = re.sub(r"\(.*?\)", "", filename)
chat_id = utils.get_chat_id(message)
self._queue.setdefault(chat_id, []).append(
{
"data": raw_data,
"filename": filename,
"playing": False,
"audio": False,
"youtube": not (reply and reply.media),
}
)
if not any(i["playing"] for i in self._queue[chat_id]):
self._queue[chat_id][-1]["playing"] = True
if self._queue[chat_id][-1]["youtube"]:
await self.play_video_yt(chat_id, raw_data)
else:
await self.play_video(chat_id, raw_data)
await utils.answer(message, self.strings("queueadd").format(filename))
@loader.command(
ru_doc="Переключить трек",
de_doc="Track wechseln",
tr_doc="Parçayı değiştir",
hi_doc="ट्रैक बदलें",
uz_doc="Trackni o'zgartiring",
)
async def qnext(self, message: Message):
"""Skips current audio in queue"""
chat_id = utils.get_chat_id(message)
if len(self._queue.get(chat_id, [])) <= 1:
await utils.answer(message, self.strings("no_queue"))
return
self._queue[chat_id].pop(0)
self._queue[chat_id][0]["playing"] = True
if self._queue[chat_id][0]["audio"]:
await self.play(chat_id, self._queue[chat_id][0]["data"])
else:
if self._queue[chat_id][0]["youtube"]:
await self.play_video_yt(chat_id, self._queue[chat_id][0]["data"])
else:
await self.play_video(chat_id, self._queue[chat_id][0]["data"])
await message.delete()
async def _download_audio(self, name: str, message: Message) -> bytes:
result = await self.musicdl.dl(name, only_document=True)
try:
return await self._client.download_file(result, bytes), self._get_fn(result)
except Exception:
return None, None
async def vcqcmd(self, message: Message):
"""Get current chat's queue"""
chat_id = utils.get_chat_id(message)
if not self._queue.get(chat_id):
await utils.answer(message, self.strings("no_queue"))
return
await utils.answer(
message,
self.strings("queue").format(
"\n".join(
[
("🎧" if i["playing"] else "🕓")
+ ("" if i["audio"] else "🎬")
+ f" {i['filename']}"
for i in self._queue[chat_id]
]
)
),
)
async def qrmcmd(self, message: Message):
"""Remove song from queue"""
if not self._queue.get(chat_id) or all(
i["playing"] for i in self._queue[chat_id]
):
await utils.answer(message, self.strings("no_queue"))
return
chat_id = utils.get_chat_id(message)
await self.inline.form(
message=message,
text=self.strings("choose_delete"),
reply_markup=utils.chunks(
[
{
"text": ("🎧" if i["audio"] else "🎬") + i["filename"],
"callback": self._inline__delete,
"args": (chat_id, index),
}
for index, i in enumerate(self._queue[chat_id])
if not i["playing"]
],
2,
),
)
async def _inline__delete(self, call: InlineCall, chat_id: int, index: int):
del self._queue[chat_id][index]
await call.answer("OK")
await call.delete()
async def _inline__pause(self, call: InlineCall, chat_id: int):
await self._app.pause_stream(chat_id)
msg, markup = self._get_inline_info(chat_id)
await call.edit(msg, reply_markup=markup)
async def _inline__play(self, call: InlineCall, chat_id: int):
await self._app.resume_stream(chat_id)
msg, markup = self._get_inline_info(chat_id)
await call.edit(msg, reply_markup=markup)
async def _inline__mute(self, call: InlineCall, chat_id: int):
await self._app.mute_stream(chat_id)
self._muted[chat_id] = True
msg, markup = self._get_inline_info(chat_id)
await call.edit(msg, reply_markup=markup)
async def _inline__unmute(self, call: InlineCall, chat_id: int):
await self._app.unmute_stream(chat_id)
self._muted[chat_id] = False
msg, markup = self._get_inline_info(chat_id)
await call.edit(msg, reply_markup=markup)
async def _inline__stop(self, call: InlineCall, chat_id: int):
with contextlib.suppress(KeyError):
del self._queue[chat_id]
with contextlib.suppress(KeyError):
del self._forms[chat_id]
with contextlib.suppress(KeyError):
del self._muted[chat_id]
await self._app.leave_group_call(chat_id)
await utils.answer(call, self.strings("stopped"))
async def _inline__next(self, call: InlineCall, chat_id: int):
self._queue[chat_id].pop(0)
self._queue[chat_id][0]["playing"] = True
if self._queue[chat_id][0]["audio"]:
await self.play(chat_id, self._queue[chat_id][0]["data"])
else:
if self._queue[chat_id][0]["youtube"]:
await self.play_video_yt(chat_id, self._queue[chat_id][0]["data"])
else:
await self.play_video(chat_id, self._queue[chat_id][0]["data"])
msg, markup = self._get_inline_info(chat_id)
await call.edit(msg, reply_markup=markup)
def _get_inline_info(self, chat_id: int) -> tuple:
if not self._queue.get(chat_id):
return None, None
if len(self._queue[chat_id]) == 1:
msg = self.strings("playing").format(
utils.escape_html(self._queue[chat_id][0]["filename"]),
)
else:
msg = self.strings("playing_with_next").format(
utils.escape_html(self._queue[chat_id][0]["filename"]),
utils.escape_html(self._queue[chat_id][1]["filename"]),
)
try:
is_playing = self._app.get_call(chat_id).status == "playing"
except Exception:
is_playing = True
markup = [
[
{
"text": self.strings("stop"),
"callback": self._inline__stop,
"args": (chat_id,),
},
],
[
*(
[
{
"text": self.strings("pause"),
"callback": self._inline__pause,
"args": (chat_id,),
}
]
if is_playing
else [
{
"text": self.strings("play"),
"callback": self._inline__play,
"args": (chat_id,),
}
]
),
*(
[
{
"text": self.strings("mute"),
"callback": self._inline__mute,
"args": (chat_id,),
}
]
if not self._muted.get(chat_id, False)
else [
{
"text": self.strings("unmute"),
"callback": self._inline__unmute,
"args": (chat_id,),
}
]
),
],
*(
[
[
{
"text": self.strings("next"),
"callback": self._inline__next,
"args": (chat_id,),
}
]
]
if len(self._queue[chat_id]) > 1
else []
),
]
return msg, markup
@loader.command(
ru_doc="Приостановить воспроизведение",
de_doc="Pausiere die Wiedergabe",
tr_doc="Oynatmayı duraklat",
hi_doc="प्लेबैक को रोकें",
uz_doc="Oynatmani to'xtatish",
)
async def qpause(self, message: Message):
"""Pause current chat's queue"""
chat_id = utils.get_chat_id(message)
with contextlib.suppress(Exception):
await self._app.pause_stream(chat_id)
msg, markup = self._get_inline_info(chat_id)
with contextlib.suppress(Exception):
await self._forms[chat_id].delete()
self._forms[chat_id] = await utils.answer(message, msg, reply_markup=markup)
@loader.command(
ru_doc="Остановить воспроизведение",
de_doc="Stoppe die Wiedergabe",
tr_doc="Oynatmayı durdur",
hi_doc="प्लेबैक को बंद करें",
uz_doc="Oynatmani to'xtatish",
)
async def qstop(self, message: Message):
"""Stop current chat's queue"""
await self._inline__stop(message, utils.get_chat_id(message))
@loader.command(
ru_doc="Продолжить воспроизведение",
de_doc="Fahre die Wiedergabe fort",
tr_doc="Oynatmaya devam et",
hi_doc="प्लेबैक को फिर से शुरू करें",
uz_doc="Oynatmani davom ettirish",
)
async def qresume(self, message: Message):
"""Resume current chat's queue"""
chat_id = utils.get_chat_id(message)
with contextlib.suppress(Exception):
await self._app.resume_stream(chat_id)
msg, markup = self._get_inline_info(chat_id)
with contextlib.suppress(Exception):
await self._forms[chat_id].delete()
self._forms[chat_id] = await utils.answer(message, msg, reply_markup=markup)
async def play(self, chat_id: int, array: bytes):
file = os.path.join(self._dir, f"{utils.rand(8)}.ogg")
with open(file, "wb") as f:
f.write(array)
await self._play(
chat_id,
types.AudioPiped(file, types.HighQualityAudio()),
StreamType().pulse_stream,
)
await asyncio.sleep(1)
if not self.config["silent_queue"]:
msg, markup = self._get_inline_info(chat_id)
with contextlib.suppress(Exception):
await self._forms[chat_id].delete()
self._forms[chat_id] = await self.inline.form(
message=chat_id, text=msg, reply_markup=markup
)
async def play_video(self, chat_id: int, array: bytes):
file = os.path.join(self._dir, f"{utils.rand(8)}.mp4")
with open(file, "wb") as f:
f.write(array)
await self._play(
chat_id,
types.AudioVideoPiped(
file,
types.HighQualityAudio(),
types.HighQualityVideo(),
),
StreamType().pulse_stream,
)
await asyncio.sleep(1)
if not self.config["silent_queue"]:
msg, markup = self._get_inline_info(chat_id)
with contextlib.suppress(Exception):
await self._forms[chat_id].delete()
self._forms[chat_id] = await self.inline.form(
message=chat_id, text=msg, reply_markup=markup
)
async def play_video_yt(self, chat_id: int, link: str):
proc = await asyncio.create_subprocess_exec(
"youtube-dl",
"-g",
"-f",
"worst",
link,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, _ = await proc.communicate()
await self._play(
chat_id,
types.AudioVideoPiped(
stdout.decode().split("\n")[0],
types.HighQualityAudio(),
types.HighQualityVideo(),
),
StreamType().pulse_stream,
)
await asyncio.sleep(1)
if not self.config["silent_queue"]:
msg, markup = self._get_inline_info(chat_id)
with contextlib.suppress(Exception):
await self._forms[chat_id].delete()
self._forms[chat_id] = await self.inline.form(
message=chat_id,
text=msg,
reply_markup=markup,
)
async def on_unload(self):
shutil.rmtree(self._dir)
for chat_id in self._muted:
await self._app.leave_group_call(chat_id)