From 271acbbe1e9d92e34aa2c338aacda34753a3608e Mon Sep 17 00:00:00 2001 From: Kan <38980663+KanTheAstronaut@users.noreply.github.com> Date: Wed, 20 Jul 2022 20:24:26 +0400 Subject: [PATCH 1/2] Improvements Changed admin id from int to long (also in the example) since telegram user ids are not integers Instead of returning null when we can't find a user in RemoveBotAdmin and AddBotAdmin let's return "Unknown user or user is not cached!" (because we are checking the database for the target user) or "You can't add/remove yourself!" Changed "GetTarget" so it returns null instead of returning the source user (which made the null check pointless) Made file logging optional (added an option in DefaultBotOptions and the interface) Made loading default modules optional Made loading addon modules optional Fixed a few typos --- .../DefaultModules/Admin.cs | 10 ++++++++-- TelegramBotFramework.Core/Helpers/UserHelpers.cs | 4 ++-- .../Interfaces/ITelegramBotOptions.cs | 5 ++++- .../Logging/TelegramBotLogger.cs | 16 ++++++++++++---- .../Objects/DefaultBotOptions.cs | 16 ++++++++++++++-- .../Extensions/TelegramBotDbExtensions.cs | 12 +++++------- .../SQLiteDb/TelegramBotSetting.cs | 2 +- TelegramBotFramework.Core/TelegramBotWrapper.cs | 8 ++++---- TelegramBotFramework.Example/Program.cs | 2 +- 9 files changed, 51 insertions(+), 24 deletions(-) diff --git a/TelegramBotFramework.Core/DefaultModules/Admin.cs b/TelegramBotFramework.Core/DefaultModules/Admin.cs index ce0200e..abb9120 100644 --- a/TelegramBotFramework.Core/DefaultModules/Admin.cs +++ b/TelegramBotFramework.Core/DefaultModules/Admin.cs @@ -86,7 +86,10 @@ public CommandResponse AddBotAdmin(CommandEventArgs args) target.IsBotAdmin = true; return new CommandResponse($"{target.Name} is now a bot admin."); } - return new CommandResponse(null); + if (target != null && target.Id == args.SourceUser.Id) + return new CommandResponse("You can't add yourself!"); + else + return new CommandResponse("Unknown user or user is not cached!"); } } @@ -99,7 +102,10 @@ public CommandResponse RemoveBotAdmin(CommandEventArgs args) target.IsBotAdmin = false; return new CommandResponse($"{target.Name} is no longer a bot admin."); } - return new CommandResponse(null); + if (target != null && target.Id == args.SourceUser.Id) + return new CommandResponse("You can't remove yourself!"); + else + return new CommandResponse("Unknown user or user is not cached!"); } [ChatCommand(Triggers = new[] { "users" }, DevOnly = true, DontSearchInline = true)] public CommandResponse GetUsersList(CommandEventArgs args) diff --git a/TelegramBotFramework.Core/Helpers/UserHelpers.cs b/TelegramBotFramework.Core/Helpers/UserHelpers.cs index b444984..b8f17a4 100644 --- a/TelegramBotFramework.Core/Helpers/UserHelpers.cs +++ b/TelegramBotFramework.Core/Helpers/UserHelpers.cs @@ -12,7 +12,7 @@ namespace TelegramBotFramework.Core.Helpers { public static class UserHelper { - public static TelegramBotUser GetTelegramUser(ITelegramBotDbContext db, int adminId, Update update = null, InlineQuery query = null, CallbackQuery cbQuery = null, bool logPoint = true) + public static TelegramBotUser GetTelegramUser(ITelegramBotDbContext db, long adminId, Update update = null, InlineQuery query = null, CallbackQuery cbQuery = null, bool logPoint = true) { using(db) { @@ -45,7 +45,7 @@ public static TelegramBotUser GetTelegramUser(ITelegramBotDbContext db, int admi public static TelegramBotUser GetTarget(this ITelegramBotDbContext db, CommandEventArgs args) { - return args.Message.GetTarget(args.Parameters, args.SourceUser, db); + return args.Message.GetTarget(args.Parameters, db); } } } diff --git a/TelegramBotFramework.Core/Interfaces/ITelegramBotOptions.cs b/TelegramBotFramework.Core/Interfaces/ITelegramBotOptions.cs index 29dd8ae..febc725 100644 --- a/TelegramBotFramework.Core/Interfaces/ITelegramBotOptions.cs +++ b/TelegramBotFramework.Core/Interfaces/ITelegramBotOptions.cs @@ -8,11 +8,14 @@ public interface ITelegramBotOptions { string Key { get; set; } string Alias { get; set; } - int AdminId { get; set; } + long AdminId { get; set; } bool ShouldApprooveNewUsers { get; set; } string PaymentToken { get; set; } string Directory { get; set; } string WebHookUrl { get; set; } bool InMemoryDb { get; set; } + bool FileLog { get; set; } + bool AddonModules { get; set; } + bool DefaultModules { get; set; } } } diff --git a/TelegramBotFramework.Core/Logging/TelegramBotLogger.cs b/TelegramBotFramework.Core/Logging/TelegramBotLogger.cs index 2466977..c6b5e1d 100644 --- a/TelegramBotFramework.Core/Logging/TelegramBotLogger.cs +++ b/TelegramBotFramework.Core/Logging/TelegramBotLogger.cs @@ -3,6 +3,7 @@ using System.IO; using System.Threading; using System.Threading.Tasks; +using TelegramBotFramework.Core.Interfaces; namespace TelegramBotFramework.Core.Logging { @@ -10,11 +11,17 @@ public class TelegramBotLogger { public readonly string Path; private readonly Queue _logQueue = new Queue(); - public TelegramBotLogger(string directory) + private ITelegramBotOptions _options; + public TelegramBotLogger(ITelegramBotOptions options, string directory) { + _options = options; Path = directory; - Directory.CreateDirectory(Path); - new Task(WatchQueue).Start(); + + if (_options.FileLog) + { + Directory.CreateDirectory(Path); + new Task(WatchQueue).Start(); + } } public void Write(object msg, LogLevel level = LogLevel.Info, ConsoleColor? overrideColor = null, string fileName = "log.log") { @@ -43,7 +50,8 @@ public void Write(object msg, LogLevel level = LogLevel.Info, ConsoleColor? over break; } finalMessage += msg.ToString(); - _logQueue.Enqueue(new LogQueueItem(System.IO.Path.Combine(Path, fileName), finalMessage)); + if (_options.FileLog) + _logQueue.Enqueue(new LogQueueItem(System.IO.Path.Combine(Path, fileName), finalMessage)); Console.ForegroundColor = color; Console.Write(finalMessage); diff --git a/TelegramBotFramework.Core/Objects/DefaultBotOptions.cs b/TelegramBotFramework.Core/Objects/DefaultBotOptions.cs index d968a83..eb5ee44 100644 --- a/TelegramBotFramework.Core/Objects/DefaultBotOptions.cs +++ b/TelegramBotFramework.Core/Objects/DefaultBotOptions.cs @@ -9,7 +9,7 @@ namespace TelegramBotFramework.Core.Objects { public class DefaultBotOptions : ITelegramBotOptions { - public DefaultBotOptions(string key, int adminId) + public DefaultBotOptions(string key, long adminId) { Key = key ?? throw new ArgumentNullException(nameof(key)); AdminId = adminId; @@ -17,11 +17,23 @@ public DefaultBotOptions(string key, int adminId) public string Key {get;set;} public string Alias { get; set; } = "TelegramBot"; - public int AdminId {get;set;} + public long AdminId {get;set;} public bool ShouldApprooveNewUsers { get; set; } = false; public string PaymentToken {get;set;} public string Directory { get; set; } = "TelegramBot"; public string WebHookUrl {get;set;} public bool InMemoryDb { get; set; } = false; + /// + /// Write all internal logs to a file instead of only printing them on the console screen + /// + public bool FileLog { get; set; } = true; + /// + /// Allows external modules and scans for them in the AddonModules directory + /// + public bool AddonModules { get; set; } = true; + /// + /// Enables default modules such as Admin and DefaultBotModule + /// + public bool DefaultModules { get; set; } = true; } } diff --git a/TelegramBotFramework.Core/SQLiteDb/Extensions/TelegramBotDbExtensions.cs b/TelegramBotFramework.Core/SQLiteDb/Extensions/TelegramBotDbExtensions.cs index fff464b..e26bb58 100644 --- a/TelegramBotFramework.Core/SQLiteDb/Extensions/TelegramBotDbExtensions.cs +++ b/TelegramBotFramework.Core/SQLiteDb/Extensions/TelegramBotDbExtensions.cs @@ -125,19 +125,17 @@ public static string ToString(this Telegram.Bot.Types.User user) } #region Helpers - public static TelegramBotUser GetTarget(this Message message, string args, TelegramBotUser sourceUser, ITelegramBotDbContext db) + public static TelegramBotUser GetTarget(this Message message, string args, ITelegramBotDbContext db) { - if (message == null) return sourceUser; + if (message == null) return null; if (message?.ReplyToMessage != null) { var m = message.ReplyToMessage; var userid = m.ForwardFrom?.Id ?? m.From.Id; - return db.TelegramBotUsers.AsNoTracking().FirstOrDefault(x => x.UserId == userid) ?? sourceUser; + return db.TelegramBotUsers.AsNoTracking().FirstOrDefault(x => x.UserId == userid); } if (String.IsNullOrWhiteSpace(args)) - { - return sourceUser; - } + return null; //check for a user mention var mention = message?.Entities.FirstOrDefault(x => x.Type == MessageEntityType.Mention); var textmention = message?.Entities.FirstOrDefault(x => x.Type == MessageEntityType.TextMention); @@ -160,7 +158,7 @@ public static TelegramBotUser GetTarget(this Message message, string args, Teleg x => String.Equals(x.UserId.ToString(), args, StringComparison.InvariantCultureIgnoreCase) || String.Equals(x.UserName, args.Replace("@", ""), StringComparison.InvariantCultureIgnoreCase)); - return result ?? sourceUser; + return result; } #endregion } diff --git a/TelegramBotFramework.Core/SQLiteDb/TelegramBotSetting.cs b/TelegramBotFramework.Core/SQLiteDb/TelegramBotSetting.cs index 54aa162..30acdcb 100644 --- a/TelegramBotFramework.Core/SQLiteDb/TelegramBotSetting.cs +++ b/TelegramBotFramework.Core/SQLiteDb/TelegramBotSetting.cs @@ -19,7 +19,7 @@ public class TelegramBotSetting:IEditableEntity /// /// The ID of the Telegram user who will be the main admin for the bot (typically, the person running the code) /// - public int TelegramDefaultAdminUserId { get; set; } + public long TelegramDefaultAdminUserId { get; set; } /// /// Your Telegram Bot API Token /// diff --git a/TelegramBotFramework.Core/TelegramBotWrapper.cs b/TelegramBotFramework.Core/TelegramBotWrapper.cs index f49d1dc..1b94ffa 100644 --- a/TelegramBotFramework.Core/TelegramBotWrapper.cs +++ b/TelegramBotFramework.Core/TelegramBotWrapper.cs @@ -248,7 +248,7 @@ private void GetMethodsFromAssembly(Assembly assembly) { if (paramss[0].ParameterType.IsAssignableFrom(currentBot)) { - Log.WriteLine($"Finded constructor, invoking it for loading {moduleAttributes.Name} at {this.GetType().FullName}"); + Log.WriteLine($"Found constructor, invoking it for loading {moduleAttributes.Name} at {this.GetType().FullName}"); instance = c.Invoke(new object[] { this }); } @@ -264,7 +264,7 @@ private void GetMethodsFromAssembly(Assembly assembly) } if (Modules.ContainsKey(moduleAttributes)) { - Log.WriteLine($"{moduleAttributes.Name} has been already loaded. Rename it, if it is no dublicate"); + Log.WriteLine($"{moduleAttributes.Name} has been already loaded. Rename it, if it is no duplicate"); continue; } Modules.Add(moduleAttributes, instance); @@ -287,7 +287,7 @@ private void GetMethodsFromAssembly(Assembly assembly) var att = method.GetCustomAttributes().First(); if (Commands.ContainsKey(att)) { - Log.WriteLine($"ChatCommand {method.Name}\n\t with Trigger(s): {att.Triggers.Aggregate((a, b) => a + ", " + b)} not loaded, possible dublicate", overrideColor: ConsoleColor.Cyan); + Log.WriteLine($"ChatCommand {method.Name}\n\t with Trigger(s): {att.Triggers.Aggregate((a, b) => a + ", " + b)} not loaded, possible duplicate", overrideColor: ConsoleColor.Cyan); continue; } Commands.Add(att, (ChatCommandMethod)Delegate.CreateDelegate(typeof(ChatCommandMethod), instance, method)); @@ -302,7 +302,7 @@ private void GetMethodsFromAssembly(Assembly assembly) if (CallbackCommands.ContainsKey(att)) { - Log.WriteLine($"Not loaded CallbackCommand {m.Name}\n\t Trigger: {att.Trigger}, possible dublicate", overrideColor: ConsoleColor.Cyan); + Log.WriteLine($"Not loaded CallbackCommand {m.Name}\n\t Trigger: {att.Trigger}, possible duplicate", overrideColor: ConsoleColor.Cyan); continue; } CallbackCommands.Add(att, (CallbackCommandMethod)Delegate.CreateDelegate(typeof(CallbackCommandMethod), instance, m)); diff --git a/TelegramBotFramework.Example/Program.cs b/TelegramBotFramework.Example/Program.cs index ab91bfc..fb32624 100644 --- a/TelegramBotFramework.Example/Program.cs +++ b/TelegramBotFramework.Example/Program.cs @@ -21,7 +21,7 @@ TelegramBotWrapper provides a simple bots menue. Just send /menu or /42 and test var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); var configuration = builder.Build(); - var opts = new DefaultBotOptions(configuration["key"], int.Parse(configuration["admin"])); + var opts = new DefaultBotOptions(configuration["key"], long.Parse(configuration["admin"])); opts.InMemoryDb = false; var bot = new SimpleTelegramBot(opts); From 8d0531729015bebe326ff8472629f1efd51060d7 Mon Sep 17 00:00:00 2001 From: Kan <38980663+KanTheAstronaut@users.noreply.github.com> Date: Wed, 20 Jul 2022 20:57:03 +0400 Subject: [PATCH 2/2] Forgot to update this file --- .../TelegramBotWrapper.cs | 29 +++++++++++-------- 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/TelegramBotFramework.Core/TelegramBotWrapper.cs b/TelegramBotFramework.Core/TelegramBotWrapper.cs index 1b94ffa..5cc31cd 100644 --- a/TelegramBotFramework.Core/TelegramBotWrapper.cs +++ b/TelegramBotFramework.Core/TelegramBotWrapper.cs @@ -1,4 +1,4 @@ - + using Microsoft.EntityFrameworkCore; using System; using System.Collections.Concurrent; @@ -130,7 +130,7 @@ public TelegramBotWrapperWithDb(ITelegramBotOptions options, IDbContextFactory a != currentAssembly); foreach (var assembly in assemblies) { GetMethodsFromAssembly(assembly);