pycord icon indicating copy to clipboard operation
pycord copied to clipboard

refactor(voice): Strict type checking in voice internals & DAVE Support (rec)

Open Paillat-dev opened this issue 8 months ago • 4 comments

Summary

Information

  • [ ] This PR fixes an issue.
  • [ ] This PR adds something new (e.g. new method or parameters).
  • [ ] This PR is a breaking change (e.g. methods or parameters removed/renamed).
  • [ ] This PR is not a code change (e.g. documentation, README, typehinting, examples, ...).

Checklist

  • [ ] I have searched the open pull requests for duplicates.
  • [ ] If code changes were made then they have been tested.
    • [ ] I have updated the documentation to reflect the changes.
  • [ ] If type: ignore comments were used, a comment is also left explaining why.
  • [ ] I have updated the changelog to include these changes.
  • [ ] AI Usage has been disclosed.
    • [ ] If AI has been used, I understand fully what the code does

Paillat-dev avatar Mar 19 '26 10:03 Paillat-dev

Thanks for opening this pull request! Please make sure you have read the Contributing Guidelines and Code of Conduct.

This pull request can be checked-out with:

git fetch origin pull/3159/head:pr-3159
git checkout pr-3159

This pull request can be installed with:

pip install git+https://github.com/Pycord-Development/pycord@refs/pull/3159/head

pycord-app[bot] avatar Mar 19 '26 10:03 pycord-app[bot]

Hi, I can't seem to get the recording properly stop and save the audio files. It just seems to be stuck somewhere never finishing the recording.

Logging in and connecting works. Recording starts, when typed !stop, Stopping recording for ... is outputed, but audio is not processed properly and seems to be hanging.

import discord
from dotenv import load_dotenv
import os
import json
import time
from discord.ext import commands
# import asyncio


load_dotenv()
RECORDINGS_DIR = "recordings"   
os.makedirs(RECORDINGS_DIR, exist_ok=True)

recording_start = {}
connections = {}

intents = discord.Intents.default()
intents.message_content = True
intents.voice_states = True

bot = commands.Bot(command_prefix="!", intents=intents)

async def finished_callback(sink: discord.sinks.WaveSink, ctx: commands.Context):
    """Called automatically when stop_recording() is called."""

    for user_id, audio in sink.audio_data.items():
        print(f"Processing audio for user {user_id} with attributes: {dir(audio)}")
        filename = f"{RECORDINGS_DIR}/{user_id}.wav"
        with open(filename, "wb") as f:
            f.write(audio.file.read())
        print(f"Saved {filename}")

    await ctx.send(f"Saved {len(sink.audio_data)} audio track(s).")

@bot.event
async def on_ready():
    print(f'We have logged in as {bot.user}')   
     
@bot.command()
async def record(ctx):
    if not ctx.author.voice:
        await ctx.send("You are not connected to a voice channel.")
        return
    
    if ctx.guild.voice_client:
        await ctx.guild.voice_client.disconnect()
        
    print(f"Connecting to {ctx.author.voice.channel}")
    vc = await ctx.author.voice.channel.connect()
    print(f"Is connected: {vc.is_connected()}")

    connections[ctx.guild.id] = (vc, sink := discord.sinks.WaveSink())
    recording_start[ctx.guild.id] = time.time()
    print(f"Connected: {vc}")
    vc.start_recording(
        sink,
        finished_callback
    )
    print("Recording started")
    await ctx.send("Recording started! Type `!stop` to stop.")
    
@bot.command()
async def stop(ctx: commands.Context):
    if ctx.guild.id not in connections:
        await ctx.send("Not recording.")
        return
    vc, sink = connections.pop(ctx.guild.id)
    print(f"Stopping recording for {vc}")
    vc.stop_recording()  
    await ctx.send("Stopping recording")
    
@bot.command()
async def check(ctx):
    if ctx.guild.id not in connections:
        await ctx.send("Not recording")
        return
    vc, sink = connections[ctx.guild.id]
    print(f"audio_data: {sink.audio_data}")
    print(f"is_recording: {vc.is_recording()}")
    await ctx.send(f"audio_data keys: {list(sink.audio_data.keys())}")
        
@bot.command()
async def disconnect(ctx: commands.Context):
    vc = ctx.guild.voice_client
    if vc:
        await vc.disconnect(force=True)
        await ctx.send("Disconnected.")
    else:
        await ctx.send("No voice client.")
        
bot.run(os.getenv('DISCORD_TOKEN'))


luc-rap avatar Apr 03 '26 23:04 luc-rap

thank you for this change <3

can't wait for it to get in

brianmatzelle avatar Apr 15 '26 05:04 brianmatzelle

I can confirm this works after building a bot on top of this PR!

DigiDuncan avatar Jun 15 '26 18:06 DigiDuncan

Claude thought this feedback would be useful:


Confirming this fixes voice reception for a recording/transcription bot. 🎉

Built against this PR (05cf65f) with davey 0.1.6 on Python 3.12.13, in a guild where DAVE is enforced (negotiated proto v1).

Before (on master, incl. the commit this branch forked from): every received packet hit opus_decode → INFO discord.opus "corrupted stream" / error has happened in opus_decode, so saved audio was pure noise and transcripts were nonsense. The root cause was exactly as you describe — Opus decoding was happening before the DAVE layer was decrypted.

After this PR: it just works.

  • Clean per-user PCM out of a custom Sink; recorded WAVs play back correctly and faster-whisper transcripts are accurate.
  • Per-user attribution is correct (SSRC→user_id mapping resolves properly).
  • No more corrupted stream / opus_decode errors in a live session.

Since Discord's non-stage E2EE enforcement, this is the difference between the bot being completely dead (close code 4017 if you advertise max_dave_protocol_version=0) and fully functional. Thanks for the work on this — would love to see it land.

(Minor, non-blocking observation: still see periodic INFO discord.voice.receive.reader Received unexpected rtcp packet type=200, SenderReportPacket — looks cosmetic, decoding is unaffected.)

cinderblock avatar Jul 20 '26 21:07 cinderblock

FWIW, I've been running this PR for a few weeks now on both Discord iOS (cellular and WiFi) and macOS clients, and it's been rock solid. No issues.

Setup:

  • Python 3.14.4, macOS 26 (Tahoe) and 27.0 (Golden Gate), both arm64
  • Custom Sink subclass (discord.sinks.Sink subclass overriding write()), is_opus()=False, consuming VoiceData.pcm (48kHz stereo s16le) with per-user buffering + webrtcvad end-of-utterance detection feeding WAV to STT

General testing has been multi-user voice channels for up to 30 minutes with bot joining/leaving/reattaching mid-session.

Great job!

digitaldevotion avatar Jul 23 '26 15:07 digitaldevotion