@Anu6is 提示是正确的方法。事实上,GetVoiceChannel() 方法做得很好。我发布了我知道必须帮助有同样问题的人的代码!
private DiscordSocketClient _client;
private CommandHandler _handler;
private SocketGuild _guild;
private SocketVoiceChannel _voiceChannel;
这些是 discord 机器人的关键组件。 _guild 和 _voiceChannel 在按钮按下调用的方法中被初始化。 commandHandler 是我自己的类,不由 discord.Net 提供,但无论如何都不需要连接到语音通道(在我的情况下,如果您想通过不和谐的命令进行连接,例如“!connect”,那就是!) .连接/断开的方法如下:
public async Task ConnectVoiceAsync()
{
_guild = _client.GetGuild(xyz);
_voiceChannel = _guild.GetVoiceChannel(xyz);
var connection = await _voiceChannel.ConnectAsync();
debugger.AddLogLine(0, "\n...\nConnection succeeded");
}
public async Task ConnectVoiceAsync(ulong guildId, ulong channelId)
{
try
{
_guild = _client.GetGuild(guildId);
_voiceChannel = _guild.GetVoiceChannel(channelId);
var connection = await _voiceChannel.ConnectAsync();
debugger.AddLogLine(0, "\r\n...\r\n>>>Connection succeeded");
}catch(Exception e)
{
debugger.AddLogLine(1, e.ToString());
}
}
public async Task DisconnectVoiceAsync()
{
try
{
if(_voiceChannel != null)
{
await _voiceChannel.DisconnectAsync();
debugger.AddLogLine(0, "Bot Disconnected");
}
else
{
debugger.AddLogLine(1, "No Connection established!");
}
}
catch(Exception e)
{
debugger.AddLogLine(1, e.ToString());
}
}
我有两个版本的连接方法,因为通过选中表单中的复选框,可以连接到预设的语音通道。如果您不希望通过交互式 UI 传递公会和服务器 ID,您可以简单地在 ypur 程序中“硬编码”这些 ID 并使用第一种方法。如果您希望用户能够灵活地连接到不同的服务器,您将使用带两个参数的重载方法。
如果你像我一样做,你在调用异步方法时必须小心。这是我在表单后面的代码中使用的方法!
private async void button4_Click(object sender, EventArgs e)
{
if (channel)
{
debugger.AddLogLine(0, "Awaiting Connection to VoiceChannel (Pos Kanal)!");
await connectionManager.ConnectVoiceAsync();
}
else if(!channel && textBoxChanneld.Text == string.Empty && TextBoxGuildId.Text == string.Empty)
{
panelAdvancedConnect.Size = defaultSizeAdvanced;
} else
{
ulong id1 = Convert.ToUInt64(TextBoxGuildId.Text);
ulong id2 = Convert.ToUInt64(textBoxChanneld.Text);
debugger.AddLogLine(0, "Trying to connect to ''" + id1.ToString() + " " + id2.ToString());
await connectionManager.ConnectVoiceAsync(id1, id2);
}
}
这里的关键是,您使用async void 声明您的按钮方法。使用async Task 会导致很多错误。 Debugger 是一个自己的类,它向应用程序添加一个小控制台窗口。
不同的面板,例如“连接到语音聊天”和用于 ID 的文本框“弹出”,以保持设计纤巧。