So basically, I have this code where my bot downloads the URL sent with the command.
[Command("jpg")]
private async Task Jpg([Remainder] string text)
{
string filetype = Path.GetExtension(text);
if (!text.StartsWith("http") || !text.StartsWith("https"))
{
return;
}
using (var client = new WebClient())
{
client.DownloadFileAsync(new Uri(text), "img\\a" filetype);
}
/* Image stuff etc */
}
I'd like to make it so it grabs the image attachment from the message instead of relying on the URL, but trying to use Context.Message.Attachments gives me an error.
CodePudding user response:
Context.Message.Attachments
is a collection of attachments, you can grab the URL of each attachment (these are on the discord server for uploaded images) and use this URL instead of a message based one.
You can loop through the attachment or just grab the URL for the first attachment.
Grabbing the first attachment URL (considering it has attachments):
string URL = Context.Message.Attachments.ElementAt(0).Url;
Looping to grab full list of URLs:
string[] urlArray = {};
foreach(IAttachment attachment in Context.Message.Attachments){
urlArray.Append(attachment.Url);
}
// Handle the URLs as you did before.
or you could implement the loop in a way to download them in that foreach
(using your DownloadFileAsync
as I assume it works for you - if not consider my previous edit of this message)
using (var client = new WebClient()) {
foreach(IAttachment attachment in Context.Message.Attachments){
string filetype = Path.GetExtension(attachment.Url);
client.DownloadFileAsync(new Uri(attachment.Url), "img\\a" filetype);
}
}