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

时间:2018-02-18 01:13:22

标签: c# bots discord discord.net

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

3 个答案:

答案 0 :(得分:0)

是的,你绝对可以。

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;
}

答案 1 :(得分:0)

假设您使用的是Discord.Net 1.0.2

如果您想将其作为命令:

Route::get('foo', 'Photos\AdminController@method');

答案 2 :(得分:0)

你也可以使用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;
}
相关问题