├── Sample.DiscordBot.Host ├── appconfig.json ├── DiscordBotHostModule.cs ├── Sample.DiscordBot.Host.csproj └── Program.cs ├── README.md ├── Sample.DiscordBot.Application ├── Commands │ ├── IDiscordCommandContextAccessor.cs │ ├── DiscordCommandContextAccessor.cs │ └── DiscordCommandHandler.cs ├── DiscordBotApplicationModule.cs ├── Authentication │ ├── IDiscordUserResolver.cs │ ├── DiscordUserResolver.cs │ └── DiscordCurrentPrincipalAccessor.cs ├── Sample.DiscordBot.Application.csproj ├── Modules │ └── PublicModule.cs └── Authorization │ └── RequireAuthorizationAttribute.cs ├── Sample.DiscordBot.Application.Contracts ├── Permissions │ ├── DiscordBotPermissions.cs │ └── DiscordBotPermissionDefinitionProvider.cs ├── Sample.DiscordBot.Application.Contracts.csproj └── DiscordApplicationContractsModule.cs ├── LICENSE ├── Sample.DiscordBot.sln ├── .gitignore └── BlogPost.md /Sample.DiscordBot.Host/appconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "Discord": { 3 | "Token": "xxxxx" 4 | } 5 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AbpDiscordBot 2 | Sample DiscordBot integration with ABP. See [here](https://github.com/Trojaner/AbpDiscordBot/blob/main/BlogPost.md) for more. 3 | -------------------------------------------------------------------------------- /Sample.DiscordBot.Application/Commands/IDiscordCommandContextAccessor.cs: -------------------------------------------------------------------------------- 1 | using Discord.Commands; 2 | 3 | namespace Sample.DiscordBot.Commands 4 | { 5 | public interface IDiscordCommandContextAccessor 6 | { 7 | ICommandContext CommandContext { get; set; } 8 | int ArgsPos { get; set; } 9 | } 10 | } -------------------------------------------------------------------------------- /Sample.DiscordBot.Application/DiscordBotApplicationModule.cs: -------------------------------------------------------------------------------- 1 | using Volo.Abp.Application; 2 | using Volo.Abp.Modularity; 3 | 4 | namespace Sample.DiscordBot 5 | { 6 | [DependsOn( 7 | typeof(AbpDddApplicationModule), 8 | typeof(DiscordBotApplicationContractsModule) 9 | )] 10 | public class DiscordBotApplicationModule : AbpModule 11 | { 12 | 13 | } 14 | } -------------------------------------------------------------------------------- /Sample.DiscordBot.Application/Commands/DiscordCommandContextAccessor.cs: -------------------------------------------------------------------------------- 1 | using Discord.Commands; 2 | using Volo.Abp.DependencyInjection; 3 | 4 | namespace Sample.DiscordBot.Commands 5 | { 6 | public class DiscordCommandContextAccessor : IDiscordCommandContextAccessor, IScopedDependency 7 | { 8 | public ICommandContext CommandContext { get; set; } 9 | public int ArgsPos { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /Sample.DiscordBot.Application.Contracts/Permissions/DiscordBotPermissions.cs: -------------------------------------------------------------------------------- 1 | namespace Sample.DiscordBot.Permissions 2 | { 3 | public class DiscordBotPermissions 4 | { 5 | public const string GroupName = "SampleDiscordBot"; 6 | 7 | public static class Commands 8 | { 9 | public const string Default = GroupName + ".Commands"; 10 | public const string Echo = Default + ".Echo"; 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /Sample.DiscordBot.Application/Authentication/IDiscordUserResolver.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Claims; 2 | using Discord; 3 | 4 | namespace Sample.DiscordBot.Authentication 5 | { 6 | public interface IDiscordUserResolver 7 | { 8 | // Get's the ABP identity of a discord user 9 | // Return null if you fail to resolve a user (e.g. user is not registered or linked yet) 10 | Task ResolveAsync(IUser user); 11 | } 12 | } -------------------------------------------------------------------------------- /Sample.DiscordBot.Application/Authentication/DiscordUserResolver.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Claims; 2 | using Discord; 3 | using Volo.Abp.DependencyInjection; 4 | 5 | namespace Sample.DiscordBot.Authentication 6 | { 7 | public class DiscordUserResolver : IDiscordUserResolver, ITransientDependency 8 | { 9 | public Task ResolveAsync(IUser user) 10 | { 11 | throw new NotImplementedException(); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Sample.DiscordBot.Host/DiscordBotHostModule.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Volo.Abp.Autofac; 3 | using Volo.Abp.Modularity; 4 | 5 | namespace Sample.DiscordBot 6 | { 7 | [DependsOn( 8 | typeof(AbpAutofacModule), 9 | typeof(DiscordBotApplicationModule))] 10 | public class DiscordBotHostModule : AbpModule 11 | { 12 | public override void ConfigureServices(ServiceConfigurationContext context) 13 | { 14 | var configuration = context.Services.GetConfiguration(); 15 | //... 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Sample.DiscordBot.Application.Contracts/Sample.DiscordBot.Application.Contracts.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | Sample.DiscordBot 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /Sample.DiscordBot.Application.Contracts/DiscordApplicationContractsModule.cs: -------------------------------------------------------------------------------- 1 | using Sample.DiscordBot.Permissions; 2 | using Volo.Abp.Application; 3 | using Volo.Abp.Authorization.Permissions; 4 | using Volo.Abp.Modularity; 5 | 6 | namespace Sample.DiscordBot 7 | { 8 | [DependsOn( 9 | typeof(AbpDddApplicationContractsModule) 10 | )] 11 | public class DiscordBotApplicationContractsModule : AbpModule 12 | { 13 | public override void ConfigureServices(ServiceConfigurationContext context) 14 | { 15 | Configure(options => 16 | { 17 | options.DefinitionProviders.Add(); 18 | }); 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /Sample.DiscordBot.Application.Contracts/Permissions/DiscordBotPermissionDefinitionProvider.cs: -------------------------------------------------------------------------------- 1 | namespace Sample.DiscordBot.Permissions 2 | { 3 | using Volo.Abp.Authorization.Permissions; 4 | 5 | public class DiscordBotPermissionDefinitionProvider : PermissionDefinitionProvider 6 | { 7 | public override void Define(IPermissionDefinitionContext context) 8 | { 9 | if (context.GetGroupOrNull(DiscordBotPermissions.GroupName) != null) 10 | { 11 | return; 12 | } 13 | 14 | var discordPermisssionGroup = context.AddGroup(DiscordBotPermissions.GroupName); 15 | discordPermisssionGroup.AddPermission(DiscordBotPermissions.Commands.Echo); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Sample.DiscordBot.Application/Authentication/DiscordCurrentPrincipalAccessor.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Claims; 2 | using Volo.Abp; 3 | using Volo.Abp.DependencyInjection; 4 | using Volo.Abp.Security.Claims; 5 | 6 | namespace Sample.DiscordBot.Authentication 7 | { 8 | [Dependency(ReplaceServices = true)] 9 | [ExposeServices(typeof(ICurrentPrincipalAccessor))] 10 | public class DiscordCurrentPrincipalAccessor : ICurrentPrincipalAccessor, IScopedDependency 11 | { 12 | public IDisposable Change(ClaimsPrincipal principal) 13 | { 14 | var previous = Principal; 15 | Principal = principal; 16 | return new DisposeAction(() => { Principal = previous; }); 17 | } 18 | 19 | public ClaimsPrincipal Principal { get; set; } 20 | } 21 | } -------------------------------------------------------------------------------- /Sample.DiscordBot.Application/Sample.DiscordBot.Application.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | Sample.DiscordBot 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /Sample.DiscordBot.Application/Modules/PublicModule.cs: -------------------------------------------------------------------------------- 1 | using Discord.Commands; 2 | using Sample.DiscordBot.Authorization; 3 | using Sample.DiscordBot.Permissions; 4 | using Volo.Abp.Users; 5 | 6 | namespace Sample.DiscordBot.Modules 7 | { 8 | public class PublicModule : ModuleBase 9 | { 10 | private readonly ICurrentUser _currentUser; 11 | public PublicModule( 12 | ICurrentUser currentUser 13 | ) 14 | { 15 | _currentUser = currentUser; 16 | } 17 | 18 | [Command("whoami")] 19 | public async Task WhoAmIAsync() 20 | { 21 | await ReplyAsync($"You are user {_currentUser.UserName}/{_currentUser.Id}"); 22 | } 23 | 24 | [Command("echo")] 25 | [RequireAuthorization(DiscordBotPermissions.Commands.Echo)] 26 | public async Task EchoAsync(string message) 27 | { 28 | await ReplyAsync($"You typed: {message}"); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Enes Sadık Özbek 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Sample.DiscordBot.Host/Sample.DiscordBot.Host.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | latest 8 | Sample.DiscordBot 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | PreserveNewest 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /Sample.DiscordBot.Application/Authorization/RequireAuthorizationAttribute.cs: -------------------------------------------------------------------------------- 1 | using Discord.Commands; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using Volo.Abp.Authorization.Permissions; 4 | using Volo.Abp.Users; 5 | 6 | namespace Sample.DiscordBot.Authorization 7 | { 8 | public class RequireAuthorizationAttribute : PreconditionAttribute 9 | { 10 | public string Permission { get; } 11 | 12 | public RequireAuthorizationAttribute(string permission = null) 13 | { 14 | Permission = permission; 15 | } 16 | 17 | public override async Task CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services) 18 | { 19 | var currentUser = services.GetRequiredService(); 20 | if (currentUser?.Id == null) 21 | { 22 | // Failed to resolve user 23 | return PreconditionResult.FromError( 24 | "You can not use this command because your discord account is not linked yet.\n"); 25 | } 26 | 27 | if (string.IsNullOrEmpty(Permission)) 28 | { 29 | return PreconditionResult.FromSuccess(); 30 | } 31 | 32 | var permissionChecker = services.GetRequiredService(); 33 | var isGranted = await permissionChecker.IsGrantedAsync(Permission); 34 | 35 | if (!isGranted) 36 | { 37 | return PreconditionResult.FromError( 38 | $"You do not have access to this command (missing permission: {Permission})."); 39 | } 40 | 41 | return PreconditionResult.FromSuccess(); 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /Sample.DiscordBot.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.31912.275 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample.DiscordBot.Host", "Sample.DiscordBot.Host\Sample.DiscordBot.Host.csproj", "{3BDB9C8A-67FD-4A97-94A9-A2FA8CE3C3EA}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample.DiscordBot.Application.Contracts", "Sample.DiscordBot.Application.Contracts\Sample.DiscordBot.Application.Contracts.csproj", "{5C783606-3C22-40E0-8423-0DDD7AF83243}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample.DiscordBot.Application", "Sample.DiscordBot.Application\Sample.DiscordBot.Application.csproj", "{416914AC-CD5E-4EB2-AAEB-AB562CD9D3AB}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {3BDB9C8A-67FD-4A97-94A9-A2FA8CE3C3EA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {3BDB9C8A-67FD-4A97-94A9-A2FA8CE3C3EA}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {3BDB9C8A-67FD-4A97-94A9-A2FA8CE3C3EA}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {3BDB9C8A-67FD-4A97-94A9-A2FA8CE3C3EA}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {5C783606-3C22-40E0-8423-0DDD7AF83243}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {5C783606-3C22-40E0-8423-0DDD7AF83243}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {5C783606-3C22-40E0-8423-0DDD7AF83243}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {5C783606-3C22-40E0-8423-0DDD7AF83243}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {416914AC-CD5E-4EB2-AAEB-AB562CD9D3AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {416914AC-CD5E-4EB2-AAEB-AB562CD9D3AB}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {416914AC-CD5E-4EB2-AAEB-AB562CD9D3AB}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {416914AC-CD5E-4EB2-AAEB-AB562CD9D3AB}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {08DE4BA6-981D-424E-8965-0083445829E2} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /Sample.DiscordBot.Host/Program.cs: -------------------------------------------------------------------------------- 1 | using Discord; 2 | using Discord.Addons.Hosting; 3 | using Discord.Commands; 4 | using Discord.WebSocket; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Microsoft.Extensions.Hosting; 8 | using Serilog; 9 | using Volo.Abp; 10 | 11 | namespace Sample.DiscordBot 12 | { 13 | public class Program 14 | { 15 | public static async Task Main(string[] args) 16 | { 17 | Log.Logger = new LoggerConfiguration() 18 | .WriteTo.Console() 19 | .CreateLogger(); 20 | 21 | try 22 | { 23 | var host = CreateHostBuilder(args).Build(); 24 | using (host) 25 | { 26 | var initializer = host.Services.GetRequiredService(); 27 | await initializer.InitializeAsync(host.Services); 28 | 29 | await host.RunAsync(); 30 | } 31 | 32 | return 0; 33 | } 34 | catch (Exception ex) 35 | { 36 | Log.Fatal(ex, "Host terminated unexpectedly!"); 37 | return 1; 38 | } 39 | finally 40 | { 41 | Log.CloseAndFlush(); 42 | } 43 | } 44 | 45 | internal static IHostBuilder CreateHostBuilder(string[] args) 46 | { 47 | return Host 48 | .CreateDefaultBuilder(args) 49 | .UseCommandService((context, config) => 50 | { 51 | config.LogLevel = LogSeverity.Verbose; 52 | config.DefaultRunMode = RunMode.Async; 53 | }) 54 | .ConfigureHostConfiguration(builder => 55 | { 56 | ConfigureConfiguration(args, builder); 57 | }) 58 | .ConfigureAppConfiguration(builder => 59 | { 60 | ConfigureConfiguration(args, builder); 61 | }) 62 | .ConfigureServices((_, services) => 63 | { 64 | services.AddApplication(); 65 | }) 66 | .ConfigureDiscordHost((context, configurationBuilder) => 67 | { 68 | configurationBuilder.Token = context.Configuration["Discord:Token"]; 69 | }) 70 | .UseAutofac() 71 | .UseSerilog() 72 | .UseConsoleLifetime(); 73 | } 74 | 75 | internal static void ConfigureConfiguration(string[] args, IConfigurationBuilder builder) 76 | { 77 | builder 78 | .SetBasePath(Directory.GetCurrentDirectory()) 79 | .AddJsonFile("appsettings.json", optional: false) 80 | .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("APP_ENVIRONMENT") ?? "Production"}.json", optional: true, reloadOnChange: true) 81 | .AddUserSecrets(typeof(Program).Assembly, true) 82 | .AddCommandLine(args) 83 | .AddEnvironmentVariables(); 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /Sample.DiscordBot.Application/Commands/DiscordCommandHandler.cs: -------------------------------------------------------------------------------- 1 | namespace Sample.DiscordBot.Commands 2 | { 3 | using Authentication; 4 | using Discord; 5 | using Discord.Commands; 6 | using Discord.WebSocket; 7 | using Microsoft.AspNetCore.Identity; 8 | using Microsoft.Extensions.DependencyInjection; 9 | using Microsoft.Extensions.Logging; 10 | using Microsoft.Extensions.Options; 11 | using Volo.Abp.DependencyInjection; 12 | using Volo.Abp.Security.Claims; 13 | using Volo.Abp.Uow; 14 | 15 | public class DiscordCommandHandler : ISingletonDependency, IDisposable 16 | { 17 | public const string CommandPrefix = "!"; // alternatively read it from the config 18 | 19 | private readonly ILogger _logger; 20 | private readonly IServiceProvider _serviceProvider; 21 | private readonly DiscordSocketClient _discordClient; 22 | private readonly IdentityOptions _identityOptions; 23 | private readonly CommandService _commandService; 24 | private readonly Dictionary> _disposables; 25 | 26 | private bool _isSubscribed; 27 | 28 | public DiscordCommandHandler( 29 | ILogger logger, 30 | IServiceProvider serviceProvider, 31 | DiscordSocketClient discordClient, 32 | IOptions identityOptionsAccessor, 33 | CommandService commandService) 34 | { 35 | _disposables = new Dictionary>(); 36 | _logger = logger; 37 | _serviceProvider = serviceProvider; 38 | _identityOptions = identityOptionsAccessor.Value; 39 | _discordClient = discordClient; 40 | _commandService = commandService; 41 | } 42 | 43 | public void Subscribe() 44 | { 45 | if (!_isSubscribed) 46 | { 47 | _discordClient.MessageReceived += HandleMessage; 48 | _commandService.CommandExecuted += CommandExecutedAsync; 49 | _isSubscribed = true; 50 | } 51 | } 52 | 53 | public void Unsubscribe() 54 | { 55 | if (_isSubscribed) 56 | { 57 | _discordClient.MessageReceived -= HandleMessage; 58 | _commandService.CommandExecuted -= CommandExecutedAsync; 59 | _isSubscribed = false; 60 | } 61 | } 62 | 63 | private async Task HandleMessage(SocketMessage incomingMessage) 64 | { 65 | if (incomingMessage is not SocketUserMessage { Source: MessageSource.User } message) 66 | { 67 | // Message is not from a user 68 | return; 69 | } 70 | 71 | // Optionally log all messages 72 | // _logger.LogInformation($"#{message.Channel.Name} <{message.Author.Username}#{message.Author.Discriminator}>: {message.Content}"); 73 | 74 | var argPos = 0; 75 | if (!message.HasStringPrefix(CommandPrefix, ref argPos)) 76 | { 77 | // message is not a command; ignore 78 | return; 79 | } 80 | 81 | var context = new SocketCommandContext(_discordClient, message); 82 | 83 | var scope = _serviceProvider.CreateScope(); 84 | var uow = _serviceProvider.GetService().Begin(); 85 | 86 | var disposableContainer = new List { uow, scope }; 87 | _disposables.Add(context, disposableContainer); 88 | 89 | try 90 | { 91 | var contextAccessor = scope.ServiceProvider.GetRequiredService(); 92 | contextAccessor.ArgsPos = argPos; 93 | contextAccessor.CommandContext = context; 94 | 95 | var userResolver = scope.ServiceProvider.GetRequiredService(); 96 | var user = await userResolver.ResolveAsync(context.User); 97 | 98 | var discordPrincipalAccessor = 99 | (DiscordCurrentPrincipalAccessor)scope.ServiceProvider 100 | .GetRequiredService(); 101 | discordPrincipalAccessor.Principal = user; 102 | 103 | await _commandService.ExecuteAsync(context, argPos, scope.ServiceProvider); 104 | } 105 | catch 106 | { 107 | DisposeContext(context); 108 | throw; 109 | } 110 | } 111 | 112 | public async Task CommandExecutedAsync(Optional command, ICommandContext context, IResult result) 113 | { 114 | DisposeContext(context); 115 | 116 | if (command.IsSpecified && !result.IsSuccess) 117 | { 118 | // Error or exception occurred; notify user 119 | var prefix = ""; 120 | if (context.Guild != null) 121 | { 122 | // Not a private message; so ping user 123 | prefix = $"<@!{context.User.Id}>: "; 124 | } 125 | 126 | await context.Channel.SendMessageAsync(prefix + result.ErrorReason); 127 | } 128 | } 129 | 130 | private void DisposeContext(ICommandContext context) 131 | { 132 | var disposables = _disposables[context]; 133 | _disposables.Remove(context); 134 | 135 | foreach (var disposable in disposables) 136 | { 137 | disposable.Dispose(); 138 | } 139 | } 140 | 141 | public void Dispose() 142 | { 143 | Unsubscribe(); 144 | } 145 | } 146 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /BlogPost.md: -------------------------------------------------------------------------------- 1 | # What is Discord? 2 | [Discord](https://discord.com/) is a popular chat and VoIP platform. In this article we will write a Discord bot that integrates with ABP. This way we can use ABP features such as unit of work, authorization, users, etc. 3 | 4 | Note: this article expects that you already have a running ABP website and that the bot will complement it. 5 | 6 | ABP has also just created [it's own Discord server](https://discord.gg/CrYrd5vcGh) too. Don't forget to join it! 7 | 8 | ## Discord Integration Libraries for .NET 9 | There are two popular unofficial Discord integration libraries for .NET: [DSharpPlus](https://github.com/DSharpPlus/DSharpPlus) and [Discord.NET](https://github.com/discord-net/Discord.Net). We will use Discord .NET as it is modular and supports [.NET Generic Host](https://docs.microsoft.com/en-us/dotnet/core/extensions/generic-host) integration via a [third party package](https://github.com/Hawxy/Discord.Addons.Hosting). 10 | 11 | # Getting started 12 | We will create a Discord bot with .NET generic hosting support first. 13 | 14 | Create a new .NET console project and name it Sample.DiscordBot.Host. After that, install `Discord.Net`, `Serilog.Extensions.Hosting`, `Serilog.Sinks.Console` and `Discord.Addons.Hosting` from NuGet. 15 | 16 | ## Setting up .NET Generic Host for Discord 17 | Replace the Main method with the following code: 18 | ```c# 19 | 20 | namespace Sample.DiscordBot 21 | { 22 | public class Program 23 | { 24 | public static async Task Main(string[] args) 25 | { 26 | Log.Logger = new LoggerConfiguration() 27 | .WriteTo.Console() 28 | .CreateLogger(); 29 | 30 | try 31 | { 32 | var host = CreateHostBuilder(args).Build(); 33 | using (host) 34 | { 35 | await host.RunAsync(); 36 | } 37 | 38 | return 0; 39 | } 40 | catch (Exception ex) 41 | { 42 | Log.Fatal(ex, "Host terminated unexpectedly!"); 43 | return 1; 44 | } 45 | finally 46 | { 47 | Log.CloseAndFlush(); 48 | } 49 | } 50 | 51 | internal static IHostBuilder CreateHostBuilder(string[] args) 52 | { 53 | return Host 54 | .CreateDefaultBuilder(args) 55 | .UseCommandService((context, config) => 56 | { 57 | config.LogLevel = LogSeverity.Verbose; 58 | config.DefaultRunMode = RunMode.Async; 59 | }) 60 | .ConfigureHostConfiguration(builder => 61 | { 62 | ConfigureConfiguration(args, builder); 63 | }) 64 | .ConfigureAppConfiguration(builder => 65 | { 66 | ConfigureConfiguration(args, builder); 67 | }) 68 | .UseSerilog() 69 | .UseConsoleLifetime(); 70 | } 71 | 72 | internal static void ConfigureConfiguration(string[] args, IConfigurationBuilder builder) 73 | { 74 | builder 75 | .SetBasePath(Directory.GetCurrentDirectory()) 76 | .AddJsonFile("appsettings.json", optional: false) 77 | .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("APP_ENVIRONMENT") ?? "Production"}.json", optional: true, reloadOnChange: true) 78 | .AddUserSecrets(typeof(Program).Assembly, true) 79 | .AddCommandLine(args) 80 | .AddEnvironmentVariables(); 81 | } 82 | } 83 | } 84 | ``` 85 | 86 | ## Integrating ABP 87 | ### Initializing ABP 88 | To initialze ABP, install the `Volo.Abp.Core` and `Volo.Abp.Autofac` packages from NuGet and call the ABP initialization service: 89 | ```c# 90 | ... 91 | using (host) 92 | { 93 | // Initialize ABP 94 | var initializer = host.Services.GetRequiredService(); 95 | await initializer.InitializeAsync(host.Services); 96 | 97 | await host.RunAsync(); 98 | } 99 | ... 100 | ``` 101 | 102 | ### Adding the Host module 103 | Create a new class called `DiscordBotHostModule`: 104 | ```c# 105 | namespace Sample.DiscordBot 106 | { 107 | [DependsOn(typeof(AbpAutofacModule))] 108 | public class DiscordBotHostModule : AbpModule 109 | { 110 | public override void ConfigureServices(ServiceConfigurationContext context) 111 | { 112 | var configuration = context.Services.GetConfiguration(); 113 | //... 114 | } 115 | } 116 | } 117 | ``` 118 | 119 | Register the module in the host builder and add Autofac: 120 | ```c# 121 | return Host 122 | ... 123 | .ConfigureServices((_, services) => 124 | { 125 | services.AddApplication(); 126 | }) 127 | .UseAutofac() 128 | ... 129 | ``` 130 | 131 | ### Linking Discord and ABP Users 132 | Create a new project, name it `Sample.DiscordBot.Application` and install `Discord.NET`, `Microsoft.AspNetCore.Identity` and `Volo.Abp.Ddd.Application`. 133 | 134 | Create and implement the following interface: 135 | ```c# 136 | namespace Sample.DiscordBot.Authentication 137 | { 138 | public interface IDiscordUserResolver 139 | { 140 | // Get's the ABP identity of a discord user 141 | // Return null if you fail to resolve a user (e.g. user is not registered or linked yet) 142 | Task ResolveAsync(IUser user); 143 | } 144 | } 145 | ``` 146 | 147 | How you resolve users is up to you. For example, you could add a command like "!link" and redirect to your website with a token. Another alternative would be linking the discord account via the website with OpenID Connect. After that you could resolve the user with an API call to your identity backend. 148 | 149 | Create and register a principal accessor and register it in the application module. The principal accessor will allow services and commands to resolve the current ABP user. 150 | ```c# 151 | namespace Sample.DiscordBot.Authentication 152 | { 153 | [Dependency(ReplaceServices = true)] 154 | [ExposeServices(typeof(ICurrentPrincipalAccessor))] 155 | public class DiscordCurrentPrincipalAccessor : ICurrentPrincipalAccessor, IScopedDependency 156 | { 157 | public IDisposable Change(ClaimsPrincipal principal) 158 | { 159 | var previous = Principal; 160 | Principal = principal; 161 | return new DisposeAction(() => { Principal = previous; }); 162 | } 163 | 164 | public ClaimsPrincipal Principal { get; set; } 165 | } 166 | } 167 | ``` 168 | 169 | ### Adding Permissions for Commands 170 | 171 | Create another new project, name it Sample.DiscordBot.Application.Contracts and install the `Volo.Abp.Ddd.Domain` and `Volo.Abp.Authorization.Abstractions` packages. 172 | 173 | After that [create and register your permissions](https://docs.abp.io/en/abp/4.4/Authorization#permission-system): 174 | ```c# 175 | namespace Sample.DiscordBot.Permissions 176 | { 177 | public class DiscordBotPermissions 178 | { 179 | public const string GroupName = "SampleDiscordBot"; 180 | 181 | public static class Commands 182 | { 183 | public const string Default = GroupName + ".Commands"; 184 | public const string Echo = Default + ".Echo"; 185 | } 186 | } 187 | } 188 | ``` 189 | 190 | ```c# 191 | namespace Sample.DiscordBot.Permissions 192 | { 193 | public class DiscordBotPermissionDefinitionProvider : PermissionDefinitionProvider 194 | { 195 | public override void Define(IPermissionDefinitionContext context) 196 | { 197 | if (context.GetGroupOrNull(DiscordBotPermissions.GroupName) != null) 198 | { 199 | return; 200 | } 201 | 202 | var discordPermisssionGroup = context.AddGroup(DiscordBotPermissions.GroupName); 203 | discordPermisssionGroup.AddPermission(DiscordBotPermissions.Commands.Echo); 204 | } 205 | } 206 | } 207 | ``` 208 | 209 | Create the application contracts ABP module and register the permission definitions: 210 | ```c# 211 | namespace Sample.DiscordBot 212 | { 213 | [DependsOn( 214 | typeof(AbpDddApplicationContractsModule) 215 | )] 216 | public class DiscordBotApplicationContractsModule : AbpModule 217 | { 218 | public override void ConfigureServices(ServiceConfigurationContext context) 219 | { 220 | Configure(options => 221 | { 222 | options.DefinitionProviders.Add(); 223 | }); 224 | } 225 | } 226 | } 227 | ``` 228 | 229 | Add the application contracts module as dependency to the host module. 230 | 231 | ### Handling Discord commands 232 | Similar to the principal accessor, create a command context accessor in the application layer so we can access the current command context from commands and services: 233 | ```c# 234 | namespace Sample.DiscordBot.Commands 235 | { 236 | public interface IDiscordCommandContextAccessor 237 | { 238 | ICommandContext CommandContext { get; set; } 239 | int ArgsPos { get; set; } 240 | } 241 | } 242 | ``` 243 | 244 | ```c# 245 | namespace Sample.DiscordBot.Commands 246 | { 247 | public class DiscordCommandContextAccessor : IDiscordCommandContextAccessor, IScopedDependency 248 | { 249 | public ICommandContext CommandContext { get; set; } 250 | public int ArgsPos { get; set; } 251 | } 252 | } 253 | ``` 254 | 255 | Now we can implement the command handler. The command handler will 256 | * create a unit of work scope for each command execution, 257 | * create a DI scope for each command execution for scoped dependencies, 258 | * set the current command context and 259 | * set the current user and principal. 260 | 261 | The command handler is the heart of the discord bot ABP integration. Add the following to the host module: 262 | 263 | ```c# 264 | namespace Sample.DiscordBot.Commands 265 | { 266 | public class DiscordCommandHandler : ISingletonDependency, IDisposable 267 | { 268 | public const string CommandPrefix = "!"; // alternatively read it from the config 269 | 270 | private readonly ILogger _logger; 271 | private readonly IServiceProvider _serviceProvider; 272 | private readonly DiscordSocketClient _discordClient; 273 | private readonly IdentityOptions _identityOptions; 274 | private readonly CommandService _commandService; 275 | private readonly Dictionary> _disposables; 276 | 277 | private bool _isSubscribed; 278 | 279 | public DiscordCommandHandler( 280 | ILogger logger, 281 | IServiceProvider serviceProvider, 282 | DiscordSocketClient discordClient, 283 | IOptions identityOptionsAccessor, 284 | CommandService commandService) 285 | { 286 | _disposables = new Dictionary>(); 287 | _logger = logger; 288 | _serviceProvider = serviceProvider; 289 | _identityOptions = identityOptionsAccessor.Value; 290 | _discordClient = discordClient; 291 | _commandService = commandService; 292 | } 293 | 294 | public void Subscribe() 295 | { 296 | if (!_isSubscribed) 297 | { 298 | _discordClient.MessageReceived += HandleMessage; 299 | _commandService.CommandExecuted += CommandExecutedAsync; 300 | _isSubscribed = true; 301 | } 302 | } 303 | 304 | public void Unsubscribe() 305 | { 306 | if (_isSubscribed) 307 | { 308 | _discordClient.MessageReceived -= HandleMessage; 309 | _commandService.CommandExecuted -= CommandExecutedAsync; 310 | _isSubscribed = false; 311 | } 312 | } 313 | 314 | private async Task HandleMessage(SocketMessage incomingMessage) 315 | { 316 | if (!(incomingMessage is SocketUserMessage message 317 | || message.Source != MessageSource.User) 318 | { 319 | // Message is not from a user 320 | return; 321 | } 322 | 323 | // Optionally log all messages 324 | // _logger.LogInformation($"#{message.Channel.Name} <{message.Author.Username}#{message.Author.Discriminator}>: {message.Content}"); 325 | 326 | var argPos = 0; 327 | if (!message.HasStringPrefix(CommandPrefix, ref argPos)) 328 | { 329 | // message is not a command; ignore 330 | return; 331 | } 332 | 333 | var context = new SocketCommandContext(_discordClient, message); 334 | 335 | var scope = _serviceProvider.CreateScope(); 336 | var uow = _serviceProvider.GetService().Begin(); 337 | 338 | var disposableContainer = new List { uow, scope }; 339 | _disposables.Add(context, disposableContainer); 340 | 341 | try 342 | { 343 | var contextAccessor = scope.ServiceProvider.GetRequiredService(); 344 | contextAccessor.ArgsPos = argPos; 345 | contextAccessor.CommandContext = context; 346 | 347 | var userResolver= scope.ServiceProvider.GetRequiredService(); 348 | var user = await userResolver.ResolveAsync(context.User); 349 | 350 | var discordPrincipalAccessor = 351 | (DiscordCurrentPrincipalAccessor)scope.ServiceProvider 352 | .GetRequiredService(); 353 | discordPrincipalAccessor.Principal = user; 354 | 355 | await _commandService.ExecuteAsync(context, argPos, scope.ServiceProvider); 356 | } 357 | catch 358 | { 359 | DisposeContext(context); 360 | throw; 361 | } 362 | } 363 | 364 | public async Task CommandExecutedAsync(Optional command, ICommandContext context, IResult result) 365 | { 366 | DisposeContext(context); 367 | 368 | if (command.IsSpecified && !result.IsSuccess) 369 | { 370 | // Error or exception occurred; notify user 371 | var prefix = ""; 372 | if (context.Guild != null) 373 | { 374 | // Not a private message; so ping user 375 | prefix = $"<@!{context.User.Id}>: "; 376 | } 377 | 378 | await context.Channel.SendMessageAsync(prefix + result.ErrorReason); 379 | } 380 | } 381 | 382 | private void DisposeContext(ICommandContext context) 383 | { 384 | var disposables = _disposables[context]; 385 | _disposables.Remove(context); 386 | 387 | foreach (var disposable in disposables) 388 | { 389 | disposable.Dispose(); 390 | } 391 | } 392 | 393 | public void Dispose() 394 | { 395 | Unsubscribe(); 396 | } 397 | } 398 | } 399 | ``` 400 | 401 | Update the host module to listen to Discord .NET events on application initialization: 402 | ```c# 403 | public override void OnApplicationInitialization(ApplicationInitializationContext context) 404 | { 405 | var commandHandler = context.ServiceProvider.GetRequiredService(); 406 | commandHandler.Subscribe(); 407 | } 408 | ``` 409 | 410 | ### Linking ABP Permissions 411 | Create a new attribute called RequireAuthorization: 412 | ```c# 413 | namespace Sample.DiscordBot.Authorization 414 | { 415 | public class RequireAuthorizationAttribute : PreconditionAttribute 416 | { 417 | public string Permission { get; } 418 | 419 | public RequireAuthorizationAttribute(string permission = null) 420 | { 421 | Permission = permission; 422 | } 423 | 424 | public override async Task CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services) 425 | { 426 | var currentUser = services.GetRequiredService(); 427 | if (currentUser?.Id == null) 428 | { 429 | // Failed to resolve user 430 | return PreconditionResult.FromError( 431 | "You can not use this command because your discord account is not linked yet.\n"); 432 | } 433 | 434 | if (string.IsNullOrEmpty(Permission)) 435 | { 436 | return PreconditionResult.FromSuccess(); 437 | } 438 | 439 | var permissionChecker = services.GetRequiredService(); 440 | var isGranted = await permissionChecker.IsGrantedAsync(Permission); 441 | 442 | if (!isGranted) 443 | { 444 | return PreconditionResult.FromError( 445 | $"You do not have access to this command (missing permission: {Permission})."); 446 | } 447 | 448 | return PreconditionResult.FromSuccess(); 449 | } 450 | } 451 | } 452 | ``` 453 | 454 | ### Adding Commands 455 | Create the application module: 456 | ```c# 457 | namespace Sample.DiscordBot 458 | { 459 | [DependsOn( 460 | typeof(AbpDddApplicationModule), 461 | typeof(DiscordBotApplicationContractsModule) 462 | )] 463 | public class DiscordBotApplicationModule : AbpModule 464 | { 465 | 466 | } 467 | } 468 | ``` 469 | 470 | Now you can add Discord .NET command modules: 471 | ```c# 472 | public class PublicModule : ModuleBase 473 | { 474 | private readonly ICurrentUser _currentUser; 475 | public PublicModule( 476 | ICurrentUser currentUser 477 | ) 478 | { 479 | _currentUser = currentUser; 480 | } 481 | 482 | [Command("whoami")] 483 | public async Task WhoAmIAsync() 484 | { 485 | await ReplyAsync($"You are user {_currentUser.UserName}/{_currentUser.Id}"); 486 | } 487 | 488 | [Command("echo")] 489 | [RequireAuthorization(DiscordBotPermissions.Commands.Echo)] 490 | public async Task EchoAsync(string message) 491 | { 492 | await ReplyAsync($"You typed: {message}"); 493 | } 494 | } 495 | ``` 496 | 497 | Note: you don't have to register this module anywhere. Discord .NET will automatically register it. 498 | 499 | ## Adding the Discord Bot Token 500 | Create a Discord bot token as explained in [this article](https://www.writebots.com/discord-bot-token/). After that add it to your appconfig.json like this: 501 | ```json 502 | { 503 | "Discord": { 504 | "Token": "..." 505 | } 506 | } 507 | ``` 508 | 509 | Add the following to the host builder to read the token from the config: 510 | ```c# 511 | return Host 512 | ... 513 | .ConfigureDiscordHost((context, configurationBuilder) => 514 | { 515 | configurationBuilder.Token = context.Configuration["Discord:Token"]; 516 | }) 517 | ``` 518 | 519 | ## Conclusion 520 | We now have a working discord bot that integrates with ABP's modularity, unit of work, principals/users and authorization. You can now easily use EntityFrameworkCore, auditing, local and distributed events, domain services, i18n, etc. 521 | 522 | # Source Code 523 | https://github.com/Trojaner/AbpDiscordBot 524 | --------------------------------------------------------------------------------