【问题标题】:How to send a message by guild ID and channel ID in Discord.NET如何在 Discord.NET 中通过公会 ID 和频道 ID 发送消息
【发布时间】:2021-09-22 05:27:13
【问题描述】:

美好的一天,我被我的不和谐机器人困住了。我正在使用 Discord.NET 库,我的任务是在直接消息中获取命令并将其发送到特定不和谐公会的特定频道。我知道频道 ID 和公会 ID,但我不知道如何使用它们。

[Command("resource")]
public async Task SendResource(string url = null, [Remainder]string description = null)
{
    if (url == null)
    {
        await ReplyAsync("...");
        return;
    }
    if (description == null)
    {
        await ReplyAsync("...");
        return;
    }
    string text = $"**New resource:** {url}\n**Description:** {description}";
    await Context.Guild.GetTextChannel(863427166662557696).SendMessageAsync(text);
}
await Context.Guild.GetTextChannel(863427166662557696).SendMessageAsync(text);

会在同一个公会找到频道,但如果命令是在直接消息中执行的,它将不起作用

我做了一些研究,发现 GetGuild(id) 方法将公会作为对象但调用该方法属于在 CommandHandler 中声明的 DiscordSocketClient

如何通过直接消息中执行的命令将消息发送到某个不和谐的内疚频道?谢谢!

【问题讨论】:

  • 你必须先获得公会,所以是的,你需要调用 GetGuild。您应该可以通过上下文访问 DiscordSocketClient
  • @Anu6is,那该怎么办呢?如何通过上下文访问客户端?
  • 简单的 Context.Client

标签: .net-core discord bots discord.net


【解决方案1】:
[Command("resource")]
public async Task SendResource(string url = null, [Remainder]string description = null)
{
    if (url == null)
    {
        await ReplyAsync("...");
        return;
    }
    if (description == null)
    {
        await ReplyAsync("...");
        return;
    }
    string text = $"**New resource:** {url}\n**Description:** {description}";
    await Context.Client.GetGuild(123456789).GetTextChannel(863427166662557696).SendMessageAsync(text);
}

注意来自
Context.Guild.GetTextChannel(channel_id).SendMessageAsync(text);
的变化 致
Context.Client.GetGuild(guild_id).GetTextChannel(channel_id).SendMessageAsync(text);

【讨论】:

    【解决方案2】:

    由于我遵循 discord.net 指南模板,因此我只是在我的类构造函数中添加了 DiscordSocketClient 客户端,它就可以工作了。

    【讨论】:

    • 这完全没有必要。就像我在上面的 cmets 中所说,命令模块已经可以通过 Context 访问客户端。见docs
    • @Anu6is Context 没有 GetGuild 或 GetTextChannel 方法。正如我在问题中所写,我的命令必须能够在 PM 和服务器通道中执行
    • 我从未说过 Context 有 GetGuildGetTextChannel 方法。我说上下文可以访问DiscordSocketClient,您可以从中调用GetGuild
    猜你喜欢
    • 2021-09-18
    • 2021-01-26
    • 1970-01-01
    • 2022-07-10
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 2022-07-25
    相关资源
    最近更新 更多