C# 是否可以检查通道是否存在?

C# 是否可以检查通道是否存在?,c#,bots,discord,discord.net,C#,Bots,Discord,Discord.net,我正在制作一个Discord机器人,我的服务器中有一个分配给我们规则的通道,我希望这个机器人在该通道中自动发送消息。是否可以检查通道是否存在?谢谢。是的,你当然可以 if (message.Content.StartsWith("!check")) { SocketGuildChannel currentChannel = message.Channel as SocketGuildChannel; SocketGuild guild = currentChannel.Guild

我正在制作一个Discord机器人,我的服务器中有一个分配给我们规则的通道,我希望这个机器人在该通道中自动发送消息。是否可以检查通道是否存在?谢谢。

是的,你当然可以

if (message.Content.StartsWith("!check"))
{
    SocketGuildChannel currentChannel = message.Channel as SocketGuildChannel;
    SocketGuild guild = currentChannel.Guild;

    foreach (SocketGuildChannel ch in guild.Channels)
    {
        if (ch.GetType() == typeof(SocketTextChannel)) //Checking text channels
        {
            if (ch.Name.Equals("rules"))
            {
                ISocketMessageChannel channel = (ISocketMessageChannel)ch; //Casting so we can send a message
                await channel.SendMessageAsync("This is the rules channel.");
                return;
            }
        }
    }
    await message.Channel.SendMessageAsync("Could not find the rules channel.");
    return;
}

假设您使用的是Discord.Net 1.0.2

如果要将其作为命令使用,请执行以下操作:

    [Command("check")]
    public async Task CheckChannel(string channel)
    {
        foreach (SocketGuildChannel chan in Context.Guild.Channels)
        {
            if (channel == chan.Name)
            {
                // It exists!
                ITextChannel ch = chan as ITextChannel;
                await ch.SendMessageAsync("This is the rules channel!");
            }
            else
            {
                // It doesn't exist!
                await ReplyAsync($"No channel named {channel} was found.");
            }
        }
    }

你也可以使用Linq

[Command("check")]
public async Task CheckChannel(string channelName)
{
    //Makes the channel name NOT case sensitive
    var channel = Context.Guild?.Channels.FirstOrDefault(c => string.Equals(c.Name, channelName, StringComparison.OrdinalIgnoreCase));
    if (channel != null)
    {
        ITextChannel ch = channel as ITextChannel;
        await ch.SendMessageAsync("This is the rules channel!");
    }
    else
    {
        // It doesn't exist!
        await ReplyAsync($"No channel named {channel} was found.");
    }
}
还有一个警告,这将在DM中失败,因为直接消息中的Context.Guild==null。如果需要,可以在命令中添加此代码段

if (Context.IsPrivate)
{
    await ReplyAsync("Cant call command from a direct message");
    return;
}

哦,忘了提一下,我正在Visual Studio中使用C#with Discord.NET。