1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
|
# This file is part of Senator Sperma
# Licensed under the GPL-3.0 License
# Copyright (C) 2026 Salmonik @ salmonik@tuta.io
# https://codeberg.org/salmonik/senator-sperma
import discord
from discord.ext import commands
import logging
import asyncio
from dataclasses import dataclass, field
from typing import Any
logger = logging.getLogger(__name__)
_voice_managers: dict[int, "VoiceManager"] = {}
def get_voice_manager(bot) -> "VoiceManager":
"""Get or create VoiceManager for a specific bot instance."""
bot_id = bot.user.id if bot.user else id(bot)
if bot_id not in _voice_managers:
_voice_managers[bot_id] = VoiceManager(bot)
return _voice_managers[bot_id]
@dataclass
class VoiceManager:
bot: Any # type: ignore[no-any-import]
_voice_lock: asyncio.Lock = field(default_factory=asyncio.Lock, init=False)
async def join_channel(self, channel):
"""Join a voice channel by channel object."""
async with self._voice_lock:
guild = channel.guild
voice_client = discord.utils.get(self.bot.voice_clients, guild=guild)
if voice_client and voice_client.is_connected():
if voice_client.channel == channel:
logger.info(f"Already connected to {channel}")
return voice_client
try:
await voice_client.move_to(channel)
logger.info(f"Moved to voice channel: {channel}")
return voice_client
except Exception as e:
logger.error(f"Failed to move voice client: {e}")
try:
await voice_client.disconnect()
except Exception:
pass
await asyncio.sleep(0.3)
try:
voice_client = await channel.connect(timeout=30.0, reconnect=False)
logger.info(f"Connected to voice channel: {channel}")
return voice_client
except Exception as e:
logger.error(f"Failed to connect to voice channel: {e}")
return None
async def join_by_channel_id(self, channel_id):
"""Join a voice channel by channel ID."""
channel = self.bot.get_channel(channel_id)
if not channel:
logger.error(f"Channel {channel_id} not found")
return None
if not isinstance(channel, discord.VoiceChannel):
logger.error(f"Channel {channel_id} is not a voice channel")
return None
return await self.join_channel(channel)
async def get_voice_client(self, guild):
"""Get existing voice client for a guild."""
return discord.utils.get(self.bot.voice_clients, guild=guild)
async def get_voice_status(self, guild):
"""Get voice client status including connection and playback state.
Returns:
tuple: (voice_client, is_connected, is_playing) or (None, False, False) if no client
"""
voice_client = await self.get_voice_client(guild)
if voice_client is None:
return None, False, False
is_connected = voice_client.is_connected()
is_playing = voice_client.is_playing() if is_connected else False
return voice_client, is_connected, is_playing
async def play_audio(self, channel, audio_source, volume=1.0):
"""Play audio in a voice channel."""
voice_client = await self.join_channel(channel)
if not voice_client:
return False
if volume != 1.0:
audio_source = discord.PCMVolumeTransformer(audio_source)
audio_source.volume = volume
try:
voice_client.play(audio_source)
while voice_client.is_playing():
await asyncio.sleep(0.1)
return True
except Exception as e:
logger.error(f"Error playing audio: {e}")
return False
async def stop(self, guild):
"""Stop playing and disconnect from voice."""
voice_client = await self.get_voice_client(guild)
if voice_client:
voice_client.stop()
await voice_client.disconnect()
logger.info(f"Stopped and disconnected from guild {guild}")
class Voice(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._voice_lock = asyncio.Lock()
async def _validate_user_voice_state(self, ctx):
if not ctx.author.voice or not ctx.author.voice.channel:
await ctx.send("You need to be in a voice channel first!")
return False
return True
async def _create_voice_client(self, ctx):
async with self._voice_lock:
try:
await asyncio.sleep(0.5)
voice_client = await ctx.author.voice.channel.connect(timeout=30.0, reconnect=False)
logger.info(f"Connected to voice channel: {ctx.author.voice.channel}")
return voice_client
except asyncio.TimeoutError:
await ctx.send("Connection to voice channel timed out.")
return None
except discord.ClientException as e:
logger.error(f"Failed to connect to voice channel: {e}")
await ctx.send("Failed to connect to voice channel. Please try again.", ephemeral=True)
return None
async def _move_voice_client(self, voice_client, ctx):
try:
await voice_client.move_to(ctx.author.voice.channel)
logger.info(f"Moved to voice channel: {ctx.author.voice.channel}")
return voice_client
except asyncio.TimeoutError:
await ctx.send("Connection to voice channel timed out.")
return None
except discord.ClientException as e:
logger.error(f"Failed to move to voice channel: {e}")
await ctx.send("Failed to move to your voice channel. Please try again.", ephemeral=True)
return None
async def _verify_connection(self, voice_client):
if not voice_client.is_connected():
try:
await voice_client.connect(reconnect=False, timeout=10.0)
return voice_client
except Exception as e:
logger.error(f"Failed to reconnect to voice: {e}")
return None
return voice_client
async def ensure_voice_client(self, ctx):
if not await self._validate_user_voice_state(ctx):
return None
voice_client = discord.utils.get(self.bot.voice_clients, guild=ctx.guild)
if voice_client and not voice_client.is_connected():
try:
await voice_client.disconnect()
except Exception:
pass
voice_client = None
if not voice_client or not voice_client.is_connected():
if not await self._validate_user_voice_state(ctx):
return None
return await self._create_voice_client(ctx)
if voice_client.channel != ctx.author.voice.channel:
return await self._move_voice_client(voice_client, ctx)
return await self._verify_connection(voice_client)
async def connect(self, ctx):
voice_client = await self.ensure_voice_client(ctx)
if not voice_client:
return None
return voice_client
def setup(bot):
bot.add_cog(Voice(bot))
|