diff --git a/Justice/Commands/Settings.cs b/Justice/Commands/Settings.cs index 447e032..4f68299 100644 --- a/Justice/Commands/Settings.cs +++ b/Justice/Commands/Settings.cs @@ -84,63 +84,6 @@ namespace DiscordApp.Discord.Commands int allCount = 0; var allReports = Startup.appDbContext.Reports.ToArray(); var allEmployee = new Dictionary(); - string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6Ijk0NTMxNzgzMjI5MDMzNjc5OCIsInRva2VuVmVyc2lvbiI6MCwiaXAiOiIxODUuMTA0LjExMi4xODAiLCJpYXQiOjE2OTkxOTA5MzMsImV4cCI6MTcwMTc4MjkzM30.Z9ykVYIIsN0bF0BlNV6sgwdiRu-GNx-olmKRxl6OJHk"; - var cookieContainer = new CookieContainer(); - var handler = new HttpClientHandler() { CookieContainer = cookieContainer }; - HttpClient client = new(handler); - client.BaseAddress = new Uri("https://spworlds.ru/api/"); - - cookieContainer.Add(client.BaseAddress, new Cookie("jeff", token)); - string ok = @"{ - ""id"": ""945317832290336798"", - ""isAdmin"": false, - ""minecraftUUID"": ""775f00d30da34275967d58cb50838b9f"", - ""accounts"": [ - { - ""id"": ""095ee127-578b-479e-90af-21b679546e09"", - ""serverId"": ""spb"", - ""roles"": [], - ""isBanned"": false, - ""banReason"": null, - ""server"": { - ""id"": ""spb"", - ""name"": ""СПб"", - ""icon"": 1, - ""hasSite"": true, - ""economy"": { - ""campaignPrice"": 32, - ""pinPrice"": 0, - ""adPrice"": 32 - } - } - }, - { - ""id"": ""96a89c09-63a1-44e9-9e10-abbf9f78483c"", - ""serverId"": ""pl"", - ""roles"": [ - ""mapmaker"" - ], - ""isBanned"": false, - ""banReason"": null, - ""server"": { - ""id"": ""pl"", - ""name"": ""PoopLand"", - ""icon"": 4, - ""hasSite"": true, - ""economy"": { - ""campaignPrice"": 32, - ""pinPrice"": 0, - ""adPrice"": 32 - } - } - } - ], - ""bedrockUsername"": ""YaFlay"", - ""username"": ""YaFlay"", - ""hasTOTP"": false -}"; - var content = new StringContent(ok) ; - await client.PostAsync("auth/refresh_token", content); foreach (var report in allReports) @@ -159,11 +102,9 @@ namespace DiscordApp.Discord.Commands { try { - var request = await client.GetAsync($"pl/accounts/{employee.Key}"); - Console.WriteLine(request.Content.ReadAsStringAsync().Result); - JsonNode response = await request.Content.ReadFromJsonAsync(); - - await Startup.sp.CreateTransaction(response["cardsOwned"][0]["number"].ToString(), employee.Value, $"zp {employee.Key}"); + + Startup startup = new (); + await Startup.sp.CreateTransaction(startup.getUserData(employee.Key).Result.cardsOwned.First().number, employee.Value, $"zp {employee.Key}"); await Console.Out.WriteLineAsync($"{employee.Key}, {employee.Value}"); allCount += employee.Value; } diff --git a/Justice/Interactions/PassportInteraction.cs b/Justice/Interactions/PassportInteraction.cs index afee20e..22182a7 100644 --- a/Justice/Interactions/PassportInteraction.cs +++ b/Justice/Interactions/PassportInteraction.cs @@ -6,6 +6,10 @@ using DiscordApp.Enums; using spworlds.Types; using DiscordApp.Justice.Modals; using System; +using System.Text.Json.Nodes; +using Microsoft.AspNetCore.Hosting; +using DiscordApp.Types; +using Newtonsoft.Json; namespace DiscordApp.Justice.Interactions { @@ -31,7 +35,7 @@ namespace DiscordApp.Justice.Interactions await DeferAsync(true); int passportId; - int.TryParse(modal.Id, out passportId); + bool tryToParsePassport = int.TryParse(modal.Id, out passportId); bool recreatePassport = modal.IsNewPassport == 1; if (recreatePassport) { @@ -39,13 +43,17 @@ namespace DiscordApp.Justice.Interactions } else { - if (passportId == null) { await FollowupAsync("Айди паспорта устаревший, используйте кнопку \"Создать новый\" для создания паспорта", ephemeral: true); return; } + if (!tryToParsePassport) { await FollowupAsync("Айди паспорта устаревший, используйте кнопку \"Создать новый\" для создания паспорта", ephemeral: true); return; } var passport = Startup.appDbContext.Passport.Where(x => x.Id == passportId).FirstOrDefault(); if (passport == null) { await FollowupAsync("ID паспорта не правильный, или не существует.", ephemeral: true); return; } + Startup startup = new(); SocketGuildUser user = Context.Guild.GetUser(Context.User.Id); Random random = new(); - User spUser = await User.CreateUser(passport.Applicant); + var spUser = await spworlds.Types.User.CreateUser(passport.Applicant); + var spUserData = await startup.getUserData(passport.Applicant); + string cityName; + string cardNumber; DateTimeOffset toTime; if (DateTimeOffset.FromUnixTimeSeconds(passport.birthDate).AddDays(14) < DateTimeOffset.Now) { @@ -56,6 +64,23 @@ namespace DiscordApp.Justice.Interactions toTime = DateTime.Now.AddDays(14); } + if (spUserData.city != null) + { + cityName = spUserData.city.name; + } + else + { + cityName = "Спавн"; + } + if (spUserData.cardsOwned.Count > 0) + { + cardNumber = spUserData.cardsOwned.First().number; + } + else + { + cardNumber = "Отсутствует"; + } + int id = random.Next(00001, 99999); while (id.ToString().Length < 5) { id = random.Next(00001, 99999); } long unixTime = toTime.ToUnixTimeSeconds(); @@ -65,15 +90,16 @@ namespace DiscordApp.Justice.Interactions passport.Date = nowUnixTime; var passportData = new EmbedFieldBuilder() - .WithName("Данные паспорта:") - .WithValue(@$" + .WithName("Данные паспорта:") + .WithValue(@$" Имя: {passport.Applicant} РП Имя: {passport.RpName} Айди: {id} Благотворитель: {passport.Support} Гендер: {passport.Gender} -Дата рождения: ") - .WithIsInline(true); +Дата рождения: +Город: {cityName} +Номер карты: {cardNumber}").WithIsInline(true); var author = new EmbedAuthorBuilder() .WithName(user.DisplayName) @@ -121,23 +147,25 @@ namespace DiscordApp.Justice.Interactions string name = modal.NickName; string RpName = modal.RPName; int supporterInt = modal.Supporter; - string birthday = modal.Birthday; string gender = modal.Gender; + Startup startup = new (); + SocketGuildUser user = Context.Guild.GetUser(Context.User.Id); Supporter supporter; Random random = new(); - User spUser = await User.CreateUser(name); - + spworlds.Types.User spUser = await spworlds.Types.User.CreateUser(name); + Root spUserData = await startup.getUserData(name); DateTimeOffset toTime; DateOnly birthDate; int id = random.Next(00001, 99999); while (id.ToString().Length < 5) { id = random.Next(00001, 99999); } long unixBirthDateTime; - + string cityName; + string cardNumber; try { - birthDate = DateOnly.Parse(birthday); + birthDate = DateOnly.FromDateTime(spUserData.createdAt); unixBirthDateTime = DateTimeOffset.Parse(birthDate.ToString()).ToUnixTimeSeconds(); if (birthDate.AddDays(14) < DateOnly.FromDateTime(DateTime.Now)) { @@ -151,7 +179,7 @@ namespace DiscordApp.Justice.Interactions } catch { - await FollowupAsync($"Возможно, с датой `{modal.Birthday}` какая-то ошибка, попробуйте такой тип: 14.02.2023", ephemeral: true); + await FollowupAsync($"Сайт вернул очень странную дату... Попробуйте позже, и напишите об этом <@945317832290336798>", ephemeral: true); return; } @@ -174,6 +202,22 @@ namespace DiscordApp.Justice.Interactions await FollowupAsync("Неправильно указан уровень благотворителя. Используйте числа от 0 до 3(в зависимости от уровня)", ephemeral: true); return; } + if (spUserData.city != null) + { + cityName = spUserData.city.name; + } + else + { + cityName = "Спавн"; + } + if (spUserData.cardsOwned.Count > 0) + { + cardNumber = spUserData.cardsOwned.First().number; + } + else + { + cardNumber = "Отсутствует"; + } Passport passport = new() { @@ -189,7 +233,7 @@ namespace DiscordApp.Justice.Interactions Reports report = new() { Employee = Startup.sp.GetUser(Context.User.Id.ToString()).Result.Name, - type = Types.ReportTypes.editPassport + type = ReportTypes.editPassport }; await Startup.appDbContext.Reports.AddAsync(report); @@ -214,7 +258,11 @@ namespace DiscordApp.Justice.Interactions Айди: {id} Благотворитель: {passport.Support} Гендер: {passport.Gender} -Дата рождения: ").WithIsInline(true); +Дата рождения: +Город: {cityName} +Номер карты: {cardNumber}").WithIsInline(true); + + var author = new EmbedAuthorBuilder() .WithName(user.DisplayName) @@ -248,37 +296,30 @@ namespace DiscordApp.Justice.Interactions string name = modal.NickName; string RpName = modal.RPName; int supporterInt = modal.Supporter; - string birthday = modal.Birthday; + string gender = modal.Gender; + Startup startup = new(); + SocketGuildUser user = Context.Guild.GetUser(Context.User.Id); - Random random = new(); Supporter supporter; - User spUser; + Random random = new(); + spworlds.Types.User spUser = await spworlds.Types.User.CreateUser(name); + Root spUserData = await startup.getUserData(name); DateTimeOffset toTime; DateOnly birthDate; - long unixBirthDateTime; - - try - { - spUser = await User.CreateUser(name); - } - catch - { - await FollowupAsync("Игрок с таким ником не найден!", ephemeral: true); - return; - } - int id = random.Next(00001, 99999); while (id.ToString().Length < 5) { id = random.Next(00001, 99999); } - + long unixBirthDateTime; + string cityName; + string cardNumber; try { - birthDate = DateOnly.Parse(birthday); + birthDate = DateOnly.FromDateTime(spUserData.createdAt); unixBirthDateTime = DateTimeOffset.Parse(birthDate.ToString()).ToUnixTimeSeconds(); if (birthDate.AddDays(14) < DateOnly.FromDateTime(DateTime.Now)) { - await FollowupAsync($"Возможно, игрок {name} играет больше двух недель, и бесплатный паспорт ему не положен! Оформляю паспорт на два месяца...", ephemeral: true); + await FollowupAsync($"Возможно, игрок {name} больше не новичек, и бесплатный паспорт ему не положен! Оформляю паспорт на месяц...", ephemeral: true); toTime = DateTimeOffset.Now.AddMonths(2); } else @@ -288,7 +329,7 @@ namespace DiscordApp.Justice.Interactions } catch { - await FollowupAsync($"Возможно, с датой `{modal.Birthday}` какая-то ошибка, попробуйте такой тип: 14.02.2023", ephemeral: true); + await FollowupAsync($"Сайт вернул очень странную дату... Попробуйте позже, и напишите об этом <@945317832290336798>", ephemeral: true); return; } @@ -311,13 +352,29 @@ namespace DiscordApp.Justice.Interactions await FollowupAsync("Неправильно указан уровень благотворителя. Используйте числа от 0 до 3(в зависимости от уровня)", ephemeral: true); return; } + if (spUserData.city != null) + { + cityName = spUserData.city.name; + } + else + { + cityName = "Спавн"; + } + if (spUserData.cardsOwned.Count > 0) + { + cardNumber = spUserData.cardsOwned.First().number; + } + else + { + cardNumber = "Отсутствует"; + } Passport passport = new() { Employee = user.Id, RpName = RpName, Gender = gender, - Date = DateTimeOffset.Now.ToUnixTimeSeconds(), + Date = toTime.ToUnixTimeSeconds(), birthDate = unixBirthDateTime, Applicant = name, Id = id, @@ -330,8 +387,9 @@ namespace DiscordApp.Justice.Interactions while (!isUnical) { id = random.Next(00001, 99999); - passport.Id = id; while (id.ToString().Length < 5) { id = random.Next(00001, 99999); } + passport.Id = id; + Console.WriteLine(passport.Id); if (Startup.appDbContext.Passport.FindAsync(passport.Id).Result == null) { break; } } } @@ -342,9 +400,11 @@ namespace DiscordApp.Justice.Interactions Имя: {passport.Applicant} РП Имя: {passport.RpName} Айди: {id} -Благотворитель: {(int)passport.Support } +Благотворитель: {passport.Support} Гендер: {passport.Gender} -Дата рождения: ") +Дата рождения: +Город: {cityName} +Номер карты: {cardNumber}") .WithIsInline(true); var author = new EmbedAuthorBuilder() @@ -365,7 +425,7 @@ namespace DiscordApp.Justice.Interactions Reports report = new() { Employee = ((IGuildUser)Context.User).DisplayName, - type = Types.ReportTypes.NewPassport + type = ReportTypes.NewPassport }; await Startup.appDbContext.Reports.AddAsync(report); await Startup.appDbContext.Passport.AddAsync(passport); diff --git a/Justice/Modals/PassportModals.cs b/Justice/Modals/PassportModals.cs index eb1bdde..ad20c80 100644 --- a/Justice/Modals/PassportModals.cs +++ b/Justice/Modals/PassportModals.cs @@ -22,9 +22,6 @@ namespace DiscordApp.Justice.Modals [InputLabel("Пол")] [ModalTextInput("gender", TextInputStyle.Short, maxLength: 200)] public string Gender { get; set; } - [InputLabel("Дата рождения")] - [ModalTextInput("BirthDay", TextInputStyle.Short, placeholder: "16.02.2023", maxLength: 100)] - public string Birthday { get; set; } } diff --git a/Startup.cs b/Startup.cs index 9335e3e..8112ea7 100644 --- a/Startup.cs +++ b/Startup.cs @@ -5,11 +5,16 @@ using Discord.WebSocket; using DiscordApp; using DiscordApp.Auth; using DiscordApp.Database; +using DiscordApp.Types; using Microsoft.AspNetCore.Authentication; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; +using Microsoft.Extensions.Primitives; +using Newtonsoft.Json; using spworlds; using System; +using System.Net; +using System.Text.Json.Nodes; namespace DiscordApp { @@ -19,6 +24,7 @@ namespace DiscordApp public static IServiceProvider serviceProvider; public static AppDbContext appDbContext; public static SPWorlds sp; + private readonly HttpClient client; private readonly DiscordSocketConfig socketConfig = new() { GatewayIntents = GatewayIntents.All, @@ -33,9 +39,78 @@ namespace DiscordApp .Build(); string CardId = "28fd1597-05a9-4ee0-8845-16ca37135081"; string CardToken = "m+ziDmuTdFElD0vcKYnO3DS1h/9HuRGk"; + string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6Ijk0NTMxNzgzMjI5MDMzNjc5OCIsInRva2VuVmVyc2lvbiI6MCwiaXAiOiIxODUuMTA0LjExMi4xODAiLCJpYXQiOjE2OTkxOTA5MzMsImV4cCI6MTcwMTc4MjkzM30.Z9ykVYIIsN0bF0BlNV6sgwdiRu-GNx-olmKRxl6OJHk"; + var cookieContainer = new CookieContainer(); + var handler = new HttpClientHandler() { CookieContainer = cookieContainer }; + client = new(handler); + client.BaseAddress = new Uri("https://spworlds.ru/api/"); + cookieContainer.Add(client.BaseAddress, new Cookie("jeff", token)); + spwLogin(); sp = new SPWorlds(CardId, CardToken); } + public void spwLogin() + { + string ok = @"{ + ""id"": ""945317832290336798"", + ""isAdmin"": false, + ""minecraftUUID"": ""775f00d30da34275967d58cb50838b9f"", + ""accounts"": [ + { + ""id"": ""095ee127-578b-479e-90af-21b679546e09"", + ""serverId"": ""spb"", + ""roles"": [], + ""isBanned"": false, + ""banReason"": null, + ""server"": { + ""id"": ""spb"", + ""name"": ""СПб"", + ""icon"": 1, + ""hasSite"": true, + ""economy"": { + ""campaignPrice"": 32, + ""pinPrice"": 0, + ""adPrice"": 32 + } + } + }, + { + ""id"": ""96a89c09-63a1-44e9-9e10-abbf9f78483c"", + ""serverId"": ""pl"", + ""roles"": [ + ""mapmaker"" + ], + ""isBanned"": false, + ""banReason"": null, + ""server"": { + ""id"": ""pl"", + ""name"": ""PoopLand"", + ""icon"": 4, + ""hasSite"": true, + ""economy"": { + ""campaignPrice"": 32, + ""pinPrice"": 0, + ""adPrice"": 32 + } + } + } + ], + ""bedrockUsername"": ""YaFlay"", + ""username"": ""YaFlay"", + ""hasTOTP"": false +}"; + var content = new StringContent(ok); + var responseMessage = client.PostAsync("auth/refresh_token", content).Result; + Console.WriteLine(responseMessage.Content.ReadAsStringAsync().Result.ToString()); + } + public async Task getUserData(string userName) + { + var request = await client.GetAsync($"pl/accounts/{userName}"); + await Console.Out.WriteLineAsync(request.Content.ToString()); + Root response = JsonConvert.DeserializeObject(request.Content.ReadAsStringAsync().Result.ToString()); + return response; + } + public void ConfigureServices(IServiceCollection services) { services.AddControllers(); diff --git a/Types/SPUser.cs b/Types/SPUser.cs new file mode 100644 index 0000000..40ad520 --- /dev/null +++ b/Types/SPUser.cs @@ -0,0 +1,44 @@ +namespace DiscordApp.Types +{ + public class CardsOwned + { + public string name { get; set; } + public int color { get; set; } + public string number { get; set; } + public string id { get; set; } + } + + public class City + { + public Mayor mayor { get; set; } + public string name { get; set; } + public int x { get; set; } + public int z { get; set; } + } + + public class Mayor + { + public string id { get; set; } + } + + public class Root + { + public string id { get; set; } + public bool isBanned { get; set; } + public User user { get; set; } + public List roles { get; set; } + public City? city { get; set; } + public string status { get; set; } + public DateTime createdAt { get; set; } + public List cardsOwned { get; set; } + public bool isFollowed { get; set; } + public bool isFollowingYou { get; set; } + } + + public class User + { + public bool isAdmin { get; set; } + public string minecraftUUID { get; set; } + public string username { get; set; } + } +}