Search code examples
c#.netasynchronousasync-awaitdiscord.net

How to call API in Discord.NET command?


I have problem with calling API in my Discord Bot, I am trying to learn async, await but it seems as I am stuck.

This is my Call API class where I am calling API.

public async Task<Root> GetInfoAsync()
    {
        string path = "https://onemocneni-aktualne.mzcr.cz/api/v2/covid-19/zakladni-prehled.json";
        Root data = null;
        HttpResponseMessage response = await client.GetAsync(path);
        if (response.IsSuccessStatusCode)
        {
            string json = await response.Content.ReadAsStringAsync();
            data = JsonConvert.DeserializeObject<Root>(json);
        }
        return data;
    }

    public async Task<string> VypisAsync()
    {
        Root data = await this.GetInfoAsync();
        int deaths = data.data[0].umrti,
            recovered = data.data[0].vyleceni,
            positive = data.data[0].aktivni_pripady,
            hospitalized = data.data[0].aktualne_hospitalizovani;
        return $"Aktualni situace v ČR:\n" +
               $"vyleceni: {recovered}\n"  +
               $"aktualne nemocni: {positive}\n" +
               $"hospitalizovani: {hospitalized}\n" +
               $"zemreli: {deaths}";
    }

And here is my covid command

public class CovidModule : ModuleBase<SocketCommandContext>
{
    // ~void -> current covid situation in CZ
    [Command("covid")]
    [Summary("shows current covid situation in CZ")]
    public async Task<Task> CovidAsync()
    {
        CovidApi api = new CovidApi();
        return ReplyAsync(await api.VypisAsync());
    }
}

I know that all others commands return Task, but I don't know how to make it like that.


Solution

  • ReplyAsync() is an async method, so you need to await it.

    Your CovidAsync() method isn't returning an actual value, so in the synchronous world its return value would be void. Since it's an async method you return Task instead.

    public async Task CovidAsync()
    {
        CovidApi api = new CovidApi();
        await ReplyAsync(await api.VypisAsync());
    }
    

    As an aside, it would be better to have CovidApi as a member of your CovidModule. That way you don't need to keep newing it up in each method.