You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

CommandService.cs 18 kB

Add callback method for when a module class has been added (#934) commit 5b047bf02b4299f34172cac05dc7e4a84ecc108c Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Feb 2 22:22:00 2018 +0100 [feature/OnModuleAdded] Quickstart fixes (#946) * Quickstart: fix minor derp * Other overdue fixes commit bd3e9eee943b9092cc45217b19ff95bae359f888 Author: Christopher F <computerizedtaco@gmail.com> Date: Sat Jan 27 16:51:18 2018 -0500 Resort usings in ModuleBase commit 8042767579b337fdae7fe48e0a6ea2f007aef440 Author: Christopher F <computerizedtaco@gmail.com> Date: Sat Jan 27 16:41:39 2018 -0500 Clean up removed owned IServiceProvider commit 30066cb102ffbd65906ead72a377811aa501abba Author: Christopher F <computerizedtaco@gmail.com> Date: Sat Jan 27 16:37:22 2018 -0500 Remove redundant try-catch around OnModuleBuilding invocation If this exception is going to be rethrown, there's no reason to include a try-catch. commit 60c7c31d4476c498a97ae0536ec5792f08efb89b Author: Christopher F <computerizedtaco@gmail.com> Date: Sat Jan 27 16:36:27 2018 -0500 Include the ModuleBuilder in OnModuleBuilding This allows modules hooking into OnModuleBuilding method to mutate theirselves at runtime. commit b6a9ff57860ff3bddbad7ca850fd331529cb8e6e Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 22 13:17:14 2018 +0100 #DERP commit f623d19c68c5642a44898a561f77ed82d53fd103 Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 22 13:15:31 2018 +0100 Resolution for #937 because it's literally 4 lines of code commit 8272c9675b0d63b4100aaf57f5067d635b68f5e6 Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 22 11:39:28 2018 +0100 Re-adjust quickstart commit e30b9071351b69baa30a93a4851516dca9ea43cf Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 22 11:35:08 2018 +0100 Undo experimental changes, request IServiceProvider instance everywhere instead commit ad7e0a46c8709e845dfacdc298a893e22dc11567 Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Jan 19 03:40:27 2018 +0100 Fix quickstart leftover from previous draft commit e3349ef3d400bb3ad8cb28dd4234d5316a80bcc4 Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Jan 19 03:33:46 2018 +0100 Doc comment on items commit 81bd9111faaf98a52679daae863ab04dce96e63e Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Jan 19 03:16:44 2018 +0100 Add comment about the ServiceProviderFactory in the quickstart commit 72b5e6c8a149d8e989b46351965daa14f8ca318c Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Jan 19 03:10:40 2018 +0100 Remove superfluous comments, provide simpler alternative for setting the ServiceProvider. commit 74b17b0e04e2c413397a2e1b66ff814615326205 Author: Joe4evr <jii.geugten@gmail.com> Date: Tue Jan 16 18:06:28 2018 +0100 Experimental change for feedback commit 7b100e99bb119be190006d1cd8e403776930e401 Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 15 23:34:06 2018 +0100 * Make the service provider parameters required * Adjust quickstart guide to reflect changes commit 7f1b792946ac6b950922b06178aa5cc37d9f4144 Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 15 20:04:37 2018 +0100 I..... missed one. commit 031b289d80604666dde62619e521af303203d48d Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 15 20:02:20 2018 +0100 Rename method to more intuitive 'OnModuleBuilding' commit 9a166ef1d0baecd21e4e5b965e2ac364feddbe2e Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 15 19:09:10 2018 +0100 Add callback method for when a module class has been added to the CommandService.
8 years ago
Add callback method for when a module class has been added (#934) commit 5b047bf02b4299f34172cac05dc7e4a84ecc108c Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Feb 2 22:22:00 2018 +0100 [feature/OnModuleAdded] Quickstart fixes (#946) * Quickstart: fix minor derp * Other overdue fixes commit bd3e9eee943b9092cc45217b19ff95bae359f888 Author: Christopher F <computerizedtaco@gmail.com> Date: Sat Jan 27 16:51:18 2018 -0500 Resort usings in ModuleBase commit 8042767579b337fdae7fe48e0a6ea2f007aef440 Author: Christopher F <computerizedtaco@gmail.com> Date: Sat Jan 27 16:41:39 2018 -0500 Clean up removed owned IServiceProvider commit 30066cb102ffbd65906ead72a377811aa501abba Author: Christopher F <computerizedtaco@gmail.com> Date: Sat Jan 27 16:37:22 2018 -0500 Remove redundant try-catch around OnModuleBuilding invocation If this exception is going to be rethrown, there's no reason to include a try-catch. commit 60c7c31d4476c498a97ae0536ec5792f08efb89b Author: Christopher F <computerizedtaco@gmail.com> Date: Sat Jan 27 16:36:27 2018 -0500 Include the ModuleBuilder in OnModuleBuilding This allows modules hooking into OnModuleBuilding method to mutate theirselves at runtime. commit b6a9ff57860ff3bddbad7ca850fd331529cb8e6e Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 22 13:17:14 2018 +0100 #DERP commit f623d19c68c5642a44898a561f77ed82d53fd103 Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 22 13:15:31 2018 +0100 Resolution for #937 because it's literally 4 lines of code commit 8272c9675b0d63b4100aaf57f5067d635b68f5e6 Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 22 11:39:28 2018 +0100 Re-adjust quickstart commit e30b9071351b69baa30a93a4851516dca9ea43cf Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 22 11:35:08 2018 +0100 Undo experimental changes, request IServiceProvider instance everywhere instead commit ad7e0a46c8709e845dfacdc298a893e22dc11567 Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Jan 19 03:40:27 2018 +0100 Fix quickstart leftover from previous draft commit e3349ef3d400bb3ad8cb28dd4234d5316a80bcc4 Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Jan 19 03:33:46 2018 +0100 Doc comment on items commit 81bd9111faaf98a52679daae863ab04dce96e63e Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Jan 19 03:16:44 2018 +0100 Add comment about the ServiceProviderFactory in the quickstart commit 72b5e6c8a149d8e989b46351965daa14f8ca318c Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Jan 19 03:10:40 2018 +0100 Remove superfluous comments, provide simpler alternative for setting the ServiceProvider. commit 74b17b0e04e2c413397a2e1b66ff814615326205 Author: Joe4evr <jii.geugten@gmail.com> Date: Tue Jan 16 18:06:28 2018 +0100 Experimental change for feedback commit 7b100e99bb119be190006d1cd8e403776930e401 Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 15 23:34:06 2018 +0100 * Make the service provider parameters required * Adjust quickstart guide to reflect changes commit 7f1b792946ac6b950922b06178aa5cc37d9f4144 Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 15 20:04:37 2018 +0100 I..... missed one. commit 031b289d80604666dde62619e521af303203d48d Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 15 20:02:20 2018 +0100 Rename method to more intuitive 'OnModuleBuilding' commit 9a166ef1d0baecd21e4e5b965e2ac364feddbe2e Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 15 19:09:10 2018 +0100 Add callback method for when a module class has been added to the CommandService.
8 years ago
Add callback method for when a module class has been added (#934) commit 5b047bf02b4299f34172cac05dc7e4a84ecc108c Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Feb 2 22:22:00 2018 +0100 [feature/OnModuleAdded] Quickstart fixes (#946) * Quickstart: fix minor derp * Other overdue fixes commit bd3e9eee943b9092cc45217b19ff95bae359f888 Author: Christopher F <computerizedtaco@gmail.com> Date: Sat Jan 27 16:51:18 2018 -0500 Resort usings in ModuleBase commit 8042767579b337fdae7fe48e0a6ea2f007aef440 Author: Christopher F <computerizedtaco@gmail.com> Date: Sat Jan 27 16:41:39 2018 -0500 Clean up removed owned IServiceProvider commit 30066cb102ffbd65906ead72a377811aa501abba Author: Christopher F <computerizedtaco@gmail.com> Date: Sat Jan 27 16:37:22 2018 -0500 Remove redundant try-catch around OnModuleBuilding invocation If this exception is going to be rethrown, there's no reason to include a try-catch. commit 60c7c31d4476c498a97ae0536ec5792f08efb89b Author: Christopher F <computerizedtaco@gmail.com> Date: Sat Jan 27 16:36:27 2018 -0500 Include the ModuleBuilder in OnModuleBuilding This allows modules hooking into OnModuleBuilding method to mutate theirselves at runtime. commit b6a9ff57860ff3bddbad7ca850fd331529cb8e6e Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 22 13:17:14 2018 +0100 #DERP commit f623d19c68c5642a44898a561f77ed82d53fd103 Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 22 13:15:31 2018 +0100 Resolution for #937 because it's literally 4 lines of code commit 8272c9675b0d63b4100aaf57f5067d635b68f5e6 Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 22 11:39:28 2018 +0100 Re-adjust quickstart commit e30b9071351b69baa30a93a4851516dca9ea43cf Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 22 11:35:08 2018 +0100 Undo experimental changes, request IServiceProvider instance everywhere instead commit ad7e0a46c8709e845dfacdc298a893e22dc11567 Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Jan 19 03:40:27 2018 +0100 Fix quickstart leftover from previous draft commit e3349ef3d400bb3ad8cb28dd4234d5316a80bcc4 Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Jan 19 03:33:46 2018 +0100 Doc comment on items commit 81bd9111faaf98a52679daae863ab04dce96e63e Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Jan 19 03:16:44 2018 +0100 Add comment about the ServiceProviderFactory in the quickstart commit 72b5e6c8a149d8e989b46351965daa14f8ca318c Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Jan 19 03:10:40 2018 +0100 Remove superfluous comments, provide simpler alternative for setting the ServiceProvider. commit 74b17b0e04e2c413397a2e1b66ff814615326205 Author: Joe4evr <jii.geugten@gmail.com> Date: Tue Jan 16 18:06:28 2018 +0100 Experimental change for feedback commit 7b100e99bb119be190006d1cd8e403776930e401 Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 15 23:34:06 2018 +0100 * Make the service provider parameters required * Adjust quickstart guide to reflect changes commit 7f1b792946ac6b950922b06178aa5cc37d9f4144 Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 15 20:04:37 2018 +0100 I..... missed one. commit 031b289d80604666dde62619e521af303203d48d Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 15 20:02:20 2018 +0100 Rename method to more intuitive 'OnModuleBuilding' commit 9a166ef1d0baecd21e4e5b965e2ac364feddbe2e Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 15 19:09:10 2018 +0100 Add callback method for when a module class has been added to the CommandService.
8 years ago
Add callback method for when a module class has been added (#934) commit 5b047bf02b4299f34172cac05dc7e4a84ecc108c Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Feb 2 22:22:00 2018 +0100 [feature/OnModuleAdded] Quickstart fixes (#946) * Quickstart: fix minor derp * Other overdue fixes commit bd3e9eee943b9092cc45217b19ff95bae359f888 Author: Christopher F <computerizedtaco@gmail.com> Date: Sat Jan 27 16:51:18 2018 -0500 Resort usings in ModuleBase commit 8042767579b337fdae7fe48e0a6ea2f007aef440 Author: Christopher F <computerizedtaco@gmail.com> Date: Sat Jan 27 16:41:39 2018 -0500 Clean up removed owned IServiceProvider commit 30066cb102ffbd65906ead72a377811aa501abba Author: Christopher F <computerizedtaco@gmail.com> Date: Sat Jan 27 16:37:22 2018 -0500 Remove redundant try-catch around OnModuleBuilding invocation If this exception is going to be rethrown, there's no reason to include a try-catch. commit 60c7c31d4476c498a97ae0536ec5792f08efb89b Author: Christopher F <computerizedtaco@gmail.com> Date: Sat Jan 27 16:36:27 2018 -0500 Include the ModuleBuilder in OnModuleBuilding This allows modules hooking into OnModuleBuilding method to mutate theirselves at runtime. commit b6a9ff57860ff3bddbad7ca850fd331529cb8e6e Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 22 13:17:14 2018 +0100 #DERP commit f623d19c68c5642a44898a561f77ed82d53fd103 Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 22 13:15:31 2018 +0100 Resolution for #937 because it's literally 4 lines of code commit 8272c9675b0d63b4100aaf57f5067d635b68f5e6 Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 22 11:39:28 2018 +0100 Re-adjust quickstart commit e30b9071351b69baa30a93a4851516dca9ea43cf Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 22 11:35:08 2018 +0100 Undo experimental changes, request IServiceProvider instance everywhere instead commit ad7e0a46c8709e845dfacdc298a893e22dc11567 Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Jan 19 03:40:27 2018 +0100 Fix quickstart leftover from previous draft commit e3349ef3d400bb3ad8cb28dd4234d5316a80bcc4 Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Jan 19 03:33:46 2018 +0100 Doc comment on items commit 81bd9111faaf98a52679daae863ab04dce96e63e Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Jan 19 03:16:44 2018 +0100 Add comment about the ServiceProviderFactory in the quickstart commit 72b5e6c8a149d8e989b46351965daa14f8ca318c Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Jan 19 03:10:40 2018 +0100 Remove superfluous comments, provide simpler alternative for setting the ServiceProvider. commit 74b17b0e04e2c413397a2e1b66ff814615326205 Author: Joe4evr <jii.geugten@gmail.com> Date: Tue Jan 16 18:06:28 2018 +0100 Experimental change for feedback commit 7b100e99bb119be190006d1cd8e403776930e401 Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 15 23:34:06 2018 +0100 * Make the service provider parameters required * Adjust quickstart guide to reflect changes commit 7f1b792946ac6b950922b06178aa5cc37d9f4144 Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 15 20:04:37 2018 +0100 I..... missed one. commit 031b289d80604666dde62619e521af303203d48d Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 15 20:02:20 2018 +0100 Rename method to more intuitive 'OnModuleBuilding' commit 9a166ef1d0baecd21e4e5b965e2ac364feddbe2e Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 15 19:09:10 2018 +0100 Add callback method for when a module class has been added to the CommandService.
8 years ago
Add callback method for when a module class has been added (#934) commit 5b047bf02b4299f34172cac05dc7e4a84ecc108c Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Feb 2 22:22:00 2018 +0100 [feature/OnModuleAdded] Quickstart fixes (#946) * Quickstart: fix minor derp * Other overdue fixes commit bd3e9eee943b9092cc45217b19ff95bae359f888 Author: Christopher F <computerizedtaco@gmail.com> Date: Sat Jan 27 16:51:18 2018 -0500 Resort usings in ModuleBase commit 8042767579b337fdae7fe48e0a6ea2f007aef440 Author: Christopher F <computerizedtaco@gmail.com> Date: Sat Jan 27 16:41:39 2018 -0500 Clean up removed owned IServiceProvider commit 30066cb102ffbd65906ead72a377811aa501abba Author: Christopher F <computerizedtaco@gmail.com> Date: Sat Jan 27 16:37:22 2018 -0500 Remove redundant try-catch around OnModuleBuilding invocation If this exception is going to be rethrown, there's no reason to include a try-catch. commit 60c7c31d4476c498a97ae0536ec5792f08efb89b Author: Christopher F <computerizedtaco@gmail.com> Date: Sat Jan 27 16:36:27 2018 -0500 Include the ModuleBuilder in OnModuleBuilding This allows modules hooking into OnModuleBuilding method to mutate theirselves at runtime. commit b6a9ff57860ff3bddbad7ca850fd331529cb8e6e Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 22 13:17:14 2018 +0100 #DERP commit f623d19c68c5642a44898a561f77ed82d53fd103 Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 22 13:15:31 2018 +0100 Resolution for #937 because it's literally 4 lines of code commit 8272c9675b0d63b4100aaf57f5067d635b68f5e6 Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 22 11:39:28 2018 +0100 Re-adjust quickstart commit e30b9071351b69baa30a93a4851516dca9ea43cf Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 22 11:35:08 2018 +0100 Undo experimental changes, request IServiceProvider instance everywhere instead commit ad7e0a46c8709e845dfacdc298a893e22dc11567 Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Jan 19 03:40:27 2018 +0100 Fix quickstart leftover from previous draft commit e3349ef3d400bb3ad8cb28dd4234d5316a80bcc4 Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Jan 19 03:33:46 2018 +0100 Doc comment on items commit 81bd9111faaf98a52679daae863ab04dce96e63e Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Jan 19 03:16:44 2018 +0100 Add comment about the ServiceProviderFactory in the quickstart commit 72b5e6c8a149d8e989b46351965daa14f8ca318c Author: Joe4evr <jii.geugten@gmail.com> Date: Fri Jan 19 03:10:40 2018 +0100 Remove superfluous comments, provide simpler alternative for setting the ServiceProvider. commit 74b17b0e04e2c413397a2e1b66ff814615326205 Author: Joe4evr <jii.geugten@gmail.com> Date: Tue Jan 16 18:06:28 2018 +0100 Experimental change for feedback commit 7b100e99bb119be190006d1cd8e403776930e401 Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 15 23:34:06 2018 +0100 * Make the service provider parameters required * Adjust quickstart guide to reflect changes commit 7f1b792946ac6b950922b06178aa5cc37d9f4144 Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 15 20:04:37 2018 +0100 I..... missed one. commit 031b289d80604666dde62619e521af303203d48d Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 15 20:02:20 2018 +0100 Rename method to more intuitive 'OnModuleBuilding' commit 9a166ef1d0baecd21e4e5b965e2ac364feddbe2e Author: Joe4evr <jii.geugten@gmail.com> Date: Mon Jan 15 19:09:10 2018 +0100 Add callback method for when a module class has been added to the CommandService.
8 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Collections.Immutable;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using Microsoft.Extensions.DependencyInjection;
  10. using Discord.Commands.Builders;
  11. using Discord.Logging;
  12. namespace Discord.Commands
  13. {
  14. public class CommandService
  15. {
  16. public event Func<LogMessage, Task> Log { add { _logEvent.Add(value); } remove { _logEvent.Remove(value); } }
  17. internal readonly AsyncEvent<Func<LogMessage, Task>> _logEvent = new AsyncEvent<Func<LogMessage, Task>>();
  18. public event Func<CommandInfo, ICommandContext, IResult, Task> CommandExecuted { add { _commandExecutedEvent.Add(value); } remove { _commandExecutedEvent.Remove(value); } }
  19. internal readonly AsyncEvent<Func<CommandInfo, ICommandContext, IResult, Task>> _commandExecutedEvent = new AsyncEvent<Func<CommandInfo, ICommandContext, IResult, Task>>();
  20. private readonly SemaphoreSlim _moduleLock;
  21. private readonly ConcurrentDictionary<Type, ModuleInfo> _typedModuleDefs;
  22. private readonly ConcurrentDictionary<Type, ConcurrentDictionary<Type, TypeReader>> _typeReaders;
  23. private readonly ConcurrentDictionary<Type, TypeReader> _defaultTypeReaders;
  24. private readonly ImmutableList<Tuple<Type, Type>> _entityTypeReaders; //TODO: Candidate for C#7 Tuple
  25. private readonly HashSet<ModuleInfo> _moduleDefs;
  26. private readonly CommandMap _map;
  27. internal readonly bool _caseSensitive, _throwOnError, _ignoreExtraArgs;
  28. internal readonly char _separatorChar;
  29. internal readonly RunMode _defaultRunMode;
  30. internal readonly Logger _cmdLogger;
  31. internal readonly LogManager _logManager;
  32. internal readonly IReadOnlyDictionary<char, char> _quotationMarkAliasMap;
  33. public IEnumerable<ModuleInfo> Modules => _moduleDefs.Select(x => x);
  34. public IEnumerable<CommandInfo> Commands => _moduleDefs.SelectMany(x => x.Commands);
  35. public ILookup<Type, TypeReader> TypeReaders => _typeReaders.SelectMany(x => x.Value.Select(y => new { y.Key, y.Value })).ToLookup(x => x.Key, x => x.Value);
  36. public CommandService() : this(new CommandServiceConfig()) { }
  37. public CommandService(CommandServiceConfig config)
  38. {
  39. _caseSensitive = config.CaseSensitiveCommands;
  40. _throwOnError = config.ThrowOnError;
  41. _ignoreExtraArgs = config.IgnoreExtraArgs;
  42. _separatorChar = config.SeparatorChar;
  43. _defaultRunMode = config.DefaultRunMode;
  44. _quotationMarkAliasMap = config.QuotationMarkAliasMap?.ToImmutableDictionary();
  45. if (_defaultRunMode == RunMode.Default)
  46. throw new InvalidOperationException("The default run mode cannot be set to Default.");
  47. _logManager = new LogManager(config.LogLevel);
  48. _logManager.Message += async msg => await _logEvent.InvokeAsync(msg).ConfigureAwait(false);
  49. _cmdLogger = _logManager.CreateLogger("Command");
  50. _moduleLock = new SemaphoreSlim(1, 1);
  51. _typedModuleDefs = new ConcurrentDictionary<Type, ModuleInfo>();
  52. _moduleDefs = new HashSet<ModuleInfo>();
  53. _map = new CommandMap(this);
  54. _typeReaders = new ConcurrentDictionary<Type, ConcurrentDictionary<Type, TypeReader>>();
  55. _defaultTypeReaders = new ConcurrentDictionary<Type, TypeReader>();
  56. foreach (var type in PrimitiveParsers.SupportedTypes)
  57. {
  58. _defaultTypeReaders[type] = PrimitiveTypeReader.Create(type);
  59. _defaultTypeReaders[typeof(Nullable<>).MakeGenericType(type)] = NullableTypeReader.Create(type, _defaultTypeReaders[type]);
  60. }
  61. _defaultTypeReaders[typeof(string)] =
  62. new PrimitiveTypeReader<string>((string x, out string y) => { y = x; return true; }, 0);
  63. var entityTypeReaders = ImmutableList.CreateBuilder<Tuple<Type, Type>>();
  64. entityTypeReaders.Add(new Tuple<Type, Type>(typeof(IMessage), typeof(MessageTypeReader<>)));
  65. entityTypeReaders.Add(new Tuple<Type, Type>(typeof(IChannel), typeof(ChannelTypeReader<>)));
  66. entityTypeReaders.Add(new Tuple<Type, Type>(typeof(IRole), typeof(RoleTypeReader<>)));
  67. entityTypeReaders.Add(new Tuple<Type, Type>(typeof(IUser), typeof(UserTypeReader<>)));
  68. _entityTypeReaders = entityTypeReaders.ToImmutable();
  69. }
  70. //Modules
  71. public async Task<ModuleInfo> CreateModuleAsync(string primaryAlias, Action<ModuleBuilder> buildFunc)
  72. {
  73. await _moduleLock.WaitAsync().ConfigureAwait(false);
  74. try
  75. {
  76. var builder = new ModuleBuilder(this, null, primaryAlias);
  77. buildFunc(builder);
  78. var module = builder.Build(this, null);
  79. return LoadModuleInternal(module);
  80. }
  81. finally
  82. {
  83. _moduleLock.Release();
  84. }
  85. }
  86. /// <summary>
  87. /// Add a command module from a type
  88. /// </summary>
  89. /// <typeparam name="T">The type of module</typeparam>
  90. /// <param name="services">An IServiceProvider for your dependency injection solution, if using one - otherwise, pass null</param>
  91. /// <returns>A built module</returns>
  92. public Task<ModuleInfo> AddModuleAsync<T>(IServiceProvider services) => AddModuleAsync(typeof(T), services);
  93. public async Task<ModuleInfo> AddModuleAsync(Type type, IServiceProvider services)
  94. {
  95. services = services ?? EmptyServiceProvider.Instance;
  96. await _moduleLock.WaitAsync().ConfigureAwait(false);
  97. try
  98. {
  99. var typeInfo = type.GetTypeInfo();
  100. if (_typedModuleDefs.ContainsKey(type))
  101. throw new ArgumentException($"This module has already been added.");
  102. var module = (await ModuleClassBuilder.BuildAsync(this, services, typeInfo).ConfigureAwait(false)).FirstOrDefault();
  103. if (module.Value == default(ModuleInfo))
  104. throw new InvalidOperationException($"Could not build the module {type.FullName}, did you pass an invalid type?");
  105. _typedModuleDefs[module.Key] = module.Value;
  106. return LoadModuleInternal(module.Value);
  107. }
  108. finally
  109. {
  110. _moduleLock.Release();
  111. }
  112. }
  113. /// <summary>
  114. /// Add command modules from an assembly
  115. /// </summary>
  116. /// <param name="assembly">The assembly containing command modules</param>
  117. /// <param name="services">An IServiceProvider for your dependency injection solution, if using one - otherwise, pass null</param>
  118. /// <returns>A collection of built modules</returns>
  119. public async Task<IEnumerable<ModuleInfo>> AddModulesAsync(Assembly assembly, IServiceProvider services)
  120. {
  121. services = services ?? EmptyServiceProvider.Instance;
  122. await _moduleLock.WaitAsync().ConfigureAwait(false);
  123. try
  124. {
  125. var types = await ModuleClassBuilder.SearchAsync(assembly, this).ConfigureAwait(false);
  126. var moduleDefs = await ModuleClassBuilder.BuildAsync(types, this, services).ConfigureAwait(false);
  127. foreach (var info in moduleDefs)
  128. {
  129. _typedModuleDefs[info.Key] = info.Value;
  130. LoadModuleInternal(info.Value);
  131. }
  132. return moduleDefs.Select(x => x.Value).ToImmutableArray();
  133. }
  134. finally
  135. {
  136. _moduleLock.Release();
  137. }
  138. }
  139. private ModuleInfo LoadModuleInternal(ModuleInfo module)
  140. {
  141. _moduleDefs.Add(module);
  142. foreach (var command in module.Commands)
  143. _map.AddCommand(command);
  144. foreach (var submodule in module.Submodules)
  145. LoadModuleInternal(submodule);
  146. return module;
  147. }
  148. public async Task<bool> RemoveModuleAsync(ModuleInfo module)
  149. {
  150. await _moduleLock.WaitAsync().ConfigureAwait(false);
  151. try
  152. {
  153. return RemoveModuleInternal(module);
  154. }
  155. finally
  156. {
  157. _moduleLock.Release();
  158. }
  159. }
  160. public Task<bool> RemoveModuleAsync<T>() => RemoveModuleAsync(typeof(T));
  161. public async Task<bool> RemoveModuleAsync(Type type)
  162. {
  163. await _moduleLock.WaitAsync().ConfigureAwait(false);
  164. try
  165. {
  166. if (!_typedModuleDefs.TryRemove(type, out var module))
  167. return false;
  168. return RemoveModuleInternal(module);
  169. }
  170. finally
  171. {
  172. _moduleLock.Release();
  173. }
  174. }
  175. private bool RemoveModuleInternal(ModuleInfo module)
  176. {
  177. if (!_moduleDefs.Remove(module))
  178. return false;
  179. foreach (var cmd in module.Commands)
  180. _map.RemoveCommand(cmd);
  181. foreach (var submodule in module.Submodules)
  182. {
  183. RemoveModuleInternal(submodule);
  184. }
  185. return true;
  186. }
  187. //Type Readers
  188. /// <summary>
  189. /// Adds a custom <see cref="TypeReader"/> to this <see cref="CommandService"/> for the supplied object type.
  190. /// If <typeparamref name="T"/> is a <see cref="ValueType"/>, a <see cref="NullableTypeReader{T}"/> will also be added.
  191. /// </summary>
  192. /// <typeparam name="T">The object type to be read by the <see cref="TypeReader"/>.</typeparam>
  193. /// <param name="reader">An instance of the <see cref="TypeReader"/> to be added.</param>
  194. public void AddTypeReader<T>(TypeReader reader)
  195. => AddTypeReader(typeof(T), reader);
  196. /// <summary>
  197. /// Adds a custom <see cref="TypeReader"/> to this <see cref="CommandService"/> for the supplied object type.
  198. /// If <paramref name="type"/> is a <see cref="ValueType"/>, a <see cref="NullableTypeReader{T}"/> for the value type will also be added.
  199. /// </summary>
  200. /// <param name="type">A <see cref="Type"/> instance for the type to be read.</param>
  201. /// <param name="reader">An instance of the <see cref="TypeReader"/> to be added.</param>
  202. public void AddTypeReader(Type type, TypeReader reader)
  203. {
  204. var readers = _typeReaders.GetOrAdd(type, x => new ConcurrentDictionary<Type, TypeReader>());
  205. readers[reader.GetType()] = reader;
  206. if (type.GetTypeInfo().IsValueType)
  207. AddNullableTypeReader(type, reader);
  208. }
  209. internal void AddNullableTypeReader(Type valueType, TypeReader valueTypeReader)
  210. {
  211. var readers = _typeReaders.GetOrAdd(typeof(Nullable<>).MakeGenericType(valueType), x => new ConcurrentDictionary<Type, TypeReader>());
  212. var nullableReader = NullableTypeReader.Create(valueType, valueTypeReader);
  213. readers[nullableReader.GetType()] = nullableReader;
  214. }
  215. internal IDictionary<Type, TypeReader> GetTypeReaders(Type type)
  216. {
  217. if (_typeReaders.TryGetValue(type, out var definedTypeReaders))
  218. return definedTypeReaders;
  219. return null;
  220. }
  221. internal TypeReader GetDefaultTypeReader(Type type)
  222. {
  223. if (_defaultTypeReaders.TryGetValue(type, out var reader))
  224. return reader;
  225. var typeInfo = type.GetTypeInfo();
  226. //Is this an enum?
  227. if (typeInfo.IsEnum)
  228. {
  229. reader = EnumTypeReader.GetReader(type);
  230. _defaultTypeReaders[type] = reader;
  231. return reader;
  232. }
  233. //Is this an entity?
  234. for (int i = 0; i < _entityTypeReaders.Count; i++)
  235. {
  236. if (type == _entityTypeReaders[i].Item1 || typeInfo.ImplementedInterfaces.Contains(_entityTypeReaders[i].Item1))
  237. {
  238. reader = Activator.CreateInstance(_entityTypeReaders[i].Item2.MakeGenericType(type)) as TypeReader;
  239. _defaultTypeReaders[type] = reader;
  240. return reader;
  241. }
  242. }
  243. return null;
  244. }
  245. //Execution
  246. public SearchResult Search(ICommandContext context, int argPos)
  247. => Search(context, context.Message.Content.Substring(argPos));
  248. public SearchResult Search(ICommandContext context, string input)
  249. {
  250. string searchInput = _caseSensitive ? input : input.ToLowerInvariant();
  251. var matches = _map.GetCommands(searchInput).OrderByDescending(x => x.Command.Priority).ToImmutableArray();
  252. if (matches.Length > 0)
  253. return SearchResult.FromSuccess(input, matches);
  254. else
  255. return SearchResult.FromError(CommandError.UnknownCommand, "Unknown command.");
  256. }
  257. public Task<IResult> ExecuteAsync(ICommandContext context, int argPos, IServiceProvider services, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Exception)
  258. => ExecuteAsync(context, context.Message.Content.Substring(argPos), services, multiMatchHandling);
  259. public async Task<IResult> ExecuteAsync(ICommandContext context, string input, IServiceProvider services, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Exception)
  260. {
  261. services = services ?? EmptyServiceProvider.Instance;
  262. var searchResult = Search(context, input);
  263. if (!searchResult.IsSuccess)
  264. return searchResult;
  265. var commands = searchResult.Commands;
  266. var preconditionResults = new Dictionary<CommandMatch, PreconditionResult>();
  267. foreach (var match in commands)
  268. {
  269. preconditionResults[match] = await match.Command.CheckPreconditionsAsync(context, services).ConfigureAwait(false);
  270. }
  271. var successfulPreconditions = preconditionResults
  272. .Where(x => x.Value.IsSuccess)
  273. .ToArray();
  274. if (successfulPreconditions.Length == 0)
  275. {
  276. //All preconditions failed, return the one from the highest priority command
  277. var bestCandidate = preconditionResults
  278. .OrderByDescending(x => x.Key.Command.Priority)
  279. .FirstOrDefault(x => !x.Value.IsSuccess);
  280. return bestCandidate.Value;
  281. }
  282. //If we get this far, at least one precondition was successful.
  283. var parseResultsDict = new Dictionary<CommandMatch, ParseResult>();
  284. foreach (var pair in successfulPreconditions)
  285. {
  286. var parseResult = await pair.Key.ParseAsync(context, searchResult, pair.Value, services).ConfigureAwait(false);
  287. if (parseResult.Error == CommandError.MultipleMatches)
  288. {
  289. IReadOnlyList<TypeReaderValue> argList, paramList;
  290. switch (multiMatchHandling)
  291. {
  292. case MultiMatchHandling.Best:
  293. argList = parseResult.ArgValues.Select(x => x.Values.OrderByDescending(y => y.Score).First()).ToImmutableArray();
  294. paramList = parseResult.ParamValues.Select(x => x.Values.OrderByDescending(y => y.Score).First()).ToImmutableArray();
  295. parseResult = ParseResult.FromSuccess(argList, paramList);
  296. break;
  297. }
  298. }
  299. parseResultsDict[pair.Key] = parseResult;
  300. }
  301. // Calculates the 'score' of a command given a parse result
  302. float CalculateScore(CommandMatch match, ParseResult parseResult)
  303. {
  304. float argValuesScore = 0, paramValuesScore = 0;
  305. if (match.Command.Parameters.Count > 0)
  306. {
  307. var argValuesSum = parseResult.ArgValues?.Sum(x => x.Values.OrderByDescending(y => y.Score).FirstOrDefault().Score) ?? 0;
  308. var paramValuesSum = parseResult.ParamValues?.Sum(x => x.Values.OrderByDescending(y => y.Score).FirstOrDefault().Score) ?? 0;
  309. argValuesScore = argValuesSum / match.Command.Parameters.Count;
  310. paramValuesScore = paramValuesSum / match.Command.Parameters.Count;
  311. }
  312. var totalArgsScore = (argValuesScore + paramValuesScore) / 2;
  313. return match.Command.Priority + totalArgsScore * 0.99f;
  314. }
  315. //Order the parse results by their score so that we choose the most likely result to execute
  316. var parseResults = parseResultsDict
  317. .OrderByDescending(x => CalculateScore(x.Key, x.Value));
  318. var successfulParses = parseResults
  319. .Where(x => x.Value.IsSuccess)
  320. .ToArray();
  321. if (successfulParses.Length == 0)
  322. {
  323. //All parses failed, return the one from the highest priority command, using score as a tie breaker
  324. var bestMatch = parseResults
  325. .FirstOrDefault(x => !x.Value.IsSuccess);
  326. return bestMatch.Value;
  327. }
  328. //If we get this far, at least one parse was successful. Execute the most likely overload.
  329. var chosenOverload = successfulParses[0];
  330. return await chosenOverload.Key.ExecuteAsync(context, chosenOverload.Value, services).ConfigureAwait(false);
  331. }
  332. }
  333. }