From dde8b38520b3c231a9047318b1c23680de09865e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=BC=D0=B8=D1=82=D1=80=D0=B8=D0=B9=20=D0=A8=D0=B8?= =?UTF-8?q?=D0=BC=D0=B0=D0=BD=D1=81=D0=BA=D0=B8=D0=B9?= Date: Thu, 9 Nov 2023 00:24:18 +0300 Subject: [PATCH] updated --- Controllers/WeatherForecastController.cs | 7 +++ Database/AppDbContext.cs | 2 + Database/Tables/Certificate.cs | 20 +++++++ DiscordApp.csproj | 1 + InteractionHandler.cs | 1 - Justice.cs | 32 +---------- Justice/Commands/Getters.cs | 31 +++++++++++ Justice/Commands/Notary.cs | 26 +++++++++ Justice/Commands/Settings.cs | 7 ++- Justice/Interactions/NotaryInteractions.cs | 35 ++++++++++++ .../Interactions/PassportGetterInteraction.cs | 55 +++++++++++++++++++ Justice/Interactions/PassportInteraction.cs | 9 ++- Justice/Modals/NotaryModals.cs | 22 ++++++++ Justice/Modals/PassportGetterModals.cs | 14 +++++ Startup.cs | 8 ++- Utilities/IdChecker.cs | 13 +++++ 16 files changed, 243 insertions(+), 40 deletions(-) create mode 100644 Database/Tables/Certificate.cs create mode 100644 Justice/Commands/Getters.cs create mode 100644 Justice/Commands/Notary.cs create mode 100644 Justice/Interactions/NotaryInteractions.cs create mode 100644 Justice/Interactions/PassportGetterInteraction.cs create mode 100644 Justice/Modals/NotaryModals.cs create mode 100644 Justice/Modals/PassportGetterModals.cs create mode 100644 Utilities/IdChecker.cs diff --git a/Controllers/WeatherForecastController.cs b/Controllers/WeatherForecastController.cs index b389f4d..170ce38 100644 --- a/Controllers/WeatherForecastController.cs +++ b/Controllers/WeatherForecastController.cs @@ -29,5 +29,12 @@ namespace DiscordApp.Controllers }) .ToArray(); } + public static async Task isAllowed(IServiceProvider services) + { + var context = services.GetRequiredService(); + if (context.HttpContext.Request.Cookies["geff"] == "ok") { return true; } + else { return false; } + + } } } \ No newline at end of file diff --git a/Database/AppDbContext.cs b/Database/AppDbContext.cs index b436da8..9dfda02 100644 --- a/Database/AppDbContext.cs +++ b/Database/AppDbContext.cs @@ -14,6 +14,8 @@ namespace DiscordApp.Database public DbSet BookPatents { get; set; } public DbSet Bizness { get; set; } public DbSet Reports { get; set; } + public DbSet Certificates { get; set; } + protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); diff --git a/Database/Tables/Certificate.cs b/Database/Tables/Certificate.cs new file mode 100644 index 0000000..875f049 --- /dev/null +++ b/Database/Tables/Certificate.cs @@ -0,0 +1,20 @@ +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; + +namespace DiscordApp.Database.Tables +{ + + [Table("Certificate", Schema = "public")] + public class Certificate + { + [Key] + public int Id { get; set; } + public string Employee { get; set; } + public Passport passport { get; set; } + public DateOnly Date { get; set; } + public string Text { get; set; } + public int DocumentId { get; set; } + + + } +} diff --git a/DiscordApp.csproj b/DiscordApp.csproj index a5fff2f..a84f35e 100644 --- a/DiscordApp.csproj +++ b/DiscordApp.csproj @@ -11,6 +11,7 @@ + diff --git a/InteractionHandler.cs b/InteractionHandler.cs index 67fc68d..9c0d533 100644 --- a/InteractionHandler.cs +++ b/InteractionHandler.cs @@ -28,7 +28,6 @@ namespace DiscordApp handler.Log += LogAsync; await handler.AddModulesAsync(Assembly.GetEntryAssembly(), services); - var guildCommand = new SlashCommandBuilder(); client.InteractionCreated += HandleInteraction; } diff --git a/Justice.cs b/Justice.cs index f956532..02fee42 100644 --- a/Justice.cs +++ b/Justice.cs @@ -29,41 +29,15 @@ namespace DiscordApp client.Log += LogAsync; client.UserJoined += Justice.Events.Events.onJoinGuild; client.MessageReceived += Justice.Events.Events.onMessageCreate; - client.Ready += onReady; + //client.Ready += onReady; await client.LoginAsync(TokenType.Bot, "MTE2NjA3OTk3NjQ0NjEwMzYwMg.GAKOIo.4af972Wh11G0EF4O5tNYb7l-vt5OwMc4HPRnjE"); await client.StartAsync(); await interactionHandler.InitializeAsync(); await Task.Delay(Timeout.Infinite); } - public async Task onReady() - { - await ChangeNicknames(); - var myTimer = new System.Timers.Timer(6 * 60 * 60 * 1000); //calculate six hours in milliseconds - myTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); - myTimer.Start(); - } - private async void OnTimedEvent(object sender, ElapsedEventArgs e) - { - Console.WriteLine("Started timer"); - await ChangeNicknames(); - } - private async Task ChangeNicknames() - { - IGuild guild = client.GetGuild(1107742957458685985); - IRole role = guild.GetRole(1136564585420304444); - var members = await guild.GetUsersAsync(); - var membersArray = members.ToArray(); - foreach (IGuildUser user in membersArray) - { - var spUser = await Startup.sp.GetUser(user.Id.ToString()); - if (spUser.IsPlayer()) - { - await user.ModifyAsync(func => { func.Nickname = spUser.Name; }); - await user.AddRoleAsync(role); - } - } - } + + private async Task LogAsync(LogMessage message) => Console.WriteLine(message.ToString()); } diff --git a/Justice/Commands/Getters.cs b/Justice/Commands/Getters.cs new file mode 100644 index 0000000..bd1d884 --- /dev/null +++ b/Justice/Commands/Getters.cs @@ -0,0 +1,31 @@ +using Discord.Interactions; +using Discord; + +namespace DiscordApp.Justice.Commands +{ + public class Getters : InteractionModuleBase + { + [SlashCommand("embed-getter-passport", "Отправляет сообщение для поиска паспорта")] + [DefaultMemberPermissions(GuildPermission.Administrator)] + public async Task getPassport() + { + await DeferAsync(true); + var embed = new EmbedBuilder() + .WithTitle("Получение информации о паспорте") + .WithDescription("Нажав на кнопку ниже вы можете получить данные о том, или ином игроке") + .WithColor(Color.DarkBlue) + .Build(); + var components = new ComponentBuilder() + .WithButton(new ButtonBuilder() + { + CustomId = "searchPassport", + Label = "Поиск паспорта", + Style = ButtonStyle.Success + }) + .Build(); + var channel = Context.Channel as ITextChannel; + await channel.SendMessageAsync(embed: embed, components: components); + await FollowupAsync("Готово!", ephemeral: true); + } + } +} diff --git a/Justice/Commands/Notary.cs b/Justice/Commands/Notary.cs new file mode 100644 index 0000000..a9eb42e --- /dev/null +++ b/Justice/Commands/Notary.cs @@ -0,0 +1,26 @@ +using Discord.Interactions; +using Discord; + +namespace DiscordApp.Justice.Commands +{ + public class Notary : InteractionModuleBase + { + [SlashCommand("notary-embed", "Отправляет сообщение с кнопками для нотариусов")] + [DefaultMemberPermissions(GuildPermission.Administrator)] + public async Task sendNotaryEmbed() + { + await DeferAsync(true); + var Embed = new EmbedBuilder() + .WithTitle("**Заверка документа**") + .WithDescription("Ниже вы можете нажать на кнопку создания ID для документа и документа заверки") + .WithColor(Color.Blue) + .Build(); + var Components = new ComponentBuilder() + .WithButton(new ButtonBuilder() { CustomId = "NewDocumentCertificate", Label = "Заверить документ", Style = ButtonStyle.Primary }) + .Build(); + await Context.Channel.SendMessageAsync(embed: Embed, components: Components); + await FollowupAsync("OK!");//, ephemeral: true); + } + + } +} diff --git a/Justice/Commands/Settings.cs b/Justice/Commands/Settings.cs index 4f68299..202e64f 100644 --- a/Justice/Commands/Settings.cs +++ b/Justice/Commands/Settings.cs @@ -98,13 +98,14 @@ namespace DiscordApp.Discord.Commands } } + Startup startup = new(); foreach (var employee in allEmployee) { try { - - Startup startup = new (); - await Startup.sp.CreateTransaction(startup.getUserData(employee.Key).Result.cardsOwned.First().number, employee.Value, $"zp {employee.Key}"); + + var userData = await startup.getUserData(employee.Key); + await Startup.sp.CreateTransaction(userData.cardsOwned.First().number, employee.Value, $"zp {employee.Key}"); await Console.Out.WriteLineAsync($"{employee.Key}, {employee.Value}"); allCount += employee.Value; } diff --git a/Justice/Interactions/NotaryInteractions.cs b/Justice/Interactions/NotaryInteractions.cs new file mode 100644 index 0000000..b184eec --- /dev/null +++ b/Justice/Interactions/NotaryInteractions.cs @@ -0,0 +1,35 @@ +using Discord.Interactions; +using DiscordApp.Justice.Modals; +using DiscordApp.Utilities; + +namespace DiscordApp.Justice.Interactions +{ + public class NotaryInteractions : InteractionModuleBase + { + [ComponentInteraction("NewDocumentCertificate")] + public async Task newCertificatedDocument() + => await Context.Interaction.RespondWithModalAsync("newCertificatedDocument"); + + [ModalInteraction("newCertificatedDocument")] + public async Task newCertificatedDocumentModal(INotaryModal modal) + { + await DeferAsync(true); + int passportId; + int documentId; + int certificateId; + Random random = new Random(); + IdChecker.IdLenghtIsLower(out certificateId); + documentId = Startup.appDbContext.Certificates.OrderBy(t => t.Id).First().Id + 1; + bool isInt = int.TryParse(modal.passportId, out passportId); + if (!isInt) + { + await FollowupAsync($"Айди паспорта еще старое, попробуй использовать другого бота.", ephemeral: true); + } + else if (Startup.appDbContext.Passport.Find(passportId) == null) + { + await FollowupAsync($"Паспорт не найден в базе данных, попробуй написать правильно", ephemeral: true); + } + + } + } +} diff --git a/Justice/Interactions/PassportGetterInteraction.cs b/Justice/Interactions/PassportGetterInteraction.cs new file mode 100644 index 0000000..eeae545 --- /dev/null +++ b/Justice/Interactions/PassportGetterInteraction.cs @@ -0,0 +1,55 @@ +using Discord; +using Discord.Interactions; +using DiscordApp.Database.Tables; +using DiscordApp.Justice.Modals; + +namespace DiscordApp.Justice.Interactions +{ + public class PassportGetterInteraction : InteractionModuleBase + { + [ComponentInteraction("searchPassport")] + public async Task searchPassportInteraction() => await RespondWithModalAsync("GetPassportModal"); + + [ModalInteraction("GetPassportModal")] + public async Task getPassportInteraction(IPassportGetter modal) + { + await DeferAsync(true); + int passportId; + Passport passport; + bool isInteger = int.TryParse(modal.passport, out passportId); + if (isInteger) + { + passport = await Startup.appDbContext.Passport.FindAsync(passportId); + } + else + { + passport = Startup.appDbContext.Passport.Where(k => k.Applicant == modal.passport).FirstOrDefault(); + } + + if (passport == null) + { + await FollowupAsync("Игрок или паспорт не найден в базе данных, попробуйте использовать старого бота.", ephemeral: true); + return; + } + var fields = new List() + { + new EmbedFieldBuilder().WithName("Никнейм").WithValue(passport.Applicant).WithIsInline(true), + new EmbedFieldBuilder().WithName("РП Имя").WithValue(passport.RpName).WithIsInline(true), + new EmbedFieldBuilder().WithName("Гендер").WithValue(passport.Gender).WithIsInline(false), + new EmbedFieldBuilder().WithName("Благотворитель").WithValue((int)passport.Support).WithIsInline(false), + new EmbedFieldBuilder().WithName("Дата рождения").WithValue($"").WithIsInline(false), + new EmbedFieldBuilder().WithName("Номер паспорта").WithValue(passport.Id).WithIsInline(true), + new EmbedFieldBuilder().WithName("Годен до").WithValue($"").WithIsInline(true), + new EmbedFieldBuilder().WithName("Паспортист").WithValue($"<@{passport.Employee}>").WithIsInline(true) + }; + var spUser = await spworlds.Types.User.CreateUser(passport.Applicant); + var embed = new EmbedBuilder() + .WithTitle("**Информация о паспорте**") + .WithFields(fields) + .WithThumbnailUrl(spUser.GetSkinPart(spworlds.Types.SkinPart.face)) + .Build(); + await FollowupAsync(embed:embed, ephemeral: true); + + } + } +} diff --git a/Justice/Interactions/PassportInteraction.cs b/Justice/Interactions/PassportInteraction.cs index 22182a7..bf64345 100644 --- a/Justice/Interactions/PassportInteraction.cs +++ b/Justice/Interactions/PassportInteraction.cs @@ -158,8 +158,8 @@ namespace DiscordApp.Justice.Interactions 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); } + int id; + Utilities.IdChecker.IdLenghtIsLower(out id); long unixBirthDateTime; string cityName; string cardNumber; @@ -242,8 +242,7 @@ namespace DiscordApp.Justice.Interactions bool isUnical = false; while (!isUnical) { - id = random.Next(00001, 99999); - while (id.ToString().Length < 5) { id = random.Next(00001, 99999); } + Utilities.IdChecker.IdLenghtIsLower(out id); passport.Id = id; Console.WriteLine(passport.Id); if (Startup.appDbContext.Passport.FindAsync(passport.Id).Result == null) { break; } @@ -256,7 +255,7 @@ namespace DiscordApp.Justice.Interactions Имя: {passport.Applicant} РП Имя: {passport.RpName} Айди: {id} -Благотворитель: {passport.Support} +Благотворитель: {(int)passport.Support} Гендер: {passport.Gender} Дата рождения: Город: {cityName} diff --git a/Justice/Modals/NotaryModals.cs b/Justice/Modals/NotaryModals.cs new file mode 100644 index 0000000..5a7edcf --- /dev/null +++ b/Justice/Modals/NotaryModals.cs @@ -0,0 +1,22 @@ +using Discord; +using Discord.Interactions; + +namespace DiscordApp.Justice.Modals +{ + public class INotaryModal : IModal + { + public string Title => "Сертификация док-ов"; + [InputLabel("ID паспорта")] + [ModalTextInput("passportId", TextInputStyle.Short, placeholder: "96534", maxLength: 10)] + public string passportId { get; set; } + + [InputLabel("Тип документа")] + [ModalTextInput("documentType", TextInputStyle.Short, placeholder: "Пользовательское соглашение", maxLength: 100)] + public string documentType { get; set; } + + [InputLabel("Текст из документа")] + [ModalTextInput("textFromDocument", TextInputStyle.Paragraph)] + public string documentText { get; set; } + + } +} diff --git a/Justice/Modals/PassportGetterModals.cs b/Justice/Modals/PassportGetterModals.cs new file mode 100644 index 0000000..3f20422 --- /dev/null +++ b/Justice/Modals/PassportGetterModals.cs @@ -0,0 +1,14 @@ +using Discord; +using Discord.Interactions; + +namespace DiscordApp.Justice.Modals +{ + public class IPassportGetter : IModal + { + public string Title => "Поиск паспорта"; + [InputLabel("Данные паспорта")] + [ModalTextInput("passport", TextInputStyle.Short, placeholder: "yawaflua или 97652", maxLength: 100)] + public string passport { get; set; } + + } +} diff --git a/Startup.cs b/Startup.cs index 8112ea7..4353080 100644 --- a/Startup.cs +++ b/Startup.cs @@ -4,8 +4,11 @@ using Discord.Interactions; using Discord.WebSocket; using DiscordApp; using DiscordApp.Auth; +using DiscordApp.Controllers; using DiscordApp.Database; using DiscordApp.Types; +using DotNetEd.CoreAdmin; +using DotNetEd.CoreAdmin.Controllers; using Microsoft.AspNetCore.Authentication; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; @@ -114,6 +117,7 @@ namespace DiscordApp public void ConfigureServices(IServiceCollection services) { services.AddControllers(); + services.AddCoreAdmin("yawaflua"); services //.AddHostedService() .AddHostedService() @@ -151,11 +155,11 @@ namespace DiscordApp c.RouteTemplate = "/swagger/v1/swagger.json"; }); } - + app.UseCoreAdminCustomAuth(k => Task.FromResult(true)); app.UseStaticFiles(); app.UseRouting(); app.UseCors(); - + app.UseCoreAdminCustomUrl("admin/private/panel"); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => diff --git a/Utilities/IdChecker.cs b/Utilities/IdChecker.cs new file mode 100644 index 0000000..5715509 --- /dev/null +++ b/Utilities/IdChecker.cs @@ -0,0 +1,13 @@ +namespace DiscordApp.Utilities +{ + public class IdChecker + { + public static void IdLenghtIsLower(out int id) + { + Random random = new(); + id = random.Next(00001, 99999); + while (id.ToString().Length < 5) { id = random.Next(00001, 99999); } + return; + } + } +}