C
C#ā€¢2y ago
thieved

random item from a record

how can I get a random item from a record?
127 Replies
Henkypenky
Henkypenkyā€¢2y ago
more context please
thieved
thievedOPā€¢2y 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ā€¢2y ago
ah you need to deserialize to List<SafeBooruResponse> then you can just do something like List.Count
thieved
thievedOPā€¢2y ago
then can i change the record to a normal class with properties?
Henkypenky
Henkypenkyā€¢2y ago
and Random show me the json
thieved
thievedOPā€¢2y 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ā€¢2y ago
so you have more properties? directory, image, x??
thieved
thievedOPā€¢2y ago
yea but i dont want to account for those do i have to?
Henkypenky
Henkypenkyā€¢2y ago
no
thieved
thievedOPā€¢2y ago
okay
Henkypenky
Henkypenkyā€¢2y ago
but the json has more of these?
thieved
thievedOPā€¢2y ago
yep it has multiple objects with more than 2 props
Henkypenky
Henkypenkyā€¢2y ago
same record as you have deserialize to List<T>
thieved
thievedOPā€¢2y 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ā€¢2y ago
don't use newtonsoft
thieved
thievedOPā€¢2y ago
yea i learned that earlier
Henkypenky
Henkypenkyā€¢2y ago
what version of .net are u targeting?
thieved
thievedOPā€¢2y ago
how do i check my version?
Henkypenky
Henkypenkyā€¢2y ago
.csproj visual studio?
thieved
thievedOPā€¢2y ago
7 vscode
Henkypenky
Henkypenkyā€¢2y ago
good
thieved
thievedOPā€¢2y ago
i dont like vs even if its handicapping me
Henkypenky
Henkypenkyā€¢2y ago
it's okay what do you want to know
thieved
thievedOPā€¢2y 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ā€¢2y ago
try using an extension method
thieved
thievedOPā€¢2y ago
elaborate?
Henkypenky
Henkypenkyā€¢2y 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ā€¢2y ago
yea but im turning off case insensitivity
Henkypenky
Henkypenkyā€¢2y 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ā€¢2y ago
is that a built in attribute from system?
Henkypenky
Henkypenkyā€¢2y ago
no, it belongs to System.Text.Json.Serialization why are u using required?
thieved
thievedOPā€¢2y ago
its always in the json its the onlhy thing returned only itll never be null lol
Henkypenky
Henkypenkyā€¢2y ago
that's not the definition of required
thieved
thievedOPā€¢2y ago
so is it only for initialization? i meant itll always be provided and should be
Henkypenky
Henkypenkyā€¢2y ago
yes but you don't need it
thieved
thievedOPā€¢2y ago
oh
Henkypenky
Henkypenkyā€¢2y 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ā€¢2y ago
ah another question
Henkypenky
Henkypenkyā€¢2y ago
you can also use [JsonIgnore]
thieved
thievedOPā€¢2y ago
why is it necessary to provide the JsonPropertyName?
Henkypenky
Henkypenkyā€¢2y ago
because the json is url not Url
thieved
thievedOPā€¢2y ago
so whats the point of insensitive casing
Henkypenky
Henkypenkyā€¢2y 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ā€¢2y 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ā€¢2y ago
how many differ from the json
thieved
thievedOPā€¢2y ago
every single one of those are capitalized while json isnt
Henkypenky
Henkypenkyā€¢2y ago
I would still use JsonPropertyName still faster
thieved
thievedOPā€¢2y ago
wouldnt it be slow..
Henkypenky
Henkypenkyā€¢2y ago
nope
thieved
thievedOPā€¢2y 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ā€¢2y ago
let me do a fast test
thieved
thievedOPā€¢2y ago
okay so i did try thisss and it did not work šŸ˜­ okay yea so its deserializing to this {}
Henkypenky
Henkypenkyā€¢2y ago
var response = JsonSerializer.Deserialize<List<NekosLifeResponse>>(raw);
thieved
thievedOPā€¢2y ago
why its not a list
thieved
thievedOPā€¢2y ago
Henkypenky
Henkypenkyā€¢2y ago
oh my bad
thieved
thievedOPā€¢2y ago
np
Henkypenky
Henkypenkyā€¢2y ago
why didn't u use what i told you ReadFromJsonAsync<T>();
thieved
thievedOPā€¢2y ago
i didnt know what u meant i cant find that method anywhere
Henkypenky
Henkypenkyā€¢2y ago
_httpClient.ReadFromJsonAsync<T>();
thieved
thievedOPā€¢2y ago
that property doesn't exist on HttpClient
public HttpClient HttpClient { get; init; }
public HttpClient HttpClient { get; init; }
Henkypenky
Henkypenkyā€¢2y 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ā€¢2y ago
my custom client class
Henkypenky
Henkypenkyā€¢2y ago
nooo why ?
thieved
thievedOPā€¢2y 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ā€¢2y ago
that's really bad
thieved
thievedOPā€¢2y ago
but it has more utilities since i cant extend the normal discord client class well im fine with it
Henkypenky
Henkypenkyā€¢2y ago
okay
thieved
thievedOPā€¢2y 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ā€¢2y ago
set a breakpoint at var raw and see what you get
thieved
thievedOPā€¢2y 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ā€¢2y ago
raw has the string correctly?
thieved
thievedOPā€¢2y ago
yea its the string json response from the request
Henkypenky
Henkypenkyā€¢2y ago
if you type elfin.HttpClient.GetFromJsonAsync<NekosLifeResponse>(url); that doesn't work?
thieved
thievedOPā€¢2y ago
nope no method found
thieved
thievedOPā€¢2y ago
Henkypenky
Henkypenkyā€¢2y ago
can you please do var _httpclient = new HttpClient(); and not use elfin
thieved
thievedOPā€¢2y ago
sure whats the point though?
Henkypenky
Henkypenkyā€¢2y ago
i want to see something just do var _httpclient = new HttpClient(); _httpClient.GetFromJsonAsync<NekosLifeResponse>(url); <NekosLifeResponse>
thieved
thievedOPā€¢2y ago
oops
thieved
thievedOPā€¢2y ago
Henkypenky
Henkypenkyā€¢2y ago
add this using System.Net.Http.Json;
thieved
thievedOPā€¢2y ago
its present now
Henkypenky
Henkypenkyā€¢2y ago
should work try it
thieved
thievedOPā€¢2y 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ā€¢2y ago
doesn't work for me can you give me 5 minutes gotta take the dog out and we can fix it
thieved
thievedOPā€¢2y ago
ofc
Henkypenky
Henkypenkyā€¢2y ago
ah lol i know what it is its a field without a setter try this
thieved
thievedOPā€¢2y ago
OH LMAO
Henkypenky
Henkypenkyā€¢2y ago
public class NekosLifeResponse
{
[JsonPropertyName("url")]
public string? Url { get; set; }
}
public class NekosLifeResponse
{
[JsonPropertyName("url")]
public string? Url { get; set; }
}
thieved
thievedOPā€¢2y ago
NO WONDER šŸ˜­
Henkypenky
Henkypenkyā€¢2y ago
late here not thinking straight xd try it out i'll be back in 5
thieved
thievedOPā€¢2y 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ā€¢2y 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ā€¢2y ago
well i cant use this then ill just use my og method
Henkypenky
Henkypenkyā€¢2y ago
what og method
thieved
thievedOPā€¢2y 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ā€¢2y ago
and your class
thieved
thievedOPā€¢2y 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ā€¢2y ago
AniListResponse that looks fine are u getting any errors?
thieved
thievedOPā€¢2y ago
none are being thrown nope hold on
Henkypenky
Henkypenkyā€¢2y ago
check response it should deserialize correctly
thieved
thievedOPā€¢2y 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ā€¢2y ago
a breakpoint?
thieved
thievedOPā€¢2y ago
no it stops worjing
Henkypenky
Henkypenkyā€¢2y ago
an exception?
thieved
thievedOPā€¢2y ago
possibly but its not killing my code and it isnt being printed so hold on forgot
thieved
thievedOPā€¢2y ago
thieved
thievedOPā€¢2y 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ā€¢2y ago
is that inside a try catch?
thieved
thievedOPā€¢2y ago
just now it was but only bc i needed to see the error
Henkypenky
Henkypenkyā€¢2y 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ā€¢2y ago
okay but i never catch it
Henkypenky
Henkypenkyā€¢2y ago
i have no idea how it handles exceptions it's a glorified text editor
thieved
thievedOPā€¢2y 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ā€¢2y 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ā€¢2y ago
that would require a try catch for every method that seems repetitive doesnt uit
Henkypenky
Henkypenkyā€¢2y ago
then make it non repetitive
thieved
thievedOPā€¢2y ago
well clearly the errors cant be caught outside of the method from what i'm seeing
Henkypenky
Henkypenkyā€¢2y ago
i think you are on a good path now try on your own learn by doing!! (and failing)
thieved
thievedOPā€¢2y ago
lol ty i got it from here lik u said have a good night
Henkypenky
Henkypenkyā€¢2y ago
if u have more questions ask for sure
thieved
thievedOPā€¢2y ago
kk ofc
Henkypenky
Henkypenkyā€¢2y ago
but try to practice
thieved
thievedOPā€¢2y ago
yap šŸ™‡ā€ā™‚ļø
Henkypenky
Henkypenkyā€¢2y ago
good night
thieved
thievedOPā€¢2y ago
night
Want results from more Discord servers?
Add your server