Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Spotify autoplay giving me index errors #237

Closed
Motzumoto opened this issue Aug 10, 2023 · 0 comments · Fixed by #254
Closed

Spotify autoplay giving me index errors #237

Motzumoto opened this issue Aug 10, 2023 · 0 comments · Fixed by #254

Comments

@Motzumoto
Copy link

Motzumoto commented Aug 10, 2023

future: <Task finished name='Task-27215' coro=<Player._auto_play_event() done, defined at /home/container/.local/lib/python3.10/site-packages/wavelink/player.py:186> exception=IndexError('list index out of range')>
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/wavelink/player.py", line 232, in _auto_play_event
    await self.play(track, populate=populate)
  File "/home/container/.local/lib/python3.10/site-packages/wavelink/player.py", line 579, in play
    track = await track.fulfill(player=self, cls=YouTubeTrack, populate=populate)
  File "/home/container/.local/lib/python3.10/site-packages/wavelink/ext/spotify/__init__.py", line 365, in fulfill
    return tracks[0]
IndexError: list index out of range

wavelink version: 2.6.2
Lavalink version: 3.7.8

Replication:

    async def get_lofi_channels(self, refresh: bool = False) -> dict[int, discord.VoiceChannel | discord.StageChannel]:
        """Fetch all lofi channels.

        Parameters
        ----------
        refresh: bool
            Whether to refresh the cache or not. Defaults to False.
        """
        if not self.bot.is_ready():
            await self.bot.wait_until_ready()

        if not refresh and self.lofi_channels:
            return self.lofi_channels

        for channel in self.bot.get_all_channels():
            if not isinstance(channel, (discord.VoiceChannel, discord.StageChannel)):
                continue

            if channel.guild.id in self.lofi_channels:
                continue

            if channel.name.lower() == self.LOFI_CHANNEL_NAME.lower():
                self.lofi_channels[channel.guild.id] = channel

        return self.lofi_channels

class Akiko(commands.AutoShardedBot):
    session: AkikoHTTPClient
    lunar_client: lunarapi.Client
    pool: asyncpg.Pool
    user: discord.ClientUser
    # dynamic icons for the achievement & challenge command
    minecraft_icons: dict[str, str]

    def __init__(self) -> None:
        # intents
        intents = discord.Intents.default()
        intents.members = True
        intents.message_content = True

        super().__init__(
            command_prefix=commands.when_mentioned_or(self.config.get("PREFIX", "a!")),
            activity=discord.CustomActivity(
                name="Custom Status",  # leave this like this
                state="¯\_(ツ)_/¯",  # edit this
            ),
            status=discord.Status.online,
            intents=intents,
            allowed_mentions=discord.AllowedMentions(roles=False, users=True, everyone=False, replied_user=False),
            strip_after_prefix=True,
            case_insensitive=True,
            help_command=None,
            reconnect=True,
            chunk_guilds_at_startup=True,
            max_messages=5000,
            owner_ids=self.get_owner_ids_from_config(),
        )
    async def update_progress(self, current, total):
        progress = Progress()
        task = progress.add_task("[cyan]Connecting to Lo-Fi channels...", total=total)
        while not progress.finished:
            progress.update(task, completed=current)
            await asyncio.sleep(1)

    # do_actual_music
    async def do_actual_music(self, channel: discord.VoiceChannel | discord.StageChannel):
        vc: wavelink.Player
        if not (vc := channel.guild.voice_client):  # type: ignore
            try:
                vc = await channel.connect(cls=wavelink.Player, self_deaf=True)  # type: ignore
            except Exception as e:
                logging.error(
                    f"Couldn't start 24/7 Lo-Fi in Channel ID: {channel.id} and Guild ID: {channel.guild.id} | {e}"
                )
                return False

        if vc.is_paused():
            await vc.disconnect()
            return

        vc.autoplay = True
        if isinstance(channel, discord.StageChannel):
            await channel.guild.me.request_to_speak()

        urls = random.choice(
            [
                "https://open.spotify.com/playlist/6vkLWP86PIBnFlmXhEbXtO?si=54a77a2a4dc64420",
                "https://open.spotify.com/playlist/0vvXsWCC9xrXsKd4FyS8kM?si=c25ca384790c4d63",
                "https://open.spotify.com/playlist/66ObUW8grgqgWyFemzkWqm?si=dfa690e5e3a544e4",
                "https://open.spotify.com/playlist/6WtkTjuGDFHXmfSM5jbhrZ?si=e790601b5d2f4ac1",
                "https://open.spotify.com/album/1jaHDcP2znVHonXWNr729X?si=FdsIn4PbT6e-sy7TMIsLkA",
            ]
        )

        spotify.decode_url(urls)
        track_count = 0
        async for track in spotify.SpotifyTrack.iterator(query=urls):
            track_count += 1
            await vc.queue.put_wait(track)

        vc.queue.shuffle()
        await vc.play(vc.queue.get(), populate=True)  # type: ignore

    # do_music
    async def do_music(self):
        if not self.is_ready():
            await self.wait_until_ready()

        music_cog: Music = self.get_cog("music")  # type: ignore
        if not music_cog:
            await asyncio.sleep(5)
            await self.do_music()
            return

        channels = await music_cog.get_lofi_channels(True)
        if channels:
            logging.info(f"Found {len(channels)} {music_cog.LOFI_CHANNEL_NAME} channels.")
            await asyncio.sleep(5)

        with Progress() as progress:
            task = progress.add_task("[cyan]Connecting to Lo-Fi channels...", total=len(channels))

            started = 0
            failed = 0
            for guild_id, channel in channels.items():
                res = await self.do_actual_music(channel)
                if res is False:
                    failed += 1
                else:
                    started += 1
                    # logging.info(
                    #     f"Started {music_cog.LOFI_CHANNEL_NAME} in Channel ID: {channel.id} and Guild ID: {guild_id}"
                    # )
                progress.update(task, advance=1)
                await asyncio.sleep(0.2)

        logging.info(f"Started {music_cog.LOFI_CHANNEL_NAME} in {started}/{len(channels)} channels. {failed} failed.")

    async def setup_hook(self):
            sc = spotify.SpotifyClient(
                client_id=f"{self.config.get('SPOTIFY_CLIENT_ID')}",
                client_secret=f"{self.config.get('SPOTIFY_CLIENT_SECRET')}",
            )

            self.nodes = [
                   nodes
            ]

            await wavelink.NodePool.connect(client=self, nodes=self.nodes, spotify=sc)
@EvieePy EvieePy linked a pull request Nov 27, 2023 that will close this issue
8 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant