add discord bot

change net6.0 net7.0
This commit is contained in:
Дмитрий Шиманский
2023-10-26 11:35:42 +03:00
parent 7c6fafa9e6
commit 9a8a4cad5d
35 changed files with 1132 additions and 37 deletions

View File

@@ -0,0 +1,27 @@
using Discord;
using Discord.Interactions;
namespace DiscordApp.Justice.Commands
{
public class Passports : InteractionModuleBase<SocketInteractionContext>
{
public InteractionService Commands { get; set; }
[SlashCommand("send_passport_embed", description: "Отправляет сообщение для регистрации паспортов")]
public async Task sendPassportBuilerEmbed()
{
await DeferAsync(true);
var Embed = new EmbedBuilder()
.WithTitle("**Регистрация паспорта!**")
.WithDescription("Ниже вы можете нажать на кнопку для создания темплейта паспорта!")
.WithColor(Color.Blue)
.Build();
var Components = new ComponentBuilder()
.WithButton(new ButtonBuilder() { CustomId = "newPassport", Label = "Новый паспорт", Style = ButtonStyle.Primary })
.WithButton(new ButtonBuilder() { CustomId = "reworkPassport", Label = "Замена паспорта", Style = ButtonStyle.Primary })
.Build();
await Context.Channel.SendMessageAsync(embed: Embed, components: Components);
await FollowupAsync("OK!");//, ephemeral: true);
}
}
}

View File

@@ -0,0 +1,94 @@
using Discord;
using Discord.Interactions;
using Discord.WebSocket;
using DiscordApp.Database;
using DiscordApp.Database.Tables;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
namespace DiscordApp.Discord.Commands
{
public class AdminCommands : InteractionModuleBase<SocketInteractionContext>
{
public InteractionService Commands { get; set; }
[SlashCommand("branches", "Настройка автоветок")]
[DefaultMemberPermissions(GuildPermission.Administrator)]
public async Task addAutoBranches(IChannel channel, string branchName = "Обсуждение")
{
await RespondAsync($"Автоветки для канала {channel.Name} настроены", ephemeral: true);
Autobranches autobranches = new()
{
ChannelId = channel.Id,
BranchName = branchName
};
Startup.appDbContext.Autobranches.Add(autobranches);
}
[SlashCommand("emotes", "Настройка автоэмоций")]
[DefaultMemberPermissions(GuildPermission.Administrator)]
public async Task addAutoReact(string emote, IChannel channel)
{
var emotes = Emote.Parse(emote);
await RespondAsync($"Автореакция {emotes.Url} для канала {channel.Name} настроены", ephemeral: true);
Autoreactions autoreactions = new()
{
ChannelId = channel.Id,
EmoteId = emotes.ToString()
};
Startup.appDbContext.Autoreactions.Add(autoreactions);
}
[SlashCommand("embed", "Отправить эмбед")]
[DefaultMemberPermissions(GuildPermission.Administrator)]
public async Task sendAsEmbed(string description, string? title = null, string? footer = null, IAttachment? attachment = null)
{
var author = new EmbedAuthorBuilder()
.WithName(Context.User.GlobalName)
.WithIconUrl(Context.User.GetAvatarUrl())
.WithUrl("https://yaflay.ru/");
var embed = new EmbedBuilder()
.WithTitle(title)
.WithDescription(description)
.WithFooter(footer)
.WithColor(5793266)
.WithAuthor(author)
.WithImageUrl(attachment?.Url)
.Build();
await DeferAsync(true);
await FollowupAsync("Готово!", ephemeral: true);
await Context.Channel.SendMessageAsync(embed: embed);
}
[SlashCommand("verification", "Отправляет сообщение верификации")]
[DefaultMemberPermissions(GuildPermission.Administrator)]
public async Task sendVerificationEmbed()
{
await DeferAsync(true);
var embed = new EmbedBuilder()
.WithTitle("**Верификация игроков**")
.WithDescription($"Если что-то случилось, и вам не выдается роль <@&1165687128366268511>, то нажмите на кнопку ниже!")
.WithImageUrl("")
.WithColor(Color.Blue)
.Build();
var components = new ComponentBuilder()
.WithButton(
new ButtonBuilder()
.WithLabel("Верификация")
.WithCustomId("UserVerification")
.WithStyle(ButtonStyle.Success)
)
.Build();
await Context.Channel.SendMessageAsync(embed: embed, components: components);
await FollowupAsync("Ok", ephemeral: true);
}
// ReplyAsync is a method on ModuleBase
}
}

57
Justice/Events/Events.cs Normal file
View File

@@ -0,0 +1,57 @@
using Discord;
using Discord.Commands;
using Discord.Interactions;
using Discord.WebSocket;
using DiscordApp;
using DiscordApp.Database.Tables;
using Microsoft.EntityFrameworkCore;
using spworlds;
using spworlds.Types;
using System.Runtime.InteropServices;
namespace DiscordApp.Justice.Events
{
public class Events
{
public static async Task onJoinGuild(SocketGuildUser socketUser)
{
try
{
User SpwUser = await Startup.sp.GetUser(socketUser.Id.ToString());
if (SpwUser.IsPlayer())
{
IRole role;
if (socketUser.Guild.Id == 1165687128366268506) { role = socketUser.Guild.GetRole(1165687128366268511); }
else if (socketUser.Guild.Id == 1107742957458685985) { role = socketUser.Guild.GetRole(1136564585420304444); }
else { return; }
await socketUser.AddRoleAsync(role);
await socketUser.ModifyAsync(func =>
{
func.Nickname = SpwUser.Name;
});
}
}
catch (Exception e) { await Console.Out.WriteLineAsync($"User {socketUser.DisplayName} not found as player!"); }
}
public static async Task onMessageCreate(SocketMessage message)
{
/**
var autoBranchesDatabase = await Startup.appDbContext.Autobranches.FindAsync(message.Channel.Id);
var autoReactDatabase = await Startup.appDbContext.Autoreactions.ForEachAsync(s => s.ChannelId == message.Channel.Id);
if (autoBranchesDatabase != null)
{
await ((ITextChannel)message.Channel).CreateThreadAsync(autoBranchesDatabase.BranchName);
}
if (autoReactDatabase != false)
{
foreach (Autoreactions autoreaction in autoReactDatabase)
{
var Emoji = Emote.Parse(autoreaction.EmoteId);
await message.AddReactionAsync(Emoji);
}
}
**/
}
}
}

View File

@@ -0,0 +1,162 @@
using Discord;
using Discord.Interactions;
using Discord.Rest;
using Discord.WebSocket;
using DiscordApp.Database.Tables;
using DiscordApp.Enums;
using Microsoft.EntityFrameworkCore;
using spworlds.Types;
using System.Globalization;
using System.IO;
using System.Xml;
namespace DiscordApp.Justice.Interactions
{
public class PassportInteraction : InteractionModuleBase<SocketInteractionContext>
{
[ComponentInteraction("newPassport")]
public async Task AplyWork()
=> await Context.Interaction.RespondWithModalAsync<NewPassportModal>("passportModal");
[ModalInteraction("passportModal")]
public async Task createPassportInteraction(NewPassportModal modal)
{
await DeferAsync(true);
string name = modal.NickName;
string RpName = modal.RPName;
int supporterInt = modal.Supporter;
string birthday = modal.Birthday;
string gender = modal.Gender;
SocketGuildUser user = Context.Guild.GetUser(Context.User.Id);
Supporter supporter;
Random random = new();
spworlds.Types.User spUser = await spworlds.Types.User.CreateUser(name);
DateTimeOffset toTime = DateTime.Now.AddDays(14);
DateTime birthDate;
int id = random.Next(00001, 99999);
long unixTime;
try
{
birthDate = DateTime.Parse(birthday);
unixTime = ((DateTimeOffset)birthDate).ToUnixTimeSeconds();
if (birthDate.AddDays(14) < DateTime.Now)
{
await FollowupAsync($"Возможно, игрок {name} больше не новичек, и бесплатный паспорт ему не положен!", ephemeral: true);
}
}
catch
{
await FollowupAsync($"Возможно, с датой {modal.Birthday} какая-то ошибка, попробуйте такой тип: 14.02.2023", ephemeral: true);
return;
}
switch (supporterInt)
{
case 0:
supporter = Supporter.None;
break;
case 1:
supporter = Supporter.FirstLvl;
break;
case 2:
supporter = Supporter.SecondLvl;
break;
case 3:
supporter = Supporter.ThirdLvl;
break;
default:
await FollowupAsync("Неправильно указан уровень благотворителя. Используйте числа от 0 до 3(в зависимости от уровня)", ephemeral: true);
return;
}
var passportData = new EmbedFieldBuilder()
.WithName("Данные паспорта:")
.WithValue($"```\nИмя: {name}\nРП Имя: {RpName}\nАйди: {id}\nБлаготворитель: {supporter}\nГендер: {gender}\nДата рождения: {birthDate.ToShortDateString()}```")
.WithIsInline(true);
var author = new EmbedAuthorBuilder()
.WithName(user.DisplayName)
.WithIconUrl(user.GetDisplayAvatarUrl());
var faceUrl = "https://visage.surgeplay.com/face/64/" + spUser.Uuid;
Console.WriteLine(faceUrl);
var embed = new EmbedBuilder()
.WithTitle("**Новый паспорт**")
.AddField(passportData)
.AddField(new EmbedFieldBuilder().WithName("Составитель: ").WithValue(user.GlobalName).WithIsInline(true))
.AddField(new EmbedFieldBuilder().WithName("Доступен до: ").WithValue($"<t:{toTime.ToUnixTimeSeconds()}:D>").WithIsInline(true))
.WithThumbnailUrl(faceUrl)
.WithColor(Color.DarkBlue)
.WithAuthor(author)
.WithTimestamp(toTime)
.Build();
Passport passport = new()
{
Employee = user.Id,
RpName = RpName,
Gender = gender,
Date = unixTime,
Applicant = name,
Id = id,
Support = supporter
};
if (Startup.appDbContext.Passport.FindAsync(passport.Id).Result != null)
{
bool isUnical = false;
while (!isUnical)
{
id = random.Next(00001, 99999);
passport.Id = id;
Console.WriteLine(passport.Id);
if (Startup.appDbContext.Passport.FindAsync(passport.Id).Result == null) { break; }
}
}
await Startup.appDbContext.Passport.AddAsync(passport);
await Startup.appDbContext.SaveChangesAsync();
await FollowupAsync($"ID для паспорта: {id}", embed: embed, ephemeral: true);
var channel = Context.Guild.GetChannel(1108006685626355733) as ITextChannel;
var message = await channel.SendMessageAsync(embed: embed);
}
}
public class NewPassportModal : IModal
{
public string Title => "Создание паспорта";
[InputLabel("Ник игрока")]
[ModalTextInput("nickname", TextInputStyle.Short, placeholder: "YaFlay", maxLength: 90)]
public string NickName { get; set; }
[InputLabel("Благотворитель")]
[ModalTextInput("Supporter", TextInputStyle.Short, placeholder: "1", maxLength: 5)]
public int Supporter { get; set; }
[InputLabel("РП Имя")]
[ModalTextInput("rolePlayName", TextInputStyle.Short, placeholder: "Олег Бебров", maxLength: 200)]
public string RPName { get; set; }
[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; }
}
}

View File

@@ -0,0 +1,33 @@
using Discord.Interactions;
namespace DiscordApp.Justice.Interactions
{
public class VerificateInteraction : InteractionModuleBase<SocketInteractionContext>
{
[ComponentInteraction("UserVerification")]
public async Task userVerificationInteraction()
{
await DeferAsync(true);
try
{
var user = await Startup.sp.GetUser(Context.User.Id.ToString());
if (user.IsPlayer())
{
await FollowupAsync("Готово!", ephemeral: true);
var guildUser = Context.Guild.GetUser(Context.User.Id);
await guildUser.AddRoleAsync(1165687128366268511);
await guildUser.ModifyAsync(func =>
{
func.Nickname = user.Name;
});
}
}
catch (Exception ex)
{
await Console.Out.WriteLineAsync($"User {Context.User.GlobalName} not found! Error: {ex.Message}");
await FollowupAsync("Какая-то ошибка, возможно вы не игрок пупленда...", ephemeral: true);
}
}
}
}

44
Justice/SelfBot.cs Normal file
View File

@@ -0,0 +1,44 @@
using Discord;
using Discord.WebSocket;
using DiscordApp;
namespace DiscordApp.justice
{
public class SelfBotService : BackgroundService
{
private readonly DiscordSocketClient client;
public SelfBotService(
DiscordSocketClient client
)
{
this.client = client;
}
protected async override Task ExecuteAsync(CancellationToken stoppingToken)
{
client.Log += LogAsync;
await client.LoginAsync(TokenType.Bearer, "MTAyNDA2MzQ2MzQ4NTYwNzk3Nw.G7rg3W.NiVYFH9x8V2y2eKP7b9XP5th7Of1XhF2WFVF_M");
await client.StartAsync();
await Task.Delay(Timeout.Infinite);
}
public async Task<IGuildUser> GetUser(string name)
{
var guild = client.GetGuild(995379037407027270);
var users = await guild.GetUsersAsync().FlattenAsync();
foreach (IGuildUser user in users)
{
if (user.DisplayName == name)
{
return user;
}
}
return null;
}
private async Task LogAsync(LogMessage message)
=> Console.WriteLine(message.ToString());
}
}