Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions TelegramBotFramework.Core/DefaultModules/Admin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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!");
}
}

Expand All @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions TelegramBotFramework.Core/Helpers/UserHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down Expand Up @@ -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);
}
}
}
5 changes: 4 additions & 1 deletion TelegramBotFramework.Core/Interfaces/ITelegramBotOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
}
}
16 changes: 12 additions & 4 deletions TelegramBotFramework.Core/Logging/TelegramBotLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,25 @@
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using TelegramBotFramework.Core.Interfaces;

namespace TelegramBotFramework.Core.Logging
{
public class TelegramBotLogger
{
public readonly string Path;
private readonly Queue<LogQueueItem> _logQueue = new Queue<LogQueueItem>();
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")
{
Expand Down Expand Up @@ -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);
Expand Down
16 changes: 14 additions & 2 deletions TelegramBotFramework.Core/Objects/DefaultBotOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,31 @@ 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;
}

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;
/// <summary>
/// Write all internal logs to a file instead of only printing them on the console screen
/// </summary>
public bool FileLog { get; set; } = true;
/// <summary>
/// Allows external modules and scans for them in the AddonModules directory
/// </summary>
public bool AddonModules { get; set; } = true;
/// <summary>
/// Enables default modules such as Admin and DefaultBotModule
/// </summary>
public bool DefaultModules { get; set; } = true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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
}
Expand Down
2 changes: 1 addition & 1 deletion TelegramBotFramework.Core/SQLiteDb/TelegramBotSetting.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class TelegramBotSetting:IEditableEntity
/// <summary>
/// The ID of the Telegram user who will be the main admin for the bot (typically, the person running the code)
/// </summary>
public int TelegramDefaultAdminUserId { get; set; }
public long TelegramDefaultAdminUserId { get; set; }
/// <summary>
/// Your Telegram Bot API Token
/// </summary>
Expand Down
37 changes: 21 additions & 16 deletions TelegramBotFramework.Core/TelegramBotWrapper.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@


using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Concurrent;
Expand Down Expand Up @@ -130,7 +130,7 @@ public TelegramBotWrapperWithDb(ITelegramBotOptions options, IDbContextFactory<T
{
Directory.CreateDirectory(Path.Combine(RootDirectory));
}
Log = new TelegramBotLogger(Path.Combine(RootDirectory, "Logs-" + Options.Alias));
Log = new TelegramBotLogger(options, Path.Combine(RootDirectory, "Logs-" + Options.Alias));
var setting = new TelegramBotSetting() { Alias = options.Alias, TelegramDefaultAdminUserId = Options.AdminId, TelegramBotAPIKey = Options.Key };
LoadedSetting = setting;

Expand Down Expand Up @@ -180,21 +180,26 @@ private void OnChanged(object sender, FileSystemEventArgs e)

public void LoadModules()
{
var currentAssembly = Assembly.GetExecutingAssembly();
//Clear the list
Commands.Clear();
//load base methods first
GetMethodsFromAssembly(Assembly.GetExecutingAssembly());
Log.WriteLine("Scanning Addon TelegramBotModules directory for custom TelegramBotModules...", overrideColor: ConsoleColor.Cyan);
var telegramBotModuleDir = Path.Combine(RootDirectory, "AddonModules-" + LoadedSetting.Alias);
Directory.CreateDirectory(telegramBotModuleDir);

Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

//now load TelegramBotModules from directory
foreach (var file in Directory.GetFiles(telegramBotModuleDir, "*.dll"))
if (Options.DefaultModules)
GetMethodsFromAssembly(currentAssembly);
if (Options.AddonModules)
{
GetMethodsFromAssembly(Assembly.LoadFrom(file));
Log.WriteLine("Scanning Addon TelegramBotModules directory for custom TelegramBotModules...", overrideColor: ConsoleColor.Cyan);
var telegramBotModuleDir = Path.Combine(RootDirectory, "AddonModules-" + LoadedSetting.Alias);
Directory.CreateDirectory(telegramBotModuleDir);

//now load TelegramBotModules from directory
foreach (var file in Directory.GetFiles(telegramBotModuleDir, "*.dll"))
{
GetMethodsFromAssembly(Assembly.LoadFrom(file));
}
}

var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a=> a != currentAssembly);
foreach (var assembly in assemblies)
{
GetMethodsFromAssembly(assembly);
Expand Down Expand Up @@ -248,7 +253,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 });
}
Expand All @@ -264,7 +269,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);
Expand All @@ -287,7 +292,7 @@ private void GetMethodsFromAssembly(Assembly assembly)
var att = method.GetCustomAttributes<ChatCommand>().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));
Expand All @@ -302,7 +307,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));
Expand Down
2 changes: 1 addition & 1 deletion TelegramBotFramework.Example/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down