Skip to content

Commit

Permalink
Permission system, URL handling and more!
Browse files Browse the repository at this point in the history
  • Loading branch information
LaineZ committed Oct 18, 2024
1 parent fe60c90 commit ac9b5a2
Show file tree
Hide file tree
Showing 17 changed files with 307 additions and 154 deletions.
4 changes: 2 additions & 2 deletions fs24bot3/Backend/Discord.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ private async Task MessageCreated(DiscordClient client, MessageCreateEventArgs a

var msg = new MessageGeneric(args.Message.Content, args.Channel.Id.ToString(), user, messageKind);

if (!msg.Sender.UserIsIgnored() && !args.Message.Author.IsBot)
if (!msg.Sender.GetPermissions().ExecuteCommands && !args.Message.Author.IsBot)
{
if (msg.Kind == MessageKind.Message) { BotContext.MessageTrigger(msg); }
await BotContext.ExecuteCommand(msg, ".");
Expand Down Expand Up @@ -141,7 +141,7 @@ public async Task SendMessage(string channel, string message)
public void Process()
{
Log.Information("Connecting to Discord...");
Task.Run(async () => { Log.Verbose("ëîõ");
Task.Run(async () => { Log.Verbose("���");
await BotClient.ConnectAsync();
BotContext.ProccessInfinite(); });
Console.ReadLine();
Expand Down
11 changes: 4 additions & 7 deletions fs24bot3/Backend/IRC.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,14 +107,11 @@ private async void Client_OnIRCMessageParsed(Client client, ParsedIRCMessage mes
{
var msg = new MessageGeneric(in message, in BotContext.Connection, Name);
var prefix = ConfigurationProvider.Config.Prefix;
var permissions = msg.Sender.GetPermissions();
BotContext.MessageTrigger(msg);

if (!msg.Sender.UserIsIgnored())
if (permissions.ExecuteCommands)
{
if (msg.Kind == MessageKind.Message)
{
BotContext.MessageTrigger(msg);
}

await BotContext.ExecuteCommand(msg, prefix);
}
}
Expand Down Expand Up @@ -199,7 +196,7 @@ public async Task SendMessage(string channel, string message)
{
await BotClient.SendAsync(new PrivMsgMessage(channel, split));
count += 1;

if (count > 4)
{
string link = await InternetServicesHelper.UploadToTrashbin(MessageHelper.StripIRC(message),
Expand Down
50 changes: 32 additions & 18 deletions fs24bot3/Bot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public class Bot
public Systems.DuckDuckGoGPT Gpt { get; }
public List<string> AcknownUsers = new List<string>();
public Profiler PProfiler { get; }

private OnMsgEvent OnMsgEvent { get; }

public enum CooldownBucketType
Expand Down Expand Up @@ -58,7 +58,7 @@ public Bot(IMessagingClient messagingClient)
})
});
Client = messagingClient;

Service.AddModule<GenericCommandsModule>();
Service.AddModule<SystemCommandModule>();
Service.AddModule<InventoryCommandsModule>();
Expand All @@ -68,7 +68,7 @@ public Bot(IMessagingClient messagingClient)
Service.AddModule<BandcampCommandsModule>();
Service.AddModule<TranslateCommandModule>();
Service.AddModule<FishCommandsModule>();

Service.AddTypeParser(new Parsers.LanugageParser());
Service.AddTypeParser(new Parsers.GoalProgressParser());
Service.AddTypeParser(new Parsers.ColorParser());
Expand All @@ -90,7 +90,7 @@ public Bot(IMessagingClient messagingClient)
.Any(x => x.Aliases.Any(a => a == command.Command));

if (!commandIntenral || string.IsNullOrWhiteSpace(command.Nick)) continue;

var user = new User(command.Nick, Connection);
Log.Warning("User {0} have a command with internal name {1}!",
user.Username,
Expand Down Expand Up @@ -146,7 +146,7 @@ public async void ProccessInfinite()
var reminds = Connection.Table<SQL.Reminds>();
foreach (var item in reminds)
{
DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0,
DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0,
DateTimeKind.Utc);
dtDateTime = dtDateTime.AddSeconds(item.RemindDate).ToLocalTime();
if (dtDateTime <= DateTime.Now)
Expand All @@ -163,23 +163,35 @@ public async void ProccessInfinite()

public void MessageTrigger(MessageGeneric message)
{
if (message.Sender.UserIsIgnored() || message.Kind == MessageKind.MessagePersonal) { return; }
if (message.Kind == MessageKind.MessagePersonal)
{
return;
}
var permissions = message.Sender.GetPermissions();
PProfiler.BeginMeasure("msg");

try
{
PProfiler.BeginMeasure("msg");
OnMsgEvent.InsertMessages(message);
OnMsgEvent.DestroyWallRandomly(Shop, message);
OnMsgEvent.LevelInscrease(Shop, message);
OnMsgEvent.PrintWarningInformation(message);
OnMsgEvent.HandleYoutube(message);
OnMsgEvent.HandleURL(message);
OnMsgEvent.WhoWrotesMe(message);
PProfiler.EndMeasure("msg");
if (permissions.HandleProcessing && !permissions.Bridge)
{
OnMsgEvent.InsertMessages(message);
OnMsgEvent.DestroyWallRandomly(Shop, message);
OnMsgEvent.LevelInscrease(Shop, message);
OnMsgEvent.PrintWarningInformation(message);
OnMsgEvent.WhoWrotesMe(message);
}

if (permissions.HandleUrls)
{
OnMsgEvent.HandleURL(message);
}
}
catch (Exception ex)
{
Log.Error("Message trigger causes a exception: {0}", ex);
}

PProfiler.EndMeasure("msg");
}

static string HeuristicPrintErrorMessage(string message)
Expand Down Expand Up @@ -239,7 +251,8 @@ await Client.SendMessage(message.Target,
$"Ошибка в `{err.Parameter}` необходимый тип: `{err.Parameter.Type.Name}` вы же ввели: `{err.Value.GetType().Name}`. Введите .helpcmd {err.Parameter.Command} чтобы узнать наконец-то, как же правильно пользоватся этой командой.");
break;
case CommandOnCooldownResult err:
await Client.SendMessage(message.Target, $"{RandomMsgs.CommandCooldownMessages.Random()} {err.Cooldowns.FirstOrDefault().RetryAfter.ToString(@"hh\:mm\:ss")}");
await Client.SendMessage(message.Target,
$"{RandomMsgs.CommandCooldownMessages.Random()} {err.Cooldowns.FirstOrDefault().RetryAfter.ToString(@"hh\:mm\:ss")}");
break;
case ArgumentParseFailedResult err:
var parserResult = err.ParserResult as DefaultArgumentParserResult;
Expand All @@ -260,12 +273,13 @@ await Client.SendMessage(message.Target,
break;
case OverloadsFailedResult:
await Client.SendMessage(message.Target, "Команда выключена...");
break;
break;
case CommandNotFoundResult _:
await CustomCommandProcessor.ProcessCmd(prefix, message);
break;
case CommandExecutionFailedResult err:
if (err.Exception.GetType() == typeof(JsonReaderException) || err.Exception.GetType() == typeof(JsonException))
if (err.Exception.GetType() == typeof(JsonReaderException) ||
err.Exception.GetType() == typeof(JsonException))
{
await Client.SendMessage(message.Target, RandomMsgs.NetworkMessages.Random());
}
Expand Down
4 changes: 3 additions & 1 deletion fs24bot3/Checks/CheckAdmin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ public override ValueTask<CheckResult> CheckAsync(CommandContext _)
{
var context = _ as CommandProcessor.CustomCommandContext;

var permissions = context.User.GetPermissions();

try
{
return (context.User.GetUserInfo().Admin >= 1 && context.IsAuthorizedAction) || ConfigurationProvider.Config.Backend == Models.Backend.Basic
return (permissions.Admin && context.IsAuthorizedAction) || ConfigurationProvider.Config.Backend == Models.Backend.Basic
? CheckResult.Successful
: CheckResult.Failed("Эта команда только для админов!");
}
Expand Down
10 changes: 8 additions & 2 deletions fs24bot3/Checks/FullAccount.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,19 @@
using System.Threading.Tasks;

namespace fs24bot3.Checks;

public sealed class FullAccount : CheckAttribute
{
public override ValueTask<CheckResult> CheckAsync(CommandContext _)
{
var context = _ as CommandProcessor.CustomCommandContext;

return !context.FromBridge && !context.User.UserIsIgnored() && context.User != null && context.IsAuthorizedAction
if (context?.User is null)
{
return CheckResult.Failed("Нет аккаунта пользователя");
}

return !context.FromBridge && context.IsAuthorizedAction
? CheckResult.Successful
: CheckResult.Failed("Эта команда требует аккаунт fs24_bot и авторизацию через NickServ!");
}
Expand All @@ -18,4 +24,4 @@ public override string ToString()
{
return "Аккаунт пользователя";
}
}
}
12 changes: 6 additions & 6 deletions fs24bot3/Commands/CustomCommandsModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public async Task CustomCmdEdit(string command, CommandToggles.CommandEdit actio

if (query != null && query.Command == command && query.IsLua == 0)
{
if (query.Nick == Context.User.Username || Context.User.GetUserInfo().Admin == 2)
if (query.Nick == Context.User.Username || Context.User.GetPermissions().Admin)
{
switch (action)
{
Expand Down Expand Up @@ -198,9 +198,9 @@ await Context.SendMessage(Context.Channel,
public async Task CustomCmdRepl(string command, string oldstr, string newstr = "")
{
var query = Context.BotCtx.Connection.Table<SQL.CustomUserCommands>().Where(v => v.Command.Equals(command)).FirstOrDefault();
if (query != null && query.Command == command || Context.User.GetUserInfo().Admin == 2)
if (query != null && query.Command == command || Context.User.GetPermissions().Admin)
{
if (query.Nick == Context.User.Username || Context.User.GetUserInfo().Admin == 2)
if (query.Nick == Context.User.Username || Context.User.GetPermissions().Admin)
{
Context.BotCtx.Connection.Execute("UPDATE CustomUserCommands SET Output = ? WHERE Command = ?", query.Output.Replace(oldstr, newstr), command);
await Context.SendMessage(Context.Channel, "[blue]Команда успешно обновлена!");
Expand All @@ -222,9 +222,9 @@ public async Task CustomCmdRepl(string command, string oldstr, string newstr = "
public async Task LuaUpdCoommand(string command, [Remainder] string newstr)
{
var query = Context.BotCtx.Connection.Table<SQL.CustomUserCommands>().Where(v => v.Command.Equals(command)).FirstOrDefault();
if (query != null && query.IsLua == 1 && query.Command == command || Context.User.GetUserInfo().Admin == 2)
if (query != null && query.IsLua == 1 && query.Command == command || Context.User.GetPermissions().Admin)
{
if (query.Nick == Context.User.Username || Context.User.GetUserInfo().Admin == 2)
if (query.Nick == Context.User.Username || Context.User.GetPermissions().Admin)
{
Context.BotCtx.Connection.Execute("UPDATE CustomUserCommands SET Output = ? WHERE Command = ?", newstr, command);
await Context.SendMessage(Context.Channel, "[blue]Команда успешно обновлена!");
Expand Down Expand Up @@ -254,7 +254,7 @@ public async Task LuaUpdCoommandUrl(string command, string rawurl)
[Checks.FullAccount]
public async Task CustomCmdRem(string command)
{
if (Context.User.GetUserInfo().Admin == 2)
if (Context.User.GetPermissions().Admin)
{
var query = Context.BotCtx.Connection.Table<SQL.CustomUserCommands>().Where(v => v.Command.Equals(command)).Delete();
if (query > 0)
Expand Down
2 changes: 1 addition & 1 deletion fs24bot3/Commands/InventoryCommandsModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ await Context.SendMessage(Context.Channel,

if (query != null && query.Name == tagname)
{
if (query.CreatedBy == Context.User.Username || Context.User.GetUserInfo().Admin == 2)
if (query.CreatedBy == Context.User.Username || Context.User.GetPermissions().Admin)
{
Context.BotCtx.Connection.Table<SQL.Tag>().Where(v => v.Name.Equals(tagname)).Delete();
await Context.SendMessage(Context.Channel,
Expand Down
Loading

0 comments on commit ac9b5a2

Please sign in to comment.