[英]Is it possible to check if a channel exists?
I'm making a Discord bot and there's a channel in my server allocated to our rules and I want this bot to automatically send a message in that channel. 我正在制作Discord机器人,并且服务器中有一个分配给我们规则的通道,我希望该机器人在该通道中自动发送消息。 Is it possible to check if the channel exists?
是否可以检查频道是否存在? Thanks.
谢谢。
Yes you definitely can. 是的,您绝对可以。
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;
}
Assuming you are using Discord.Net 1.0.2 假设您正在使用Discord.Net 1.0.2
If you want to have it as a command: 如果要使用它作为命令:
[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.");
}
}
}
You could also use Linq! 您也可以使用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.");
}
}
Also a warning, This will fail in a DM because Context.Guild == null in a direct message. 也是警告,这将在DM中失败,因为直接消息中的Context.Guild == null。 If you so desired, you can add this snippet inside your command!
如果需要,可以在命令中添加此代码段!
if (Context.IsPrivate)
{
await ReplyAsync("Cant call command from a direct message");
return;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.