Discord.NET C# 1.0.2 如何向特定频道发送消息

Discord.NET C# 1.0.2 How to send messages to specific channels

我正在制作一个可以在特定事件发生时发布消息的机器人。有谁知道如何将消息输出到特定的文本频道?

public async Task Announce() // 1
{
    DiscordSocketClient _client = new DiscordSocketClient(); // 2
    ulong id = 123456789012345678; // 3
    var chnl = _client.GetChannel(id) as IMessageChannel; // 4
    await chnl.SendMessageAsync("Announcement!"); // 5
}

[1] 一个标准的异步任务(您可以选择只在您自己的方法中包含大括号内的代码)。
[2] 创建 Discord 客户端实例。
[3] 随机顺序频道ID(替换为您自己的频道ID)。
[4] 创建 Discord Channel 的实例作为 IMessageChannel 而不是 SocketChannel。
[5]正在发送消息到文字频道

public async Task TalkInChannel() //1
{
   DiscordSocketClient _client = new DiscordSocketClient(); //2
   var channel = _client.GetChannel(Channel ID) as SocketGuildChannel; //3
   await channel.SendMessageAsync("Message Here!"); //4
}

You can also use embeds by creating an Embed then replacing "Message Here!" with """, false EmbedName.Build()"

正如@slothgod 所说

    public async Task Announce() // 1
{
    DiscordSocketClient _client = new DiscordSocketClient(); // 2
    ulong id = 123456789012345678; // 3
    var chnl = _client.GetChannel(id) as IMessageChannel; // 4
    await chnl.SendMessageAsync("Announcement!"); // 5
}

当您只想在一个频道中发送回复 pre-fixed 消息(如上面代码中的 "Announcement!" )时,上述代码有效。您可以在 "ulong id = ....your channel id here....;"

中更改频道

但如果您想将自定义消息发送到自定义频道,请尝试此代码。

    public async Task _say(IMessageChannel chh,[Remainder]string repeat)
{
    await Context.Message.DeleteAsync();
    await chh.SendMessageAsync(repeat); // 5
}

要使用我发送的代码,只需键入此命令:"Your Bot Prefix and Command" "Channel name or ID" "Message you want to send"

示例:DFH.say TestChannel Welcome to this channel

我所做的是: 使用依赖注入让登录的客户端在我想发送消息的任何地方都可用,在我的例子中,它是一个模块。

public XModule(DiscordSocketClient client){
 this.client = client;
}

然后正如@slothgod 所说:

 private async Task Announce(ExampleType object) //1
        {
            ulong id = object.ChannelId; // 3
            var chnl = client.GetChannel(id) as IMessageChannel; // 4
            await chnl.SendMessageAsync("Message!"); // 5
        }