Исходник Музыкальный бот ютуба на Python в Discord

Начинающий
Статус
Оффлайн
Регистрация
16 Фев 2023
Сообщения
29
Реакции[?]
3
Поинты[?]
1K
в cmd пишем pip install discord pytube youtube-search

Пожалуйста, авторизуйтесь для просмотра ссылки.
качаем и засовываем ffmpeg.exe в папку с кодом

код:
import discord
from discord.ext import commands
from discord import app_commands
from pytube import YouTube
from youtube_search import YoutubeSearch

bot = commands.Bot(command_prefix="a!", intents=discord.Intents.all())
bot.remove_command("help")

@bot.event
async def on_ready():
    await bot.change_presence(activity=discord.Game(name="/play /stop"))
    print("Bot запущен.")
    try:
        synced = await bot.tree.sync()
        print(f"Сихронизировано {len(synced)} команд")
    except Exception as e:
        print(f"Ошибка синхронизации команд: {e}")

@bot.tree.command(name="play", description="play youtube")
@app_commands.describe(запрос="ссылка на ют")
async def play_yt(interaction: discord.Interaction, запрос: str):
    voice_state = interaction.guild.get_member(interaction.user.id).voice
    if voice_state == None or voice_state.channel == None:
        await interaction.followup.send("Вы должны быть в войсе.", ephemeral=True)
        return
    await interaction.response.defer()

    voice_client = discord.utils.get(bot.voice_clients, guild=interaction.guild)
    if voice_client and voice_client.is_connected():
        await voice_client.disconnect()
    
    try:
        voice_client = await voice_state.channel.connect()
        if запрос.startswith("http"):
            video_url = запрос
        else:
            results = YoutubeSearch(запрос, max_results=1).to_dict()
            if not results:
                await interaction.followup.send("По вашему запросу ничего не найдено.")
                return
            video_url = "https://www.youtube.com" + results[0]['url_suffix']
        yt = YouTube(video_url)
        stream = yt.streams.filter(only_audio=True).first()
        ffmpeg_options = {
            'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
            'options': '-vn -af aresample=async=1'
        }
        embed = discord.Embed(title=yt.title, description=f"Длительность: {yt.length // 60}:{yt.length % 60:02d}")
        embed.set_footer(text=f"Добавлено {interaction.user.display_name}")
        voice_client.play(discord.FFmpegPCMAudio(stream.url, **ffmpeg_options))
        await interaction.followup.send(embed=embed)
    except Exception as e:
        await interaction.followup.send(f"Ошибка: {e}", ephemeral=True)

@bot.tree.command(name="stop", description="останавливает трек и выходит с войса")
async def stopandquit(interaction: discord.Interaction):
    voice_state = interaction.guild.get_member(interaction.user.id).voice
    if voice_state is None or voice_state.channel is None:
        await interaction.response.send_message("Вы должны быть в голосовом канале, чтобы использовать эту команду.")
        return
    await interaction.response.defer()

    try:
        voice_client = discord.utils.get(bot.voice_clients, guild=interaction.guild)
        if voice_client and voice_client.is_playing():
            voice_client.stop()
            await interaction.followup.send("Воспроизведение музыки остановлено.", ephemeral=True)
            await voice_client.disconnect()
        else:
            await interaction.followup.send("В данный момент ничего не воспроизводится.", ephemeral=True)
            await voice_client.disconnect()
    except Exception as e:
        await interaction.followup.send(f'Произошла ошибка: {e}', ephemeral=True)

bot.run("токен")
 
Эксперт
Статус
Оффлайн
Регистрация
29 Мар 2021
Сообщения
1,500
Реакции[?]
560
Поинты[?]
104K
в cmd пишем pip install discord pytube youtube-search

Пожалуйста, авторизуйтесь для просмотра ссылки.
качаем и засовываем ffmpeg.exe в папку с кодом

код:
import discord
from discord.ext import commands
from discord import app_commands
from pytube import YouTube
from youtube_search import YoutubeSearch

bot = commands.Bot(command_prefix="a!", intents=discord.Intents.all())
bot.remove_command("help")

@bot.event
async def on_ready():
    await bot.change_presence(activity=discord.Game(name="/play /stop"))
    print("Bot запущен.")
    try:
        synced = await bot.tree.sync()
        print(f"Сихронизировано {len(synced)} команд")
    except Exception as e:
        print(f"Ошибка синхронизации команд: {e}")

@bot.tree.command(name="play", description="play youtube")
@app_commands.describe(запрос="ссылка на ют")
async def play_yt(interaction: discord.Interaction, запрос: str):
    voice_state = interaction.guild.get_member(interaction.user.id).voice
    if voice_state == None or voice_state.channel == None:
        await interaction.followup.send("Вы должны быть в войсе.", ephemeral=True)
        return
    await interaction.response.defer()

    voice_client = discord.utils.get(bot.voice_clients, guild=interaction.guild)
    if voice_client and voice_client.is_connected():
        await voice_client.disconnect()
   
    try:
        voice_client = await voice_state.channel.connect()
        if запрос.startswith("http"):
            video_url = запрос
        else:
            results = YoutubeSearch(запрос, max_results=1).to_dict()
            if not results:
                await interaction.followup.send("По вашему запросу ничего не найдено.")
                return
            video_url = "https://www.youtube.com" + results[0]['url_suffix']
        yt = YouTube(video_url)
        stream = yt.streams.filter(only_audio=True).first()
        ffmpeg_options = {
            'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
            'options': '-vn -af aresample=async=1'
        }
        embed = discord.Embed(title=yt.title, description=f"Длительность: {yt.length // 60}:{yt.length % 60:02d}")
        embed.set_footer(text=f"Добавлено {interaction.user.display_name}")
        voice_client.play(discord.FFmpegPCMAudio(stream.url, **ffmpeg_options))
        await interaction.followup.send(embed=embed)
    except Exception as e:
        await interaction.followup.send(f"Ошибка: {e}", ephemeral=True)

@bot.tree.command(name="stop", description="останавливает трек и выходит с войса")
async def stopandquit(interaction: discord.Interaction):
    voice_state = interaction.guild.get_member(interaction.user.id).voice
    if voice_state is None or voice_state.channel is None:
        await interaction.response.send_message("Вы должны быть в голосовом канале, чтобы использовать эту команду.")
        return
    await interaction.response.defer()

    try:
        voice_client = discord.utils.get(bot.voice_clients, guild=interaction.guild)
        if voice_client and voice_client.is_playing():
            voice_client.stop()
            await interaction.followup.send("Воспроизведение музыки остановлено.", ephemeral=True)
            await voice_client.disconnect()
        else:
            await interaction.followup.send("В данный момент ничего не воспроизводится.", ephemeral=True)
            await voice_client.disconnect()
    except Exception as e:
        await interaction.followup.send(f'Произошла ошибка: {e}', ephemeral=True)

bot.run("токен")
хранить токен в текстовом формате кринжатура и позор, environ или (лучше) абузить dotenv
 
Пользователь
Статус
Оффлайн
Регистрация
28 Фев 2019
Сообщения
640
Реакции[?]
134
Поинты[?]
21K
кринж а не мюзик бот лучше использовать любую другую дискорд библиотеку + лавалинк
 
Сверху Снизу