Ejemplo n.º 1
0
async def handler(event):
    try:
        chat = await event.get_chat()
        await event.delete()
        async with client.action(chat, 'record-voice'):
            origin_text = event.message.text.replace('!d ', '')
            voicename, _duration = speech.demon(origin_text)

            chat = await event.get_chat()
            wafe_form = speech.get_waveform(0, 31, 100)
            await client.send_file(chat,
                                   voicename,
                                   reply_to=event.message.reply_to_msg_id,
                                   attributes=[
                                       types.DocumentAttributeAudio(
                                           duration=_duration,
                                           voice=True,
                                           waveform=utils.encode_waveform(
                                               bytes(wafe_form)))
                                   ])  # 2**5 because 5-bit

            speech.try_delete(voicename)

    except Exception as e:
        print(e)
Ejemplo n.º 2
0
 async def oggcmd(self, message):
     """.ogg <reply to audio>
                 Сконвертировать войс в ogg
             """
     reply = await message.get_reply_message()
     formatik = 'ogg'
     await message.edit("Downloading...")
     au = io.BytesIO()
     await message.client.download_media(reply.media.document, au)
     au.seek(0)
     await message.edit(f"Converting в {formatik}...")
     audio = AudioSegment.from_file(au)
     m = io.BytesIO()
     m.name = "Converted_to." + formatik
     audio.split_to_mono()
     await message.edit("Sending...")
     audio.export(m, format=formatik)
     m.seek(0)
     await message.client.send_file(
         message.to_id,
         m,
         reply_to=reply.id,
         attributes=[
             types.DocumentAttributeAudio(
                 duration=reply.document.attributes[0].duration,
                 title=f"Converted to " + formatik,
                 performer="Converter")
         ])
     await message.delete()
Ejemplo n.º 3
0
async def voice(event):
    if environ.get("isSuspended") == "True" or environ.get(
            "BG_DEFAULT") == 0 or environ.get(
                "BG_DEFAULT") == '0' or environ.get("BG_DEFAULT") == None:
        return
    is_enabled = environ.get("enabled", "True")
    if is_enabled == "True":
        if event.forward:
            return
        if event.voice:
            chat = await event.get_chat()
            await event.delete()
            async with event.client.action(chat, 'record-voice'):
                path_to_voice = await event.download_media()
                voicename, _duration = speech.megre_sounds(
                    path_to_voice, environ["BG_DEFAULT"])

                chat = await event.get_chat()
                wafe_form = speech.get_waveform(0, 31, 100)
                await event.client.send_file(
                    chat,
                    voicename,
                    reply_to=event.message.reply_to_msg_id,
                    attributes=[
                        types.DocumentAttributeAudio(
                            duration=_duration,
                            voice=True,
                            waveform=utils.encode_waveform(bytes(wafe_form)))
                    ])  # 2**5 because 5-bit

                speech.try_delete(voicename)
Ejemplo n.º 4
0
async def voice_note(event):
    if environ.get("isSuspended") == "True":
        return
    try:
        chat = await event.get_chat()
        await event.delete()
        async with event.client.action(chat, 'record-voice'):
            origin_text = event.message.text.replace('.a ', '')
            voicename, _duration = speech.syntese(origin_text, background=True)

            chat = await event.get_chat()
            wafe_form = speech.get_waveform(0, 31, 100)
            await event.client.send_file(
                chat,
                voicename,
                reply_to=event.message.reply_to_msg_id,
                attributes=[
                    types.DocumentAttributeAudio(
                        duration=_duration,
                        voice=True,
                        waveform=utils.encode_waveform(bytes(wafe_form)))
                ])  # 2**5 because 5-bit

            speech.try_delete(voicename)

    except Exception as e:
        print(e)
Ejemplo n.º 5
0
    async def byrobertscmd(self, message):
        """.byroberts <reply to audio>
		    Добавить в конец аудио "Directed by Robert B Weide"
		"""
        v = False
        reply = await message.get_reply_message()
        if not reply:
            await message.edit("А где реплай?")
            return
        await message.edit("Скачиваем...")
        fname = await message.client.download_media(message=reply.media)
        await message.edit("Делаем магию...")
        if fname.endswith(".oga") or fname.endswith(".ogg"):
            v = True
            audio = AudioSegment.from_file(fname)
        elif fname.endswith(".mp3") or fname.endswith(
                ".m4a") or fname.endswith(".wav"):
            audio = AudioSegment.from_file(fname)
        else:
            await message.edit("<b>Unsupported format!</b>")
            os.remove(fname)
            return
        if os.path.isfile("directed.mp3") == False:
            open("directed.mp3", "wb").write(
                requests.get(
                    "https://raw.githubusercontent.com/Daniel3k00/files-for-modules/master/directed.mp3"
                ).content)
        audio.export("temp.mp3", format="mp3")
        os.remove(fname)
        out = AudioSegment.empty()
        out += AudioSegment.from_file("temp.mp3")
        out += AudioSegment.from_file("directed.mp3").apply_gain(+10)
        await message.edit("Отправляем...")
        m = io.BytesIO()
        if v:
            m.name = "voice.ogg"
            audio.split_to_mono()
            out.export(m, format="ogg", bitrate="64k", codec="libopus")
            await message.client.send_file(message.to_id,
                                           m,
                                           reply_to=reply.id,
                                           voice_note=True)
        else:
            m.name = "DirectedAudio.mp3"
            out.export(m, format="mp3")
            await message.client.send_file(
                message.to_id,
                m,
                reply_to=reply.id,
                attributes=[
                    types.DocumentAttributeAudio(
                        duration=reply.document.attributes[0].duration,
                        title="Directed",
                        performer="Robert B. Weide")
                ])
        await message.delete()
        os.remove("temp.mp3")
        os.remove("directed.mp3")
Ejemplo n.º 6
0
    async def slowscmd(self, message):
        """.slows <reply to audio>
		    Замедлить аудио 0.5x
		"""
        v = False
        reply = await message.get_reply_message()
        if not reply:
            await message.edit("А где реплай?")
            return
        await message.edit("Скачиваем...")
        fname = await message.client.download_media(message=reply.media)
        await message.edit("Замедляем...")
        if fname.endswith(".oga") or fname.endswith(".ogg"):
            v = True
            audio = AudioSegment.from_file(fname)
        elif fname.endswith(".mp3") or fname.endswith(
                ".m4a") or fname.endswith(".wav"):
            audio = AudioSegment.from_file(fname)
        else:
            await message.edit("<b>Unsupported format!</b>")
            os.remove(fname)
            return
        sound = AudioSegment.from_file(fname)
        sound_with_altered_frame_rate = sound._spawn(
            sound.raw_data,
            overrides={"frame_rate": int(sound.frame_rate * 0.5)})
        sound = sound_with_altered_frame_rate.set_frame_rate(sound.frame_rate)
        await message.edit("Отправляем...")
        m = io.BytesIO()
        if v:
            m.name = "voice.ogg"
            audio.split_to_mono()
            sound.export(m, format="ogg", bitrate="64k", codec="libopus")
            await message.client.send_file(message.to_id,
                                           m,
                                           reply_to=reply.id,
                                           voice_note=True)
        else:
            m.name = "Slow.mp3"
            sound.export(m, format="mp3")
            await message.client.send_file(
                message.to_id,
                m,
                reply_to=reply.id,
                attributes=[
                    types.DocumentAttributeAudio(
                        duration=reply.document.attributes[0].duration,
                        title="Slowed",
                        performer="Slowed")
                ])
        await message.delete()
Ejemplo n.º 7
0
    async def toformatcmd(self, message):
        """.toformat [format] <reply to audio>
		    Сконвертировать аудио/видео/войс в нужный формат
			Поддерживаются mp3, m4a, ogg, mpeg, wav, oga
		"""
        frmts = ['ogg', 'mpeg', 'mp3', 'wav', 'oga', 'm4a', '3gp']
        reply = await message.get_reply_message()
        if not reply:
            await message.edit("А где реплай?")
            return
        else:
            try:
                reply.media.document.attributes[0].duration
                if utils.get_args_raw(message):
                    if utils.get_args_raw(message) not in frmts:
                        await message.edit(
                            f"Формат {utils.get_args_raw(message)} для конвертирования не поддерживается!"
                        )
                        return
                    formatik = utils.get_args_raw(message)
                else:
                    await message.edit("Укажите формат конвертирования")
                    return
            except:
                await message.edit("Это не аудиофайл!")
                return
        await message.edit("Скачиваем...")
        au = io.BytesIO()
        await message.client.download_media(reply.media.document, au)
        au.seek(0)
        await message.edit(f"Конвертируем в {formatik}...")
        audio = AudioSegment.from_file(au)
        m = io.BytesIO()
        m.name = "Converted_to." + formatik
        audio.split_to_mono()
        await message.edit("Экспортируем...")
        audio.export(m, format=formatik)
        await message.edit("Отправляем...")
        m.seek(0)
        await message.client.send_file(
            message.to_id,
            m,
            reply_to=reply.id,
            attributes=[
                types.DocumentAttributeAudio(
                    duration=reply.document.attributes[0].duration,
                    title=f"Converted to " + formatik,
                    performer="Converter")
            ])
        await message.delete()
Ejemplo n.º 8
0
    async def revscmd(self, message):
        """.revs <reply to audio>
		    Развернуть аудио
		"""
        v = False
        reply = await message.get_reply_message()
        if not reply:
            await message.edit("А где реплай?")
            return
        await message.edit("Скачиваем...")
        fname = await message.client.download_media(message=reply.media)
        await message.edit("Reverse'им...")
        if fname.endswith(".oga") or fname.endswith(".ogg"):
            v = True
            audio = AudioSegment.from_file(fname)
        elif fname.endswith(".mp3") or fname.endswith(
                ".m4a") or fname.endswith(".wav"):
            audio = AudioSegment.from_file(fname)
        else:
            await message.edit("<b>Unsupported format!</b>")
            os.remove(fname)
            return
        rev = audio.reverse()
        audio = rev
        m = io.BytesIO()
        await message.edit("Отправляем...")
        if v:
            m.name = "voice.ogg"
            audio.split_to_mono()
            audio.export(m, format="ogg", bitrate="64k", codec="libopus")
            await message.client.send_file(message.to_id,
                                           m,
                                           reply_to=reply.id,
                                           voice_note=True)
        else:
            m.name = "Reversed.mp3"
            audio.export(m, format="mp3")
            await message.client.send_file(
                message.to_id,
                m,
                reply_to=reply.id,
                attributes=[
                    types.DocumentAttributeAudio(
                        duration=reply.document.attributes[0].duration,
                        title="Reversed",
                        performer="Reversed")
                ])
        await message.delete()
        os.remove(fname)
Ejemplo n.º 9
0
    async def normscmd(self, message):
        """.norms <reply to audio>
		    Нормализовать звук (Из тихого - нормальный)
		"""
        v = False
        reply = await message.get_reply_message()
        if not reply:
            await message.edit("А где реплай?")
            return
        await message.edit("Скачиваем...")
        fname = await message.client.download_media(message=reply.media)
        await message.edit("Нормализуем звук...")
        if fname.endswith(".oga") or fname.endswith(".ogg"):
            v = True
            audio = AudioSegment.from_file(fname)
        elif fname.endswith(".mp3") or fname.endswith(
                ".m4a") or fname.endswith(".wav"):
            audio = AudioSegment.from_file(fname)
        else:
            await message.edit("<b>Unsupported format!</b>")
            os.remove(fname)
            return
        sound = AudioSegment.from_file(fname)
        sound = effects.normalize(sound)
        await message.edit("Отправляем...")
        m = io.BytesIO()
        if v:
            m.name = "voice.ogg"
            audio.split_to_mono()
            sound.export(m, format="ogg", bitrate="64k", codec="libopus")
            await message.client.send_file(message.to_id,
                                           m,
                                           reply_to=reply.id,
                                           voice_note=True)
        else:
            m.name = "Normalized.mp3"
            sound.export(m, format="mp3")
            await message.client.send_file(
                message.to_id,
                m,
                reply_to=reply.id,
                attributes=[
                    types.DocumentAttributeAudio(
                        duration=reply.document.attributes[0].duration,
                        title="Left",
                        performer="Left")
                ])
        await message.delete()
Ejemplo n.º 10
0
    async def rightscmd(self, message):
        """.rights <reply to audio>
		    Весь звук в правый канал
		"""
        v = False
        reply = await message.get_reply_message()
        if not reply:
            await message.edit("А где реплай?")
            return
        await message.edit("Скачиваем...")
        fname = await message.client.download_media(message=reply.media)
        await message.edit("Pan'им...")
        if fname.endswith(".oga") or fname.endswith(".ogg"):
            v = True
            sound = AudioSegment.from_file(fname)
        elif fname.endswith(".mp3") or fname.endswith(
                ".m4a") or fname.endswith(".wav"):
            sound = AudioSegment.from_file(fname)
        else:
            await message.edit("<b>Unsupported format!</b>")
            os.remove(fname)
            return
        sound = AudioSegment.from_file(fname)
        sound = effects.pan(sound, +1.0)
        await message.edit("Отправляем...")
        m = io.BytesIO()
        if v:
            m.name = "voice.ogg"
            sound.export(m, format="ogg", bitrate="64k", codec="libopus")
            await message.client.send_file(message.to_id,
                                           m,
                                           reply_to=reply.id,
                                           voice_note=True)
        else:
            m.name = "Right.mp3"
            sound.export(m, format="mp3")
            await message.client.send_file(
                message.to_id,
                m,
                reply_to=reply.id,
                attributes=[
                    types.DocumentAttributeAudio(
                        duration=reply.document.attributes[0].duration,
                        title="Right",
                        performer="Right")
                ])
        await message.delete()
Ejemplo n.º 11
0
async def _(event):
    if not borg.me.bot:
        await event.delete()

    ts = event.raw_text.split(maxsplit=1)
    text = None if len(ts) < 2 else ts[1]

    if not text and event.is_reply:
        text = (await event.get_reply_message()).raw_text

    if not text:
        return

    file = io.BytesIO(await translator.tts(text))
    file.name = 'a.borg+tts'
    await borg.send_file(
        event.chat_id,
        file,
        reply_to=event.reply_to_msg_id if not borg.me.bot else None,
        attributes=[types.DocumentAttributeAudio(duration=0, voice=True)])
Ejemplo n.º 12
0
async def go_out(m, reply, audio, out, pref, title, fs=None):
    o = io.BytesIO()
    o.name = "audio." + ("ogg" if audio[1] else "mp3")
    if audio[1]: out.split_to_mono()
    await m.edit(f"[{pref}] Экспортирую...")
    out.export(o,
               format="ogg" if audio[1] else "mp3",
               bitrate="64k" if audio[1] else None,
               codec="libopus" if audio[1] else None)
    await m.edit(f"[{pref}] Отправляю...")
    await m.client.send_file(
        m.to_id,
        o,
        reply_to=reply.id,
        voice_note=audio[1],
        attributes=[
            types.DocumentAttributeAudio(duration=fs if fs else audio[2],
                                         title=title,
                                         performer="AudioEditor")
        ] if not audio[1] else None)
    await m.delete()
Ejemplo n.º 13
0
async def handler(event):
    if event.voice:
        chat = await event.get_chat()
        await event.delete()
        async with client.action(chat, 'record-voice'):
            path_to_voice = await event.download_media()
            voicename, _duration = speech.megre_sounds(path_to_voice)

            chat = await event.get_chat()
            wafe_form = speech.get_waveform(0, 31, 100)
            await client.send_file(chat,
                                   voicename,
                                   reply_to=event.message.reply_to_msg_id,
                                   attributes=[
                                       types.DocumentAttributeAudio(
                                           duration=_duration,
                                           voice=True,
                                           waveform=utils.encode_waveform(
                                               bytes(wafe_form)))
                                   ])  # 2**5 because 5-bit

            speech.try_delete(voicename)
Ejemplo n.º 14
0
async def go_out(self, m, audio, out, pref, title, fs=None, fmt='mp3'):
    o = io.BytesIO()
    o.name = "audio." + ("ogg" if audio.voice else "mp3")
    if audio.voice:
        out.split_to_mono()
    m = await utils.answer(m, self.strings("exporting").format(pref))
    out.export(o,
               format="ogg" if audio.voice else fmt,
               bitrate="64k" if audio.voice else None,
               codec="libopus" if audio.voice else None)
    o.seek(0)
    await utils.answer(
        m,
        o,
        reply_to=audio.reply.id,
        voice_note=audio.voice,
        attributes=[
            types.DocumentAttributeAudio(
                duration=fs or audio.duration,
                title=title,
                performer="AudioEditor",
            )
        ] if not audio.voice else None,
    )
Ejemplo n.º 15
0
async def bassbooster(e):
    v = False
    accentuate_db = 40
    reply = await e.get_reply_message()
    if not reply:
        await e.edit("**Bir səsli mediaya cavab verin**")
        return
    if e.pattern_match.group(1):
        ar = e.pattern_match.group(1)
        try:
            int(ar)
            if int(ar) >= 2 and int(ar) <= 100:
                accentuate_db = int(ar)
            else:
                await e.edit("**BassBost** `səviyyəsi 2-100 arası olmalıdır.`")
                return
        except Exception as exx:
            await e.edit("`Bir xəta baş verdi` \n**Xəta:** " + str(exx))
            return
    else:
        accentuate_db = 2
    await e.edit("`Fayl yüklənilir...`")
    fname = await e.client.download_media(message=reply.media)
    await e.edit("`Bass effekti hazırlanır...`")
    if fname.endswith(".oga") or fname.endswith(".ogg"):
        v = True
        audio = AudioSegment.from_file(fname)
    elif fname.endswith(".mp3") or fname.endswith(".m4a") or fname.endswith(
            ".wav"):
        audio = AudioSegment.from_file(fname)
    else:
        await e.edit(
            "`Dəstəklənməyən fayl tipi` \n**Hazırda dəstəklənən fayl tipləri :** `mp3, m4a, wav.`"
        )
        os.remove(fname)
        return
    sample_track = list(audio.get_array_of_samples())
    await asyncio.sleep(0.3)
    est_mean = np.mean(sample_track)
    await asyncio.sleep(0.3)
    est_std = 3 * np.std(sample_track) / (math.sqrt(2))
    await asyncio.sleep(0.3)
    bass_factor = int(round((est_std - est_mean) * 0.005))
    await asyncio.sleep(5)
    attenuate_db = 0
    filtered = audio.low_pass_filter(bass_factor)
    await asyncio.sleep(5)
    out = (audio - attenuate_db).overlay(filtered + accentuate_db)
    await asyncio.sleep(6)
    m = io.BytesIO()
    if v:
        m.name = "voice.ogg"
        out.split_to_mono()
        await e.edit("`Hazırlanır...`")
        await asyncio.sleep(0.3)
        out.export(m, format="ogg", bitrate="64k", codec="libopus")
        await e.edit("`Effekt hazırlandı\n Fayl göndərilir...`")
        await e.client.send_file(
            e.to_id,
            m,
            reply_to=reply.id,
            voice_note=True,
            caption=
            "[U S Σ R Δ T O R](t.me/UseratorOT) `ilə bass gücləndirildi`",
        )

    else:
        m.name = "UseratorBASS.mp3"
        await e.edit("`Hazırlanır...`")
        await asyncio.sleep(0.3)
        out.export(m, format="mp3")
        await e.edit("`Effekt hazırlandı\n Fayl göndərilir...`")
        await e.client.send_file(
            e.to_id,
            m,
            reply_to=reply.id,
            attributes=[
                types.DocumentAttributeAudio(
                    duration=reply.document.attributes[0].duration,
                    title=f"BassBoost {str(accentuate_db)}lvl",
                    performer="BassBoost",
                )
            ],
            caption=
            "[U S Σ R Δ T O R](t.me/UseratorOT) `ilə bass gücləndirildi`",
        )
    await e.delete()
    os.remove(fname)
Ejemplo n.º 16
0
async def bruh(event):
  if environ.get("isSuspended") == "True":
        return
  await event.delete()
  wafe_form = speech.get_waveform(0, 31, 100)
  duration_ = int(os.popen("ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 'media/bruh.ogg'").read().split('.')[0])
  await event.client.send_file(event.chat_id, 'media/bruh.ogg', reply_to = event.message.reply_to_msg_id, attributes=[types.DocumentAttributeAudio(duration=duration_, voice=True, waveform=utils.encode_waveform(bytes(wafe_form)))]) # 2**5 because 5-bit
Ejemplo n.º 17
0
async def handler(event: events.NewMessage.Event):
    try:
        chat = await event.get_chat()
        await event.delete()
        async with client.action(chat, 'record-voice'):
            origin_text = event.message.text.replace('!a', '').strip()

            if event.message.is_reply and origin_text == '':
                msg = await event.message.get_reply_message()
                origin_text = msg.text

            voicename, _duration = speech.syntese(origin_text, background = True)

            chat = await event.get_chat()
            wafe_form = speech.get_waveform(0, 31, 100)
            await client.send_file(chat, voicename, reply_to = event.message.reply_to_msg_id, attributes=[types.DocumentAttributeAudio(duration=_duration, voice=True, waveform=utils.encode_waveform(bytes(wafe_form)))]) # 2**5 because 5-bit

            speech.try_delete(voicename)

    except Exception as e:
        print(e)
Ejemplo n.º 18
0
    async def echoscmd(self, message):
        """.echos <reply to audio>
		    Эхо эффект
		"""
        v = False
        reply = await message.get_reply_message()
        if not reply:
            await message.edit("А где реплай?")
            return
        await message.edit("Скачиваем...")
        fname = await message.client.download_media(message=reply.media)
        await message.edit("Echo'ярим...")
        if fname.endswith(".oga") or fname.endswith(".ogg"):
            v = True
            echo = AudioSegment.from_file(fname)
        elif fname.endswith(".mp3") or fname.endswith(
                ".m4a") or fname.endswith(".wav"):
            echo = AudioSegment.from_file(fname)

        else:
            await message.edit("<b>Unsupported format!</b>")
            os.remove(fname)
            return
        out = AudioSegment.empty()
        n = 200
        if os.path.isfile("none.mp3") == False:
            open("none.mp3", "wb").write(
                requests.get(
                    "https://raw.githubusercontent.com/Daniel3k00/files-for-modules/master/none.mp3"
                ).content)
        out += echo + AudioSegment.from_file("none.mp3")
        for i in range(5):
            echo = echo - 7
            out = out.overlay(echo, n)
            n += 200
        m = io.BytesIO()
        await message.edit("Отправляем...")
        if v:
            m.name = "voice.ogg"
            out.split_to_mono()
            out.export(m, format="ogg", bitrate="64k", codec="libopus")
            await message.client.send_file(message.to_id,
                                           m,
                                           reply_to=reply.id,
                                           voice_note=True)
        else:
            m.name = "Echo.mp3"
            out.export(m, format="mp3")
            await message.client.send_file(
                message.to_id,
                m,
                reply_to=reply.id,
                attributes=[
                    types.DocumentAttributeAudio(
                        duration=reply.document.attributes[0].duration,
                        title="Эхо эффект",
                        performer="Эхо эффект")
                ])
        await message.delete()
        os.remove(fname)
        os.remove("none.mp3")
Ejemplo n.º 19
0
    response = await tts_client.synthesize_speech(
        input=texttospeech.SynthesisInput(text=text),
        voice=texttospeech.VoiceSelectionParams(
            language_code=lang,
            ssml_gender=texttospeech.SsmlVoiceGender.FEMALE),
        audio_config=texttospeech.AudioConfig(
            audio_encoding=texttospeech.AudioEncoding.MP3))

    file = io.BytesIO(response.audio_content)
    file.name = 'a.borg+tts'
    await borg.send_file(
        event.chat_id,
        file,
        reply_to=event.reply_to_msg_id or event.id
        if not borg.me.bot else None,
        attributes=[types.DocumentAttributeAudio(duration=0, voice=True)])


@borg.on(borg.cmd("langs"))
async def _(event):
    langs = "\n".join([
        "<b>Supported languages:</b>",
        *(f"{l.language_code}: {l.display_name}" for _, l in tl_langs.items())
    ])
    if borg.me.bot:
        action = event.respond
    else:
        action = event.edit
    await action(langs, parse_mode="html")
Ejemplo n.º 20
0
async def __(message):
    v = False
    accentuate_db = 40
    reply = await message.get_reply_message()
    if not reply:
        await message.edit("Can You Reply To A MSG :?")
        return
    if message.pattern_match.group(1):
        ar = message.pattern_match.group(1)
        try:
            int(ar)
            if int(ar) >= 2 and int(ar) <= 100:
                accentuate_db = int(ar)
            else:
                await message.edit(
                    "`BassBost Level Should Be From 2 to 100 Only.`")
                return
        except Exception as exx:
            await message.edit("`SomeThing Went Wrong..` \n**Error:** " +
                               str(exx))
            return
    else:
        accentuate_db = 2
    await message.edit("`Downloading This File...`")
    fname = await borg.download_media(message=reply.media)
    await message.edit("`BassBoosting In Progress..`")
    if fname.endswith(".oga") or fname.endswith(".ogg"):
        v = True
        audio = AudioSegment.from_file(fname)
    elif fname.endswith(".mp3") or fname.endswith(".m4a") or fname.endswith(
            ".wav"):
        audio = AudioSegment.from_file(fname)
    else:
        await message.edit(
            "`This Format is Not Supported Yet` \n**Currently Supported :** `mp3, m4a and wav.`"
        )
        os.remove(fname)
        return
    sample_track = list(audio.get_array_of_samples())
    await asyncio.sleep(0.3)
    est_mean = np.mean(sample_track)
    await asyncio.sleep(0.3)
    est_std = 3 * np.std(sample_track) / (math.sqrt(2))
    await asyncio.sleep(0.3)
    bass_factor = int(round((est_std - est_mean) * 0.005))
    await asyncio.sleep(5)
    attenuate_db = 0
    filtered = audio.low_pass_filter(bass_factor)
    await asyncio.sleep(5)
    out = (audio - attenuate_db).overlay(filtered + accentuate_db)
    await asyncio.sleep(6)
    m = io.BytesIO()
    if v:
        m.name = "voice.ogg"
        out.split_to_mono()
        await message.edit("`Now Exporting...`")
        await asyncio.sleep(0.3)
        out.export(m, format="ogg", bitrate="64k", codec="libopus")
        await message.edit("`Process Completed. Uploading Now Here..`")
        await borg.send_file(
            message.to_id,
            m,
            reply_to=reply.id,
            voice_note=True,
            caption="Bass Boosted, \nDone By VirtualUserbot",
        )
        os.remove(m)
    else:
        m.name = "BassBoosted.mp3"
        await message.edit("`Now Exporting...`")
        await asyncio.sleep(0.3)
        out.export(m, format="mp3")
        await message.edit("`Process Completed. Uploading Now Here..`")
        await borg.send_file(
            message.to_id,
            m,
            reply_to=reply.id,
            attributes=[
                types.DocumentAttributeAudio(
                    duration=reply.document.attributes[0].duration,
                    title=f"BassBoost {str(accentuate_db)}lvl",
                    performer="BassBoost",
                )
            ],
            caption="Bass Boosted, \nDone By VirtualUserbot",
        )
        os.remove(m)
    await message.delete()
    os.remove(fname)
Ejemplo n.º 21
0
    async def basscmd(self, message):
        """.bass [уровень bass'а от 2 до 100 (по умолчанию 2)] <reply to audio>
		    BassBoost
		"""
        v = False
        accentuate_db = 2
        reply = await message.get_reply_message()
        if not reply:
            await message.edit("А где реплай?")
            return
        if utils.get_args_raw(message):
            ar = utils.get_args_raw(message)
            try:
                int(ar)
                if int(ar) >= 2 and int(ar) <= 100:
                    accentuate_db = int(ar)
                else:
                    await message.edit(
                        "Укажите уровень BassBoost'а от 2 до 100!")
                    return
            except Exception as exx:
                await message.edit("Неверный аргумент!<br>" + str(exx))
                return
        else:
            accentuate_db = 2
        await message.edit("Скачиваем...")
        fname = await message.client.download_media(message=reply.media)
        await message.edit("BassBoost'им...")
        if fname.endswith(".oga") or fname.endswith(".ogg"):
            v = True
            audio = AudioSegment.from_file(fname)
        elif fname.endswith(".mp3") or fname.endswith(
                ".m4a") or fname.endswith(".wav"):
            audio = AudioSegment.from_file(fname)

        else:
            await message.edit("<b>Unsupported format!</b>")
            os.remove(fname)
            return
        sample_track = list(audio.get_array_of_samples())
        est_mean = np.mean(sample_track)
        est_std = 3 * np.std(sample_track) / (math.sqrt(2))
        bass_factor = int(round((est_std - est_mean) * 0.005))
        attenuate_db = 0
        filtered = audio.low_pass_filter(bass_factor)
        out = (audio - attenuate_db).overlay(filtered + accentuate_db)
        m = io.BytesIO()

        if v:
            m.name = "voice.ogg"
            out.split_to_mono()
            await message.edit("Экспортируем...")
            out.export(m, format="ogg", bitrate="64k", codec="libopus")
            await message.edit("Отправляем...")
            await message.client.send_file(message.to_id,
                                           m,
                                           reply_to=reply.id,
                                           voice_note=True)
        else:
            m.name = "BassBoosted.mp3"
            await message.edit("Экспортируем...")
            out.export(m, format="mp3")
            await message.edit("Отправляем...")
            await message.client.send_file(
                message.to_id,
                m,
                reply_to=reply.id,
                attributes=[
                    types.DocumentAttributeAudio(
                        duration=reply.document.attributes[0].duration,
                        title=f"BassBoost {str(accentuate_db)}lvl",
                        performer="BassBoost")
                ])
        await message.delete()
        os.remove(fname)
        os.remove("none.mp3")