我的机器人可以毫无问题地加入和离开语音 channel ,但我如何验证它是否已经连接到语音聊天?
我的音频服务 .cs 文件中的代码
public async Task<IAudioClient> ConnecttoVC(SocketCommandContext ctx)
{
SocketGuildUser user = ctx.User as SocketGuildUser;
IVoiceChannel chnl = user.VoiceChannel;
if(chnl == null)
{
await ctx.Channel.SendMessageAsync("Not connected!");
return null;
}
await ctx.Channel.SendMessageAsync("Joining Voice!");
return await chnl.ConnectAsync();
}
最佳答案
我知道您说过您在使用 VoiceChannel
加入和离开机器人时遇到问题CurrentUser
的属性(property),但我需要我的机器人知道它是否与执行命令的用户在同一个 channel 中。所以我采用了这种方法,到目前为止测试时没有任何问题。我想我会在这里为任何试图弄清楚如何做到这一点的人分享我的代码。我已经评论了代码,所以希望它应该很容易理解。
public async Task<IAudioClient> ConnectAudio(SocketCommandContext context)
{
SocketGuildUser user = context.User as SocketGuildUser; // Get the user who executed the command
IVoiceChannel channel = user.VoiceChannel;
bool shouldConnect = false;
if (channel == null) // Check if the user is in a channel
{
await context.Message.Channel.SendMessageAsync("Please join a voice channel first.");
} else
{
var clientUser = await context.Channel.GetUserAsync(context.Client.CurrentUser.Id); // Find the client's current user (I.e. this bot) in the channel the command was executed in
if (clientUser != null)
{
if (clientUser is IGuildUser bot) // Cast the client user so we can access the VoiceChannel property
{
if (bot.VoiceChannel == null)
{
Console.WriteLine("Bot is not in any channels");
shouldConnect = true;
}
else if (bot.VoiceChannel.Id == channel.Id)
{
Console.WriteLine($"Bot is already in requested channel: {bot.VoiceChannel.Name}");
}
else
{
Console.WriteLine($"Bot is in channel: {bot.VoiceChannel.Name}");
shouldConnect = true;
}
}
}
else
{
Console.WriteLine($"Unable to find bot in server: {context.Guild.Name}");
}
}
return (shouldConnect ? await channel.ConnectAsync() : null); // Return the IAudioClient or null if there was no need to connect
}
关于c# - 如何检查我的 Discord.Net 机器人是否已连接到语音 channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60242891/