【发布时间】:2018-07-28 14:06:41
【问题描述】:
我正在制作一个 Discord 机器人,我的服务器中有一个通道分配给我们的规则,我希望这个机器人自动在该通道中发送消息。是否可以检查频道是否存在?谢谢。
【问题讨论】:
-
哦,忘了说,我在 Visual Studio 中使用 C# 和 Discord.NET。
标签: c# bots discord discord.net
我正在制作一个 Discord 机器人,我的服务器中有一个通道分配给我们的规则,我希望这个机器人自动在该通道中发送消息。是否可以检查频道是否存在?谢谢。
【问题讨论】:
标签: c# bots discord discord.net
你也可以使用 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 在直接消息中。如果你愿意,你可以在你的命令中添加这个 sn-p!
if (Context.IsPrivate)
{
await ReplyAsync("Cant call command from a direct message");
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.");
}
}
}
【讨论】:
是的,你绝对可以。
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;
}
【讨论】: