C
C#•3y ago
thieved

random item from a record

how can I get a random item from a record?
127 Replies
Henkypenky
Henkypenky•3y ago
more context please
thieved
thievedOP•3y ago
var response = JsonSerializer.Deserialize<SafeBooruResponse>(raw);
var response = JsonSerializer.Deserialize<SafeBooruResponse>(raw);
i'm deserializing to a custom record type and i need to get a random entry
namespace Elfin.Types
{
public record SafeBooruResponse(string Directory, string Image);
}
namespace Elfin.Types
{
public record SafeBooruResponse(string Directory, string Image);
}
i think i did this right, im new to C# but the http reponse returns an array of safebooru image data(s)
Henkypenky
Henkypenky•3y ago
ah you need to deserialize to List<SafeBooruResponse> then you can just do something like List.Count
thieved
thievedOP•3y ago
then can i change the record to a normal class with properties?
Henkypenky
Henkypenky•3y ago
and Random show me the json
thieved
thievedOP•3y ago
um it looks sum like this
[{"directory": "blah blah blah", "image": "blah blah blah", ...}]
[{"directory": "blah blah blah", "image": "blah blah blah", ...}]
Henkypenky
Henkypenky•3y ago
so you have more properties? directory, image, x??
thieved
thievedOP•3y ago
yea but i dont want to account for those do i have to?
Henkypenky
Henkypenky•3y ago
no
thieved
thievedOP•3y ago
okay
Henkypenky
Henkypenky•3y ago
but the json has more of these?
thieved
thievedOP•3y ago
yep it has multiple objects with more than 2 props
Henkypenky
Henkypenky•3y ago
same record as you have deserialize to List<T>
thieved
thievedOP•3y ago
var response = JsonSerializer.Deserialize<List<SafeBooruResponse>>(raw);
var random = new Random();
var pick = response![random.Next(0, response.Count)];

await context.Message.RespondAsync($"https://safebooru.org/images/{pick.Directory}/{pick.Image}");
var response = JsonSerializer.Deserialize<List<SafeBooruResponse>>(raw);
var random = new Random();
var pick = response![random.Next(0, response.Count)];

await context.Message.RespondAsync($"https://safebooru.org/images/{pick.Directory}/{pick.Image}");
ees good seems i had another question about some code since im new to this deserializer i used newtonsoft but its not type safe
Henkypenky
Henkypenky•3y ago
don't use newtonsoft
thieved
thievedOP•3y ago
yea i learned that earlier
Henkypenky
Henkypenky•3y ago
what version of .net are u targeting?
thieved
thievedOP•3y ago
how do i check my version?
Henkypenky
Henkypenky•3y ago
.csproj visual studio?
thieved
thievedOP•3y ago
7 vscode
Henkypenky
Henkypenky•3y ago
good
thieved
thievedOP•3y ago
i dont like vs even if its handicapping me
Henkypenky
Henkypenky•3y ago
it's okay what do you want to know
thieved
thievedOP•3y ago
okay so
var got = await elfin.HttpClient.GetAsync("https://nekos.life/api/v2/img/neko");
var raw = await got.Content.ReadAsStringAsync();
var response = JsonSerializer.Deserialize<NekosLifeResponse>(raw, new JsonSerializerOptions()
{
PropertyNameCaseInsensitive = true
});

await context.Message.RespondAsync(response!.Url);
var got = await elfin.HttpClient.GetAsync("https://nekos.life/api/v2/img/neko");
var raw = await got.Content.ReadAsStringAsync();
var response = JsonSerializer.Deserialize<NekosLifeResponse>(raw, new JsonSerializerOptions()
{
PropertyNameCaseInsensitive = true
});

await context.Message.RespondAsync(response!.Url);
i have this heres my response class
namespace Elfin.Types
{
public class NekosLifeResponse
{
public required string Url;
}
}
namespace Elfin.Types
{
public class NekosLifeResponse
{
public required string Url;
}
}
so the returned json is {"url": "link"} but for some reason Url is returning as null? even if propertynamecaseinsensitive is on??
Henkypenky
Henkypenky•3y ago
try using an extension method
thieved
thievedOP•3y ago
elaborate?
Henkypenky
Henkypenky•3y ago
var response = await _httpClient.ReadFromJsonAsync<NekosLifeResponse>("https://nekos.life/api/v2/img/neko");
//response now is an object type NekosLifeResponse with Url property
var response = await _httpClient.ReadFromJsonAsync<NekosLifeResponse>("https://nekos.life/api/v2/img/neko");
//response now is an object type NekosLifeResponse with Url property
await context.Message.RespondAsync(response.url);
await context.Message.RespondAsync(response.url);
also as you see the api says url not Url
thieved
thievedOP•3y ago
yea but im turning off case insensitivity
Henkypenky
Henkypenky•3y ago
good yes you can do that or explicitly say so in the class
namespace Elfin.Types
{
public class NekosLifeResponse
{
[JsonPropertyName("url")]
public required string Url;
}
}
namespace Elfin.Types
{
public class NekosLifeResponse
{
[JsonPropertyName("url")]
public required string Url;
}
}
thieved
thievedOP•3y ago
is that a built in attribute from system?
Henkypenky
Henkypenky•3y ago
no, it belongs to System.Text.Json.Serialization why are u using required?
thieved
thievedOP•3y ago
its always in the json its the onlhy thing returned only itll never be null lol
Henkypenky
Henkypenky•3y ago
that's not the definition of required
thieved
thievedOP•3y ago
so is it only for initialization? i meant itll always be provided and should be
Henkypenky
Henkypenky•3y ago
yes but you don't need it
thieved
thievedOP•3y ago
oh
Henkypenky
Henkypenky•3y ago
for that purpose
ReadFromJsonAsync<T>();
ReadFromJsonAsync<T>();
will serialize all the properties it finds in the T if they are not there they are skipped same thing when deserializing
thieved
thievedOP•3y ago
ah another question
Henkypenky
Henkypenky•3y ago
you can also use [JsonIgnore]
thieved
thievedOP•3y ago
why is it necessary to provide the JsonPropertyName?
Henkypenky
Henkypenky•3y ago
because the json is url not Url
thieved
thievedOP•3y ago
so whats the point of insensitive casing
Henkypenky
Henkypenky•3y ago
because you are dealing with 1 property json but if you have a big big json it's slower much slower when you can just say what properties are different or not
thieved
thievedOP•3y ago
so hold on
namespace Elfin.Types
{
public class AniListResponse
{
public AniListData Data { get; init; }
}

public class AniListData
{
public AniListCharacters? Characters { get; init; }
public AniListCharacter? Character { get; init; }
}

public class AniListCharacters
{
public AniListCharacterResult[] Results { get; init; }
}

public class AniListCharacterResult
{
public string Id { get; init; }
}

public class AniListCharacter
{
public int Id { get; init; }
public AniListName Name { get; init; }
public AniListImage Image { get; init; }
public string Gender { get; init; }
public string? Age { get; init; }
public string? BloodType { get; init; }
public int Favourites { get; init; }
public string Description { get; init; }
public string SiteUrl { get; init; }
public AniListMedia Media { get; init; }
}

public class AniListName
{
public string Full { get; init; }
}

public class AniListImage
{
public string? Large { get; init; }
public string? Medium { get; init; }
}

public class AniListMedia
{
public List<AniListMediaEdge> Edges { get; init; }
}

public class AniListMediaEdge
{
public int Id { get; init; }
}
}
namespace Elfin.Types
{
public class AniListResponse
{
public AniListData Data { get; init; }
}

public class AniListData
{
public AniListCharacters? Characters { get; init; }
public AniListCharacter? Character { get; init; }
}

public class AniListCharacters
{
public AniListCharacterResult[] Results { get; init; }
}

public class AniListCharacterResult
{
public string Id { get; init; }
}

public class AniListCharacter
{
public int Id { get; init; }
public AniListName Name { get; init; }
public AniListImage Image { get; init; }
public string Gender { get; init; }
public string? Age { get; init; }
public string? BloodType { get; init; }
public int Favourites { get; init; }
public string Description { get; init; }
public string SiteUrl { get; init; }
public AniListMedia Media { get; init; }
}

public class AniListName
{
public string Full { get; init; }
}

public class AniListImage
{
public string? Large { get; init; }
public string? Medium { get; init; }
}

public class AniListMedia
{
public List<AniListMediaEdge> Edges { get; init; }
}

public class AniListMediaEdge
{
public int Id { get; init; }
}
}
what about this? lol
Henkypenky
Henkypenky•3y ago
how many differ from the json
thieved
thievedOP•3y ago
every single one of those are capitalized while json isnt
Henkypenky
Henkypenky•3y ago
I would still use JsonPropertyName still faster
thieved
thievedOP•3y ago
wouldnt it be slow..
Henkypenky
Henkypenky•3y ago
nope
thieved
thievedOP•3y ago
using System.Text.Json.Serialization;

namespace Elfin.Types
{
public class AniListResponse
{
[JsonPropertyName("data")]
public AniListData Data { get; init; }
}

public class AniListData
{
[JsonPropertyName("characters")]
public AniListCharacters? Characters { get; init; }
[JsonPropertyName("character")]
public AniListCharacter? Character { get; init; }
}

public class AniListCharacters
{
[JsonPropertyName("results")]
public AniListCharacterResult[] Results { get; init; }
}

public class AniListCharacterResult
{
[JsonPropertyName("id")]
public string Id { get; init; }
}

public class AniListCharacter
{
[JsonPropertyName("id")]
public int Id { get; init; }
[JsonPropertyName("name")]
public AniListName Name { get; init; }
[JsonPropertyName("image")]
public AniListImage Image { get; init; }
[JsonPropertyName("gender")]
public string Gender { get; init; }
[JsonPropertyName("age")]
public string? Age { get; init; }
[JsonPropertyName("bloodType")]
public string? BloodType { get; init; }
[JsonPropertyName("favourites")]
public int Favourites { get; init; }
[JsonPropertyName("description")]
public string Description { get; init; }
[JsonPropertyName("siteUrl")]
public string SiteUrl { get; init; }
[JsonPropertyName("media")]
public AniListMedia Media { get; init; }
}

public class AniListName
{
[JsonPropertyName("full")]
public string Full { get; init; }
}

public class AniListImage
{
[JsonPropertyName("large")]
public string? Large { get; init; }
[JsonPropertyName("medium")]
public string? Medium { get; init; }
}

public class AniListMedia
{
[JsonPropertyName("edges")]
public List<AniListMediaEdge> Edges { get; init; }
}

public class AniListMediaEdge
{
[JsonPropertyName("id")]
public int Id { get; init; }
}
}
using System.Text.Json.Serialization;

namespace Elfin.Types
{
public class AniListResponse
{
[JsonPropertyName("data")]
public AniListData Data { get; init; }
}

public class AniListData
{
[JsonPropertyName("characters")]
public AniListCharacters? Characters { get; init; }
[JsonPropertyName("character")]
public AniListCharacter? Character { get; init; }
}

public class AniListCharacters
{
[JsonPropertyName("results")]
public AniListCharacterResult[] Results { get; init; }
}

public class AniListCharacterResult
{
[JsonPropertyName("id")]
public string Id { get; init; }
}

public class AniListCharacter
{
[JsonPropertyName("id")]
public int Id { get; init; }
[JsonPropertyName("name")]
public AniListName Name { get; init; }
[JsonPropertyName("image")]
public AniListImage Image { get; init; }
[JsonPropertyName("gender")]
public string Gender { get; init; }
[JsonPropertyName("age")]
public string? Age { get; init; }
[JsonPropertyName("bloodType")]
public string? BloodType { get; init; }
[JsonPropertyName("favourites")]
public int Favourites { get; init; }
[JsonPropertyName("description")]
public string Description { get; init; }
[JsonPropertyName("siteUrl")]
public string SiteUrl { get; init; }
[JsonPropertyName("media")]
public AniListMedia Media { get; init; }
}

public class AniListName
{
[JsonPropertyName("full")]
public string Full { get; init; }
}

public class AniListImage
{
[JsonPropertyName("large")]
public string? Large { get; init; }
[JsonPropertyName("medium")]
public string? Medium { get; init; }
}

public class AniListMedia
{
[JsonPropertyName("edges")]
public List<AniListMediaEdge> Edges { get; init; }
}

public class AniListMediaEdge
{
[JsonPropertyName("id")]
public int Id { get; init; }
}
}
whew..
var got = await elfin.HttpClient.GetAsync("https://nekos.life/api/v2/img/neko");
var raw = await got.Content.ReadAsStringAsync();
var response = JsonSerializer.Deserialize<NekosLifeResponse>(raw);

await context.Message.RespondAsync(response!.Url);
var got = await elfin.HttpClient.GetAsync("https://nekos.life/api/v2/img/neko");
var raw = await got.Content.ReadAsStringAsync();
var response = JsonSerializer.Deserialize<NekosLifeResponse>(raw);

await context.Message.RespondAsync(response!.Url);
Henkypenky
Henkypenky•3y ago
let me do a fast test
thieved
thievedOP•3y ago
okay so i did try thisss and it did not work 😭 okay yea so its deserializing to this {}
Henkypenky
Henkypenky•3y ago
var response = JsonSerializer.Deserialize<List<NekosLifeResponse>>(raw);
thieved
thievedOP•3y ago
why its not a list
thieved
thievedOP•3y ago
Henkypenky
Henkypenky•3y ago
oh my bad
thieved
thievedOP•3y ago
np
Henkypenky
Henkypenky•3y ago
why didn't u use what i told you ReadFromJsonAsync<T>();
thieved
thievedOP•3y ago
i didnt know what u meant i cant find that method anywhere
Henkypenky
Henkypenky•3y ago
_httpClient.ReadFromJsonAsync<T>();
thieved
thievedOP•3y ago
that property doesn't exist on HttpClient
public HttpClient HttpClient { get; init; }
public HttpClient HttpClient { get; init; }
Henkypenky
Henkypenky•3y ago
it's an extension method is this a console app? it should be by default nonetheless what is elfin? var got = await elfin.HttpClient.GetAsync("https://nekos.life/api/v2/img/neko"); here
thieved
thievedOP•3y ago
my custom client class
Henkypenky
Henkypenky•3y ago
nooo why ?
thieved
thievedOP•3y ago
using Elfin.Types;
using DSharpPlus;
using DSharpPlus.Entities;
using DSharpPlus.Interactivity;
using DSharpPlus.Interactivity.Extensions;
using DSharpPlus.EventArgs;

namespace Elfin.Core
{
public class ElfinClient
{
public ElfinRegistrar Registrar { get; init; }
public DiscordClient RawClient { get; init; }
public HttpClient HttpClient { get; init; }
public ElfinEvent[] Events = { };
public ElfinCommand[] Commands = { };
public string Prefix;

public ElfinClient(ElfinData data)
{
this.Registrar = new ElfinRegistrar(this);
this.RawClient = new DiscordClient(new DiscordConfiguration()
{
Token = data.Token,
TokenType = TokenType.Bot,
Intents = data.Intents,
MinimumLogLevel = data.LogLevel
});

this.RawClient.UseInteractivity(new InteractivityConfiguration()
{
Timeout = TimeSpan.FromSeconds(30)
});

this.HttpClient = new HttpClient();
this.Prefix = data.Prefix;
}

public void DisableCommands()
{
foreach (ElfinCommand command in this.Commands)
{
command.Enabled = false;
}
}

public void EnableCommands()
{
foreach (ElfinCommand command in this.Commands)
{
command.Enabled = true;
}
}

public void LoadCommands()
{
this.Commands = this.Registrar.ReadCommands();
}

public void LoadEvents()
{
this.Events = this.Registrar.ReadEvents();

foreach (ElfinEvent ev in this.Events)
{
ev.Initialize();
}
}

public bool IsCompatible(string name, ElfinCommand command)
{
return name == command.Name || command.Aliases.Any(alias => name == alias);
}

public ElfinCommand? GetCommand(string name)
{
return this.Commands.FirstOrDefault(command => IsCompatible(name, command));
}

public void HandlePossibleCommand(MessageCreateEventArgs packet)
{
DiscordMessage message = packet.Message;
string messageContent = message.Content;

if (!message.Author.IsBot && messageContent.StartsWith(this.Prefix))
{
string[] components = messageContent.Split(" ");
string commandName = components[0].Replace(this.Prefix, "").ToLower();
ElfinCommand? command = this.GetCommand(commandName);

if (command != null && command.Enabled)
{
ElfinCommandContext context = new()
{
Packet = packet,
Author = packet.Author,
Guild = packet.Guild,
Channel = packet.Channel,
Message = message,
Args = components[1..]
};

command.Respond!(this, context);
}
}
}

public async Task Login()
{
await this.RawClient.ConnectAsync();
await Task.Delay(-1);
}
}
}
using Elfin.Types;
using DSharpPlus;
using DSharpPlus.Entities;
using DSharpPlus.Interactivity;
using DSharpPlus.Interactivity.Extensions;
using DSharpPlus.EventArgs;

namespace Elfin.Core
{
public class ElfinClient
{
public ElfinRegistrar Registrar { get; init; }
public DiscordClient RawClient { get; init; }
public HttpClient HttpClient { get; init; }
public ElfinEvent[] Events = { };
public ElfinCommand[] Commands = { };
public string Prefix;

public ElfinClient(ElfinData data)
{
this.Registrar = new ElfinRegistrar(this);
this.RawClient = new DiscordClient(new DiscordConfiguration()
{
Token = data.Token,
TokenType = TokenType.Bot,
Intents = data.Intents,
MinimumLogLevel = data.LogLevel
});

this.RawClient.UseInteractivity(new InteractivityConfiguration()
{
Timeout = TimeSpan.FromSeconds(30)
});

this.HttpClient = new HttpClient();
this.Prefix = data.Prefix;
}

public void DisableCommands()
{
foreach (ElfinCommand command in this.Commands)
{
command.Enabled = false;
}
}

public void EnableCommands()
{
foreach (ElfinCommand command in this.Commands)
{
command.Enabled = true;
}
}

public void LoadCommands()
{
this.Commands = this.Registrar.ReadCommands();
}

public void LoadEvents()
{
this.Events = this.Registrar.ReadEvents();

foreach (ElfinEvent ev in this.Events)
{
ev.Initialize();
}
}

public bool IsCompatible(string name, ElfinCommand command)
{
return name == command.Name || command.Aliases.Any(alias => name == alias);
}

public ElfinCommand? GetCommand(string name)
{
return this.Commands.FirstOrDefault(command => IsCompatible(name, command));
}

public void HandlePossibleCommand(MessageCreateEventArgs packet)
{
DiscordMessage message = packet.Message;
string messageContent = message.Content;

if (!message.Author.IsBot && messageContent.StartsWith(this.Prefix))
{
string[] components = messageContent.Split(" ");
string commandName = components[0].Replace(this.Prefix, "").ToLower();
ElfinCommand? command = this.GetCommand(commandName);

if (command != null && command.Enabled)
{
ElfinCommandContext context = new()
{
Packet = packet,
Author = packet.Author,
Guild = packet.Guild,
Channel = packet.Channel,
Message = message,
Args = components[1..]
};

command.Respond!(this, context);
}
}
}

public async Task Login()
{
await this.RawClient.ConnectAsync();
await Task.Delay(-1);
}
}
}
it includes a raw client lol
Henkypenky
Henkypenky•3y ago
that's really bad
thieved
thievedOP•3y ago
but it has more utilities since i cant extend the normal discord client class well im fine with it
Henkypenky
Henkypenky•3y ago
okay
thieved
thievedOP•3y ago
it does what i need but yea this is my response class
using System.Text.Json.Serialization;

namespace Elfin.Types
{
public class NekosLifeResponse
{
[JsonPropertyName("url")]
public string Url;
}
}
using System.Text.Json.Serialization;

namespace Elfin.Types
{
public class NekosLifeResponse
{
[JsonPropertyName("url")]
public string Url;
}
}
but the deserialized object is empty
Henkypenky
Henkypenky•3y ago
set a breakpoint at var raw and see what you get
thieved
thievedOP•3y ago
well i get the raw json when i print it it comes out normally it* however for some reason the converter isnt understanding the type
{"url":"https://cdn.nekos.life/neko/neko123.jpeg"}
{"url":"https://cdn.nekos.life/neko/neko123.jpeg"}
Henkypenky
Henkypenky•3y ago
raw has the string correctly?
thieved
thievedOP•3y ago
yea its the string json response from the request
Henkypenky
Henkypenky•3y ago
if you type elfin.HttpClient.GetFromJsonAsync<NekosLifeResponse>(url); that doesn't work?
thieved
thievedOP•3y ago
nope no method found
thieved
thievedOP•3y ago
Henkypenky
Henkypenky•3y ago
can you please do var _httpclient = new HttpClient(); and not use elfin
thieved
thievedOP•3y ago
sure whats the point though?
Henkypenky
Henkypenky•3y ago
i want to see something just do var _httpclient = new HttpClient(); _httpClient.GetFromJsonAsync<NekosLifeResponse>(url); <NekosLifeResponse>
thieved
thievedOP•3y ago
oops
thieved
thievedOP•3y ago
Henkypenky
Henkypenky•3y ago
add this using System.Net.Http.Json;
thieved
thievedOP•3y ago
its present now
Henkypenky
Henkypenky•3y ago
should work try it
thieved
thievedOP•3y ago
let me try came out as an empty object wth 😭
var response = await elfin.HttpClient.GetFromJsonAsync<NekosLifeResponse>("https://nekos.life/api/v2/img/neko");

await context.Message.RespondAsync(response!.Url);
var response = await elfin.HttpClient.GetFromJsonAsync<NekosLifeResponse>("https://nekos.life/api/v2/img/neko");

await context.Message.RespondAsync(response!.Url);
Henkypenky
Henkypenky•3y ago
doesn't work for me can you give me 5 minutes gotta take the dog out and we can fix it
thieved
thievedOP•3y ago
ofc
Henkypenky
Henkypenky•3y ago
ah lol i know what it is its a field without a setter try this
thieved
thievedOP•3y ago
OH LMAO
Henkypenky
Henkypenky•3y ago
public class NekosLifeResponse
{
[JsonPropertyName("url")]
public string? Url { get; set; }
}
public class NekosLifeResponse
{
[JsonPropertyName("url")]
public string? Url { get; set; }
}
thieved
thievedOP•3y ago
NO WONDER 😭
Henkypenky
Henkypenky•3y ago
late here not thinking straight xd try it out i'll be back in 5
thieved
thievedOP•3y ago
its 10pm for me alright ty works! how can i d o this with a post request? i need to do something like this
var payload = new StringContent(serialized, Encoding.UTF8, "application/json");
var response = await elfin.HttpClient.PostAsJsonAsync<List<AniListResponse>>("https://graphql.anilist.co/", payload);
var payload = new StringContent(serialized, Encoding.UTF8, "application/json");
var response = await elfin.HttpClient.PostAsJsonAsync<List<AniListResponse>>("https://graphql.anilist.co/", payload);
but the payload parameter is saying it needs to be of the same type im using for the request method
var payload = new StringContent(serialized, Encoding.UTF8, "application/json");
var feed = await elfin.HttpClient.PostAsync("https://graphql.anilist.co/", payload);
var raw = await feed.Content.ReadAsStringAsync();

if (raw == "")
{
await context.Message.RespondAsync("No character found.");
}
var payload = new StringContent(serialized, Encoding.UTF8, "application/json");
var feed = await elfin.HttpClient.PostAsync("https://graphql.anilist.co/", payload);
var raw = await feed.Content.ReadAsStringAsync();

if (raw == "")
{
await context.Message.RespondAsync("No character found.");
}
should i continue with my other method?
var response = JsonSerializer.Deserialize<AniListResponse>(raw);
var response = JsonSerializer.Deserialize<AniListResponse>(raw);
Henkypenky
Henkypenky•3y ago
PostAsJsonAsync is just List<AnyListResponse> list = new(); add whatever to the list then elfin.HttpClient.PostAsJsonAsync<List<AniListResponse>>("https://graphql.anilist.co/", list); no StrinContent needed if you dont want to use that just do what you did and use SendAsync (see below) or better yet PostAsync
thieved
thievedOP•3y ago
well i cant use this then ill just use my og method
Henkypenky
Henkypenky•3y ago
what og method
thieved
thievedOP•3y ago
it seems theres a prob tho šŸ¤”
var characterName = string.Join(" ", context.Args);
var serialized = JsonSerializer.Serialize(new
{
variables = new { search = characterName },
query = searchGraphQL
});

var payload = new StringContent(serialized, Encoding.UTF8, "application/json");
var feed = await elfin.HttpClient.PostAsync("https://graphql.anilist.co/", payload);
var raw = await feed.Content.ReadAsStringAsync();


if (raw == "")
{
await context.Message.RespondAsync("No character found.");
}
else
{
var response = JsonSerializer.Deserialize<AniListResponse>(raw);
var characterName = string.Join(" ", context.Args);
var serialized = JsonSerializer.Serialize(new
{
variables = new { search = characterName },
query = searchGraphQL
});

var payload = new StringContent(serialized, Encoding.UTF8, "application/json");
var feed = await elfin.HttpClient.PostAsync("https://graphql.anilist.co/", payload);
var raw = await feed.Content.ReadAsStringAsync();


if (raw == "")
{
await context.Message.RespondAsync("No character found.");
}
else
{
var response = JsonSerializer.Deserialize<AniListResponse>(raw);
but the response isnt deserializing properly heres what raw looks like
{"data":{"characters":{"results":[{"id":71}]}}}
{"data":{"characters":{"results":[{"id":71}]}}}
Henkypenky
Henkypenky•3y ago
and your class
thieved
thievedOP•3y ago
public class AniListResponse
{
[JsonPropertyName("data")]
public AniListData Data { get; set; }
}

public class AniListData
{
[JsonPropertyName("characters")]
public AniListCharacters? Characters { get; set; }
[JsonPropertyName("character")]
public AniListCharacter? Character { get; set; }
}

public class AniListCharacters
{
[JsonPropertyName("results")]
public AniListCharacterResult[] Results { get; set; }
}

public class AniListCharacterResult
{
[JsonPropertyName("id")]
public string Id { get; set; }
}
public class AniListResponse
{
[JsonPropertyName("data")]
public AniListData Data { get; set; }
}

public class AniListData
{
[JsonPropertyName("characters")]
public AniListCharacters? Characters { get; set; }
[JsonPropertyName("character")]
public AniListCharacter? Character { get; set; }
}

public class AniListCharacters
{
[JsonPropertyName("results")]
public AniListCharacterResult[] Results { get; set; }
}

public class AniListCharacterResult
{
[JsonPropertyName("id")]
public string Id { get; set; }
}
Henkypenky
Henkypenky•3y ago
AniListResponse that looks fine are u getting any errors?
thieved
thievedOP•3y ago
none are being thrown nope hold on
Henkypenky
Henkypenky•3y ago
check response it should deserialize correctly
thieved
thievedOP•3y ago
var response = JsonSerializer.Deserialize<AniListResponse>(raw);

Console.WriteLine(response.GetType());
var response = JsonSerializer.Deserialize<AniListResponse>(raw);

Console.WriteLine(response.GetType());
nothing prints so theres a break after the deserialization
Henkypenky
Henkypenky•3y ago
a breakpoint?
thieved
thievedOP•3y ago
no it stops worjing
Henkypenky
Henkypenky•3y ago
an exception?
thieved
thievedOP•3y ago
possibly but its not killing my code and it isnt being printed so hold on forgot
thieved
thievedOP•3y ago
thieved
thievedOP•3y ago
ids are integers for anilist lol but i had a question abt errors too why arent they killing my program?? theyre just silent
Henkypenky
Henkypenky•3y ago
is that inside a try catch?
thieved
thievedOP•3y ago
just now it was but only bc i needed to see the error
Henkypenky
Henkypenky•3y ago
then that's why if you catch the exception, execution goes on visual studio code is horrible at this sort of things
thieved
thievedOP•3y ago
okay but i never catch it
Henkypenky
Henkypenky•3y ago
i have no idea how it handles exceptions it's a glorified text editor
thieved
thievedOP•3y ago
im using command prompt i think its the way my cmd is handled basically it goes like this MessageEvent => Command Handler Method => Run
using Elfin.Attributes;
using Elfin.Core;

namespace Elfin.Events
{
[ElfinEvent("MessageCreated")]
public class MessageCreatedEvent
{
public static void Initalize(ElfinClient elfin)
{
elfin.RawClient.MessageCreated += async (self, packet) =>
{
elfin.HandlePossibleCommand(packet);
};
}
}
}
using Elfin.Attributes;
using Elfin.Core;

namespace Elfin.Events
{
[ElfinEvent("MessageCreated")]
public class MessageCreatedEvent
{
public static void Initalize(ElfinClient elfin)
{
elfin.RawClient.MessageCreated += async (self, packet) =>
{
elfin.HandlePossibleCommand(packet);
};
}
}
}
i think i got an ide idea welp didnt work
ElfinCommand newCommand = new()
{
Name = commandName,
Aliases = aliases,
Usage = usage,
Description = description,
Respond = (ElfinClient elfin, ElfinCommandContext context) => {
try {
method.Invoke(null, new object[] { elfin, context });
} catch (Exception ex) {
Console.WriteLine(ex);
}
}
};
ElfinCommand newCommand = new()
{
Name = commandName,
Aliases = aliases,
Usage = usage,
Description = description,
Respond = (ElfinClient elfin, ElfinCommandContext context) => {
try {
method.Invoke(null, new object[] { elfin, context });
} catch (Exception ex) {
Console.WriteLine(ex);
}
}
};
i tried catchi ng it in the method's invoking but its whatever
Henkypenky
Henkypenky•3y ago
catch it in the request handling not the method invoking
try {

//DO ALL THE POST HERE
}
catch(){}
try {

//DO ALL THE POST HERE
}
catch(){}
thieved
thievedOP•3y ago
that would require a try catch for every method that seems repetitive doesnt uit
Henkypenky
Henkypenky•3y ago
then make it non repetitive
thieved
thievedOP•3y ago
well clearly the errors cant be caught outside of the method from what i'm seeing
Henkypenky
Henkypenky•3y ago
i think you are on a good path now try on your own learn by doing!! (and failing)
thieved
thievedOP•3y ago
lol ty i got it from here lik u said have a good night
Henkypenky
Henkypenky•3y ago
if u have more questions ask for sure
thieved
thievedOP•3y ago
kk ofc
Henkypenky
Henkypenky•3y ago
but try to practice
thieved
thievedOP•3y ago
yap šŸ™‡ā€ā™‚ļø
Henkypenky
Henkypenky•3y ago
good night
thieved
thievedOP•3y ago
night

Did you find this page helpful?