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

voice chats : random disconnection from the voice chat #9511

Closed
3 tasks done
TruncatedDinoSour opened this issue Jul 28, 2023 · 5 comments
Closed
3 tasks done

voice chats : random disconnection from the voice chat #9511

TruncatedDinoSour opened this issue Jul 28, 2023 · 5 comments
Labels
unconfirmed bug A bug report that needs triaging

Comments

@TruncatedDinoSour
Copy link

TruncatedDinoSour commented Jul 28, 2023

Summary

voice chats : random disconnection from the voice chat

Reproduction Steps

1, install discord.py and pynacl
2. use discord,py
3. see it crash

Minimal Reproducible Code

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""example vc thing, full example : https://ari-web.xyz/gh/124"""

import asyncio
import os
import sys
import typing
from warnings import filterwarnings as filter_warnings

import discord
import yt_dlp  # type: ignore

FFMPEG_OPTIONS: typing.Final[dict[str, str]] = {
    "before_options": "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5",
    "options": "-vn",
}
YTDL_OPTIONS: typing.Final[dict[str, typing.Any]] = {
    "format": "251/bestaudio",
    "extract_flat": "in_playlist",
    "ignoreerrors": True,
    "logtostderr": False,
    "quiet": True,
    "no_warnings": True,
    "default_search": "auto",
    "source_address": "0.0.0.0",
    "noprogress": True,
    "socket_timeout": 5,
    "socket_io_timeout": 10,
    "sleep_interval": 1,
    "max_sleep_interval": 5,
    "retries": 10,
    "fragment_retries": 10,
    "threads": 6,
    "nocheckcertificate": True,
    "geo_bypass": True,
}
YTDL: typing.Final[yt_dlp.YoutubeDL] = yt_dlp.YoutubeDL(YTDL_OPTIONS)
EMO: str = "https://www.youtube.com/watch?v=RRKJiM9Njr8"


class YTDLSource(discord.PCMVolumeTransformer):  # type: ignore
    def __init__(
        self,
        source: discord.AudioSource,
        *,
        data: dict[typing.Any, typing.Any],
        volume: float = 0.5,
    ) -> None:
        super().__init__(source, volume)  # type: ignore
        self.data: dict[typing.Any, typing.Any] = data

    @classmethod
    async def from_url(
        cls,
        url: str,
        ytdl: yt_dlp.YoutubeDL,
        *,
        loop: typing.Optional[asyncio.AbstractEventLoop] = None,
    ) -> typing.Any:
        loop = loop or asyncio.get_event_loop()

        data: typing.Any = await loop.run_in_executor(
            None, lambda: ytdl.extract_info(url, download=False)  # type: ignore
        )

        if data is None:
            return

        if "entries" in data:  # type: ignore
            data: typing.Any = data["entries"][0]

        return cls(discord.FFmpegPCMAudio(data["url"], **FFMPEG_OPTIONS), data=data)  # type: ignore


class Bot(discord.Client):
    async def on_message(self, msg: discord.message.Message) -> None:
        if msg.content != "!emo" or msg.author.bot or msg.guild is None:
            return

        if msg.guild.voice_client is not None:
            await msg.reply(content=f"alrd playing music -- {EMO}")
            return

        if msg.author.voice is None:  # type: ignore
            await msg.reply(content="join vc")
            return

        v: discord.VoiceClient

        while True:
            (v := await msg.author.voice.channel.connect()).play(await YTDLSource.from_url(EMO, YTDL))  # type: ignore

            while v.is_connected() or v.is_playing():  # type: ignore
                await asyncio.sleep(1)

            await v.disconnect()  # type: ignore


def main() -> int:
    """entry / main function"""

    if (d := os.environ.get("D")) is None:
        print("set D environment variable to ur discord bot token\n$ export D='...'", file=sys.stderr)
        return 1

    Bot(intents=discord.Intents.all()).run(d)

    return 0


if __name__ == "__main__":
    assert main.__annotations__.get("return") is int, "main() should return an integer"

    filter_warnings("error", category=Warning)
    raise SystemExit(main())

Expected Results

for it to not randomly disconnect

Actual Results

it randomly disconnects and throws this error :

Traceback (most recent call last):
  File "/home/ari/124/venv/lib/python3.9/site-packages/discord/voice_client.py", line 456, in poll_voice_ws
    await self.ws.poll_event()
  File "/home/ari/124/venv/lib/python3.9/site-packages/discord/gateway.py", line 1011, in poll_event
    raise ConnectionClosed(self.ws, shard_id=None, code=self._close_code)
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1006

Intents

discord.Intents.all()

System Information

on the server i run the bot :

Checklist

  • I have searched the open issues for duplicates.
  • I have shown the entire traceback, if possible.
  • I have removed my token from display, if visible.

Additional Context

im using the bot as a youtube music bot 👍

to use the example just add the bot with admin privs and run !emo while in a vc lol, also set the D env var to ur discord token :)

@TruncatedDinoSour TruncatedDinoSour added the unconfirmed bug A bug report that needs triaging label Jul 28, 2023
@TruncatedDinoSour TruncatedDinoSour changed the title voice messages : random disconnection from the voice chat voice chats : random disconnection from the voice chat Jul 28, 2023
@imayhaveborkedit
Copy link
Contributor

The voice connection code for the library has been rewritten. If you're still having this issue, do you mind seeing if it still happens on the latest commit?

@TruncatedDinoSour
Copy link
Author

The voice connection code for the library has been rewritten. If you're still having this issue, do you mind seeing if it still happens on the latest commit?

i assume its working but i dont even use discord anymore so i cant sry

@TruncatedDinoSour
Copy link
Author

( if anyone is able to confirm that the vc fix worked pls lmk so i could close this )

@BabyBoySnow
Copy link

I think you're okay to close this

@TruncatedDinoSour
Copy link
Author

great

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
unconfirmed bug A bug report that needs triaging
Projects
None yet
Development

No branches or pull requests

3 participants