【问题标题】:How to read a posted file in C# Discord.net?如何在 C# Discord.net 中读取发布的文件?
【发布时间】:2019-04-15 20:31:13
【问题描述】:

我想让我的discord.net 机器人读取在聊天中发布的文件。到目前为止,我似乎无法在 C# 中找到答案。

有没有办法做到这一点?

【问题讨论】:

    标签: c# discord discord.net


    【解决方案1】:

    似乎我正在寻找的答案是我可以使用Context.Message 访问用户的消息以及几乎所有有关它的详细信息,尤其是在继承自ModuleBase<SocketCommandContext> 的类中。像这样,我可以使用 System.Net 模块从 URL 下载附件的内容,然后做任何我想做的事情。

    这是一个实现上述内容的示例命令。旁注:为简单起见,它没有实施任何安全措施。

    [Command("printFile")]
    public async Task PrintFile()
    {
        var attachments = Context.Message.Attachments;
    
        // Create a new WebClient instance.
        WebClient myWebClient = new WebClient();
    
        string file = attachments.ElementAt(0).Filename;
        string url = attachments.ElementAt(0).Url;
    
        // Download the resource and load the bytes into a buffer.
        byte[] buffer = myWebClient.DownloadData(url);
    
        // Encode the buffer into UTF-8
        string download = Encoding.UTF8.GetString(buffer);
    
        Console.WriteLine("Download successful.");
    
        // Place the contents as a message because the method said it should.
        await ReplyAsync("Received attachment!\n\n" + download);
    }
    

    【讨论】:

      【解决方案2】:

      鉴于 discord bot API 的异步特性以及它对任务的广泛使用,我建议您改用 HttpClient 并异步执行操作...

      public class DebugModule : ModuleBase<SocketCommandContext>
      {
          [Command("read")]
          [Summary("Reads the contents of a dropped file.")]
          public async Task Read() {
              using(var client = new HttpClient())
                  await ReplyAsync(await client.GetStringAsync(Context.Message.Attachments.First().Url));
          }
      }
      

      因为我已经像许多其他人一样配置了我的机器人来使用!作为前缀,这里的用法很简单...

      将文件放到频道上 输入评论为“!阅读” 这会指示机器人以异步方式回复上传文件的内容。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-11
        • 1970-01-01
        • 2016-09-18
        • 2021-11-16
        • 1970-01-01
        • 1970-01-01
        • 2016-04-17
        • 2021-07-06
        相关资源
        最近更新 更多