add auto-getter from spworlds.ru user data

This commit is contained in:
Дмитрий Шиманский
2023-11-07 00:09:51 +03:00
parent 7f8aebac5f
commit 0b218a4c6d
5 changed files with 221 additions and 104 deletions

View File

@@ -84,63 +84,6 @@ namespace DiscordApp.Discord.Commands
int allCount = 0; int allCount = 0;
var allReports = Startup.appDbContext.Reports.ToArray(); var allReports = Startup.appDbContext.Reports.ToArray();
var allEmployee = new Dictionary<string, int>(); var allEmployee = new Dictionary<string, int>();
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) foreach (var report in allReports)
@@ -159,11 +102,9 @@ namespace DiscordApp.Discord.Commands
{ {
try try
{ {
var request = await client.GetAsync($"pl/accounts/{employee.Key}");
Console.WriteLine(request.Content.ReadAsStringAsync().Result); Startup startup = new ();
JsonNode response = await request.Content.ReadFromJsonAsync<JsonNode>(); await Startup.sp.CreateTransaction(startup.getUserData(employee.Key).Result.cardsOwned.First().number, employee.Value, $"zp {employee.Key}");
await Startup.sp.CreateTransaction(response["cardsOwned"][0]["number"].ToString(), employee.Value, $"zp {employee.Key}");
await Console.Out.WriteLineAsync($"{employee.Key}, {employee.Value}"); await Console.Out.WriteLineAsync($"{employee.Key}, {employee.Value}");
allCount += employee.Value; allCount += employee.Value;
} }

View File

@@ -6,6 +6,10 @@ using DiscordApp.Enums;
using spworlds.Types; using spworlds.Types;
using DiscordApp.Justice.Modals; using DiscordApp.Justice.Modals;
using System; using System;
using System.Text.Json.Nodes;
using Microsoft.AspNetCore.Hosting;
using DiscordApp.Types;
using Newtonsoft.Json;
namespace DiscordApp.Justice.Interactions namespace DiscordApp.Justice.Interactions
{ {
@@ -31,7 +35,7 @@ namespace DiscordApp.Justice.Interactions
await DeferAsync(true); await DeferAsync(true);
int passportId; int passportId;
int.TryParse(modal.Id, out passportId); bool tryToParsePassport = int.TryParse(modal.Id, out passportId);
bool recreatePassport = modal.IsNewPassport == 1; bool recreatePassport = modal.IsNewPassport == 1;
if (recreatePassport) if (recreatePassport)
{ {
@@ -39,13 +43,17 @@ namespace DiscordApp.Justice.Interactions
} }
else 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(); var passport = Startup.appDbContext.Passport.Where(x => x.Id == passportId).FirstOrDefault();
if (passport == null) { await FollowupAsync("ID паспорта не правильный, или не существует.", ephemeral: true); return; } if (passport == null) { await FollowupAsync("ID паспорта не правильный, или не существует.", ephemeral: true); return; }
Startup startup = new();
SocketGuildUser user = Context.Guild.GetUser(Context.User.Id); SocketGuildUser user = Context.Guild.GetUser(Context.User.Id);
Random random = new(); 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; DateTimeOffset toTime;
if (DateTimeOffset.FromUnixTimeSeconds(passport.birthDate).AddDays(14) < DateTimeOffset.Now) if (DateTimeOffset.FromUnixTimeSeconds(passport.birthDate).AddDays(14) < DateTimeOffset.Now)
{ {
@@ -56,6 +64,23 @@ namespace DiscordApp.Justice.Interactions
toTime = DateTime.Now.AddDays(14); 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); int id = random.Next(00001, 99999);
while (id.ToString().Length < 5) { id = random.Next(00001, 99999); } while (id.ToString().Length < 5) { id = random.Next(00001, 99999); }
long unixTime = toTime.ToUnixTimeSeconds(); long unixTime = toTime.ToUnixTimeSeconds();
@@ -65,15 +90,16 @@ namespace DiscordApp.Justice.Interactions
passport.Date = nowUnixTime; passport.Date = nowUnixTime;
var passportData = new EmbedFieldBuilder() var passportData = new EmbedFieldBuilder()
.WithName("Данные паспорта:") .WithName("Данные паспорта:")
.WithValue(@$" .WithValue(@$"
Имя: {passport.Applicant} Имя: {passport.Applicant}
РП Имя: {passport.RpName} РП Имя: {passport.RpName}
Айди: {id} Айди: {id}
Благотворитель: {passport.Support} Благотворитель: {passport.Support}
Гендер: {passport.Gender} Гендер: {passport.Gender}
Дата рождения: <t:{passport.birthDate}:D>") Дата рождения: <t:{passport.birthDate}:D>
.WithIsInline(true); Город: {cityName}
Номер карты: {cardNumber}").WithIsInline(true);
var author = new EmbedAuthorBuilder() var author = new EmbedAuthorBuilder()
.WithName(user.DisplayName) .WithName(user.DisplayName)
@@ -121,23 +147,25 @@ namespace DiscordApp.Justice.Interactions
string name = modal.NickName; string name = modal.NickName;
string RpName = modal.RPName; string RpName = modal.RPName;
int supporterInt = modal.Supporter; int supporterInt = modal.Supporter;
string birthday = modal.Birthday;
string gender = modal.Gender; string gender = modal.Gender;
Startup startup = new ();
SocketGuildUser user = Context.Guild.GetUser(Context.User.Id); SocketGuildUser user = Context.Guild.GetUser(Context.User.Id);
Supporter supporter; Supporter supporter;
Random random = new(); 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; DateTimeOffset toTime;
DateOnly birthDate; DateOnly birthDate;
int id = random.Next(00001, 99999); int id = random.Next(00001, 99999);
while (id.ToString().Length < 5) { id = random.Next(00001, 99999); } while (id.ToString().Length < 5) { id = random.Next(00001, 99999); }
long unixBirthDateTime; long unixBirthDateTime;
string cityName;
string cardNumber;
try try
{ {
birthDate = DateOnly.Parse(birthday); birthDate = DateOnly.FromDateTime(spUserData.createdAt);
unixBirthDateTime = DateTimeOffset.Parse(birthDate.ToString()).ToUnixTimeSeconds(); unixBirthDateTime = DateTimeOffset.Parse(birthDate.ToString()).ToUnixTimeSeconds();
if (birthDate.AddDays(14) < DateOnly.FromDateTime(DateTime.Now)) if (birthDate.AddDays(14) < DateOnly.FromDateTime(DateTime.Now))
{ {
@@ -151,7 +179,7 @@ namespace DiscordApp.Justice.Interactions
} }
catch catch
{ {
await FollowupAsync($"Возможно, с датой `{modal.Birthday}` какая-то ошибка, попробуйте такой тип: 14.02.2023", ephemeral: true); await FollowupAsync($"Сайт вернул очень странную дату... Попробуйте позже, и напишите об этом <@945317832290336798>", ephemeral: true);
return; return;
} }
@@ -174,6 +202,22 @@ namespace DiscordApp.Justice.Interactions
await FollowupAsync("Неправильно указан уровень благотворителя. Используйте числа от 0 до 3(в зависимости от уровня)", ephemeral: true); await FollowupAsync("Неправильно указан уровень благотворителя. Используйте числа от 0 до 3(в зависимости от уровня)", ephemeral: true);
return; 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() Passport passport = new()
{ {
@@ -189,7 +233,7 @@ namespace DiscordApp.Justice.Interactions
Reports report = new() Reports report = new()
{ {
Employee = Startup.sp.GetUser(Context.User.Id.ToString()).Result.Name, Employee = Startup.sp.GetUser(Context.User.Id.ToString()).Result.Name,
type = Types.ReportTypes.editPassport type = ReportTypes.editPassport
}; };
await Startup.appDbContext.Reports.AddAsync(report); await Startup.appDbContext.Reports.AddAsync(report);
@@ -214,7 +258,11 @@ namespace DiscordApp.Justice.Interactions
Айди: {id} Айди: {id}
Благотворитель: {passport.Support} Благотворитель: {passport.Support}
Гендер: {passport.Gender} Гендер: {passport.Gender}
Дата рождения: <t:{passport.birthDate}:D>").WithIsInline(true); Дата рождения: <t:{passport.birthDate}:D>
Город: {cityName}
Номер карты: {cardNumber}").WithIsInline(true);
var author = new EmbedAuthorBuilder() var author = new EmbedAuthorBuilder()
.WithName(user.DisplayName) .WithName(user.DisplayName)
@@ -248,37 +296,30 @@ namespace DiscordApp.Justice.Interactions
string name = modal.NickName; string name = modal.NickName;
string RpName = modal.RPName; string RpName = modal.RPName;
int supporterInt = modal.Supporter; int supporterInt = modal.Supporter;
string birthday = modal.Birthday;
string gender = modal.Gender; string gender = modal.Gender;
Startup startup = new();
SocketGuildUser user = Context.Guild.GetUser(Context.User.Id); SocketGuildUser user = Context.Guild.GetUser(Context.User.Id);
Random random = new();
Supporter supporter; 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; DateTimeOffset toTime;
DateOnly birthDate; DateOnly birthDate;
long unixBirthDateTime;
try
{
spUser = await User.CreateUser(name);
}
catch
{
await FollowupAsync("Игрок с таким ником не найден!", ephemeral: true);
return;
}
int id = random.Next(00001, 99999); int id = random.Next(00001, 99999);
while (id.ToString().Length < 5) { id = random.Next(00001, 99999); } while (id.ToString().Length < 5) { id = random.Next(00001, 99999); }
long unixBirthDateTime;
string cityName;
string cardNumber;
try try
{ {
birthDate = DateOnly.Parse(birthday); birthDate = DateOnly.FromDateTime(spUserData.createdAt);
unixBirthDateTime = DateTimeOffset.Parse(birthDate.ToString()).ToUnixTimeSeconds(); unixBirthDateTime = DateTimeOffset.Parse(birthDate.ToString()).ToUnixTimeSeconds();
if (birthDate.AddDays(14) < DateOnly.FromDateTime(DateTime.Now)) if (birthDate.AddDays(14) < DateOnly.FromDateTime(DateTime.Now))
{ {
await FollowupAsync($"Возможно, игрок {name} играет больше двух недель, и бесплатный паспорт ему не положен! Оформляю паспорт на два месяца...", ephemeral: true); await FollowupAsync($"Возможно, игрок {name} больше не новичек, и бесплатный паспорт ему не положен! Оформляю паспорт на месяц...", ephemeral: true);
toTime = DateTimeOffset.Now.AddMonths(2); toTime = DateTimeOffset.Now.AddMonths(2);
} }
else else
@@ -288,7 +329,7 @@ namespace DiscordApp.Justice.Interactions
} }
catch catch
{ {
await FollowupAsync($"Возможно, с датой `{modal.Birthday}` какая-то ошибка, попробуйте такой тип: 14.02.2023", ephemeral: true); await FollowupAsync($"Сайт вернул очень странную дату... Попробуйте позже, и напишите об этом <@945317832290336798>", ephemeral: true);
return; return;
} }
@@ -311,13 +352,29 @@ namespace DiscordApp.Justice.Interactions
await FollowupAsync("Неправильно указан уровень благотворителя. Используйте числа от 0 до 3(в зависимости от уровня)", ephemeral: true); await FollowupAsync("Неправильно указан уровень благотворителя. Используйте числа от 0 до 3(в зависимости от уровня)", ephemeral: true);
return; 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() Passport passport = new()
{ {
Employee = user.Id, Employee = user.Id,
RpName = RpName, RpName = RpName,
Gender = gender, Gender = gender,
Date = DateTimeOffset.Now.ToUnixTimeSeconds(), Date = toTime.ToUnixTimeSeconds(),
birthDate = unixBirthDateTime, birthDate = unixBirthDateTime,
Applicant = name, Applicant = name,
Id = id, Id = id,
@@ -330,8 +387,9 @@ namespace DiscordApp.Justice.Interactions
while (!isUnical) while (!isUnical)
{ {
id = random.Next(00001, 99999); id = random.Next(00001, 99999);
passport.Id = id;
while (id.ToString().Length < 5) { id = random.Next(00001, 99999); } 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; } if (Startup.appDbContext.Passport.FindAsync(passport.Id).Result == null) { break; }
} }
} }
@@ -342,9 +400,11 @@ namespace DiscordApp.Justice.Interactions
Имя: {passport.Applicant} Имя: {passport.Applicant}
РП Имя: {passport.RpName} РП Имя: {passport.RpName}
Айди: {id} Айди: {id}
Благотворитель: {(int)passport.Support } Благотворитель: {passport.Support}
Гендер: {passport.Gender} Гендер: {passport.Gender}
Дата рождения: <t:{passport.birthDate}:D>") Дата рождения: <t:{passport.birthDate}:D>
Город: {cityName}
Номер карты: {cardNumber}")
.WithIsInline(true); .WithIsInline(true);
var author = new EmbedAuthorBuilder() var author = new EmbedAuthorBuilder()
@@ -365,7 +425,7 @@ namespace DiscordApp.Justice.Interactions
Reports report = new() Reports report = new()
{ {
Employee = ((IGuildUser)Context.User).DisplayName, Employee = ((IGuildUser)Context.User).DisplayName,
type = Types.ReportTypes.NewPassport type = ReportTypes.NewPassport
}; };
await Startup.appDbContext.Reports.AddAsync(report); await Startup.appDbContext.Reports.AddAsync(report);
await Startup.appDbContext.Passport.AddAsync(passport); await Startup.appDbContext.Passport.AddAsync(passport);

View File

@@ -22,9 +22,6 @@ namespace DiscordApp.Justice.Modals
[InputLabel("Пол")] [InputLabel("Пол")]
[ModalTextInput("gender", TextInputStyle.Short, maxLength: 200)] [ModalTextInput("gender", TextInputStyle.Short, maxLength: 200)]
public string Gender { get; set; } public string Gender { get; set; }
[InputLabel("Дата рождения")]
[ModalTextInput("BirthDay", TextInputStyle.Short, placeholder: "16.02.2023", maxLength: 100)]
public string Birthday { get; set; }
} }

View File

@@ -5,11 +5,16 @@ using Discord.WebSocket;
using DiscordApp; using DiscordApp;
using DiscordApp.Auth; using DiscordApp.Auth;
using DiscordApp.Database; using DiscordApp.Database;
using DiscordApp.Types;
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design; using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using spworlds; using spworlds;
using System; using System;
using System.Net;
using System.Text.Json.Nodes;
namespace DiscordApp namespace DiscordApp
{ {
@@ -19,6 +24,7 @@ namespace DiscordApp
public static IServiceProvider serviceProvider; public static IServiceProvider serviceProvider;
public static AppDbContext appDbContext; public static AppDbContext appDbContext;
public static SPWorlds sp; public static SPWorlds sp;
private readonly HttpClient client;
private readonly DiscordSocketConfig socketConfig = new() private readonly DiscordSocketConfig socketConfig = new()
{ {
GatewayIntents = GatewayIntents.All, GatewayIntents = GatewayIntents.All,
@@ -33,9 +39,78 @@ namespace DiscordApp
.Build(); .Build();
string CardId = "28fd1597-05a9-4ee0-8845-16ca37135081"; string CardId = "28fd1597-05a9-4ee0-8845-16ca37135081";
string CardToken = "m+ziDmuTdFElD0vcKYnO3DS1h/9HuRGk"; 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); 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<Root> getUserData(string userName)
{
var request = await client.GetAsync($"pl/accounts/{userName}");
await Console.Out.WriteLineAsync(request.Content.ToString());
Root response = JsonConvert.DeserializeObject<Root>(request.Content.ReadAsStringAsync().Result.ToString());
return response;
}
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
services.AddControllers(); services.AddControllers();

44
Types/SPUser.cs Normal file
View File

@@ -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<string> roles { get; set; }
public City? city { get; set; }
public string status { get; set; }
public DateTime createdAt { get; set; }
public List<CardsOwned> 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; }
}
}