1
1
1 22020-05-08 11:32:32
Python
1 2, 2020-05-08 11:32:32

Discord.py Saving mp3 file on hosting?

How to save a file for example mp3 on the hosting itself where my bot files are located. What if they give the bot a command to play music from youtube, he saved the file next to his own.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
s4q, 2020-05-08
@weRifiCatoR

Below is the code. Before starting, you need to install FFMpeg (not pip), youtube-dl (pip), PyNaCl (pip) on the hosting and write the command "pip install discord.py[voice]".
This is the complete code for playing music, including join and leave.

import os
from discord.utils import get
import youtube_dl

# Ржака и другие Voice Chat

# Join
@client.command()
async def join(ctx):
    global voice
    channel = ctx.message.author.voice.channel
    voice = get(client.voice_clients, guild = ctx.guild)

    if voice and voice.is_connected():
        await voice.move_to(channel)
    else:
        voice = await channel.connect()
        await ctx.send(f'Бот присоединился к каналу: {channel}')

# Leave
@client.command()
async def leave(ctx):
    channel = ctx.message.author.voice.channel
    voice = get(client.voice_clients, guild=ctx.guild)

    if voice and voice.is_connected():
        await voice.disconnect()
    else:
        voice = await channel.connect()
        await ctx.send(f'Бот отключился от канала: {channel}')

# Музло
@client.command()
async def play(ctx, url : str):
    song_there = os.path.isfile('song.mp3')

    try:
        if song_there:
            os.remove('song.mp3')
            print('[log] Старый файл удален')
    except PermissionError:
        print('[log] Не удалось удалить файл')

    await ctx.send('Пожалуйста, ожидайте. Файл обрабатывается.')

    voice = get(client.voice_clients, guild = ctx.guild)

    ydl_opts = {
        'format' : 'bestaudio/best',
        'postprocessors' : [{
            'key' : 'FFmpegExtractAudio',
            'preferredcodec' : 'mp3',
            'preferredquality' : '192'
        }],
    }

    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        print('[log] Загружаю музыку...')
        ydl.download([url])

    for file in os.listdir('./'):
        if file.endswith('.mp3'):
            name = file
            print(f'[log] Переименовываю файл: {file}')
            os.rename(file, 'song.mp3')

    voice.play(discord.FFmpegPCMAudio('song.mp3'), after = lambda e: print(f'[log] {name}, музыка закончила свое проигрывание'))
    voice.source = discord.PCMVolumeTransformer(voice.source)
    voice.source.volume = 0.07

    song_name = name.rsplit('-', 2)
    await ctx.send(f'Сейчас проигрывает музыка: {song_name[0]}')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question