c# - 如何检查我的 Discord.Net 机器人是否已连接到语音通道
问题描述
我的机器人可以毫无问题地加入和离开语音频道,但我如何验证它是否已经连接到语音聊天?
我的音频服务 .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
,但我需要我的机器人知道它是否与执行命令的用户在同一个频道中。所以我采用了这种方法,到目前为止测试时没有任何问题。我想我会在这里为任何试图弄清楚如何做到这一点的人分享我的代码。我已经评论了代码,所以希望它应该很容易理解。
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
}
推荐阅读
- obd-ii - 如何使用其物理地址与特定 ECU 通信
- node.js - 为什么 viber-bot(Nodejs) 在 Nginx 后面的 Docker 中运行时无法注册 webhook?
- javascript - 使用 fetch 的 POST 请求不起作用
- c# - Apache Ignite.NET 服务中的依赖注入
- android - 应用程序仅在连接到笔记本电脑的设备上运行
- arrays - 如何在bash中嵌套变量和循环子变量
- python - 在 Python 中为 OpenCV BoundryBox 设置自定义 RoI
- ruby-on-rails - 在 Rails 中控制公共文件响应代码
- c# - 与 ef 对话和可定制的 asp.net 类库
- google-app-engine - AppEngine 日志不接受上下文