LoginSignup
pythonwakaran
@pythonwakaran

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

動画再生discordbotのエラー

解決したいこと

pythonで動画再生discordbotをつくっています。
記事を投稿する機能の実装中にエラーが発生しました。
解決方法を教えて下さい。

発生している問題・エラー

2024-05-14 17:15:15 ERROR    discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "join" is not found
2024-05-14 17:18:43 ERROR    discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "list" is not found

該当するソースコード

import asyncio
import discord
import youtube_dl
from discord.ext import commands

# コンソールの使用に関するノイズを抑制
youtube_dl.utils.bug_reports_message = lambda: ''

ytdl_format_options = {
    'format': 'bestaudio/best',
    'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
    'restrictfilenames': True,
    'noplaylist': True,
    'nocheckcertificate': True,
    'ignoreerrors': False,
    'logtostderr': False,
    'quiet': True,
    'no_warnings': True,
    'default_search': 'auto',
    'source_address': '0.0.0.0'  # ipv6アドレスで問題が発生する場合があるため、ipv4にバインド
}

ffmpeg_options = {
    'options': '-vn'
}

ytdl = youtube_dl.YoutubeDL(ytdl_format_options)

class YTDLSource(discord.PCMVolumeTransformer):
    def __init__(self, source, *, data, volume=0.5):
        super().__init__(source, volume)
        self.data = data
        self.title = data.get('title')
        self.url = data.get('url')

    @classmethod
    async def from_url(cls, url, *, loop=None, stream=False):
        loop = loop or asyncio.get_event_loop()
        data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))

        if 'entries' in data:
            # プレイリストから最初のアイテムを取得
            data = data['entries'][0]

        filename = data['url'] if stream else ytdl.prepare_filename(data)
        return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)

class Music(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.queue = []

    @commands.command()
    async def join(self, ctx):
        """ボイスチャンネルに参加"""
        if ctx.author.voice:
            channel = ctx.author.voice.channel
            if ctx.voice_client is not None:
                return await ctx.voice_client.move_to(channel)
            await channel.connect()
            await ctx.send(f'{channel} に接続しました。')
        else:
            await ctx.send("ボイスチャンネルに接続されていません。")
    
    @commands.command()
    async def play(self, ctx, *, query):
        """ローカルファイルを再生"""
        source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(query))
        self.queue.append(source)
        if not ctx.voice_client.is_playing():
            self.play_next(ctx)
        await ctx.send(f'再生キューに追加: {query}')

    @commands.command()
    async def yt(self, ctx, *, url):
        """URLから再生 (ほぼ全てのyoutube_dlがサポートするもの)"""
        async with ctx.typing():
            player = await YTDLSource.from_url(url, loop=self.bot.loop)
            self.queue.append(player)
            if not ctx.voice_client.is_playing():
                self.play_next(ctx)
        await ctx.send(f'キューに追加しました: {player.title}')

    @commands.command()
    async def stream(self, ctx, *, url):
        """URLからストリーミング (ytと同じですが、事前にダウンロードしない)"""
        async with ctx.typing():
            player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True)
            self.queue.append(player)
            if not ctx.voice_client.is_playing():
                self.play_next(ctx)
        await ctx.send(f'キューに追加しました: {player.title}')

    @commands.command()
    async def volume(self, ctx, volume: int):
        """プレイヤーの音量を変更"""
        if ctx.voice_client is None:
            return await ctx.send("ボイスチャンネルに接続されていません。")
        ctx.voice_client.source.volume = volume / 100
        await ctx.send(f"音量を{volume}%に変更しました")

    @commands.command()
    async def stop(self, ctx):
        """停止してボイスチャンネルから切断"""
        self.queue.clear()
        await ctx.voice_client.disconnect()
        await ctx.send("再生を停止し、ボイスチャンネルから切断しました。")

    @commands.command()
    async def list(self, ctx):
        """使用可能なコマンドを表示"""
        commands = (
            "!join - ボイスチャンネルに参加",
            "!play <ファイルパス> - ローカルファイルを再生",
            "!yt <URL> - YouTubeなどから再生",
            "!stream <URL> - YouTubeなどからストリーム再生",
            "!volume <音量(0-100)> - 音量を変更",
            "!stop - 再生を停止して切断"
        )
        await ctx.send("使用可能なコマンド:\n" + "\n".join(commands))

    def play_next(self, ctx):
        if self.queue:
            next_player = self.queue.pop(0)
            ctx.voice_client.play(next_player, after=lambda e: self.play_next(ctx) if e is None else print(f'プレイヤーエラー: {e}'))
        else:
            asyncio.run_coroutine_threadsafe(ctx.voice_client.disconnect(), self.bot.loop)

    @play.before_invoke
    @yt.before_invoke
    @stream.before_invoke
    async def ensure_voice(self, ctx):
        if ctx.voice_client is None:
            if ctx.author.voice:
                await ctx.author.voice.channel.connect()
            else:
                await ctx.send("ボイスチャンネルに接続されていません。")
                raise commands.CommandError("ボイスチャンネルに接続されていないユーザーです。")
        elif ctx.voice_client.is_playing():
            ctx.voice_client.stop()

# 必要なすべてのIntentsを有効にする
intents = discord.Intents.default()
intents.message_content = True
intents.guilds = True
intents.voice_states = True

bot = commands.Bot(command_prefix=commands.when_mentioned_or("!"),
                   description='シンプルな音楽ボットの例',
                   intents=intents)

@bot.event
async def on_ready():
    print(f'ログインしました {bot.user} ({bot.user.id})')
    print('------')

# ここでCogを追加する
async def main():
    async with bot:
        await bot.add_cog(Music(bot))
bot.run('TOKUN')

asyncio.run(main())

最後に一言

python始めたばかりなのであまり分からないのですが、回答よろしくお願いいたします!

0

1Answer

Your answer might help someone💌