switch to .net configurationbuilder instead of dotenv

This commit is contained in:
Ben Harris 2017-12-03 15:59:01 -05:00
parent 6c47a590fb
commit 505a69d7f9
7 changed files with 123 additions and 23 deletions

View File

@ -1 +0,0 @@
TOKEN=""

2
.gitignore vendored
View File

@ -1,4 +1,4 @@
.env
_config.json
*.swp
*.*~

88
Commands/Help.cs Normal file
View File

@ -0,0 +1,88 @@
using Discord;
using Discord.Commands;
using Microsoft.Extensions.Configuration;
using System.Linq;
using System.Threading.Tasks;
namespace Example.Modules
{
public class HelpModule : ModuleBase<SocketCommandContext>
{
private readonly CommandService _service;
private readonly IConfigurationRoot _config;
public HelpModule(CommandService service, IConfigurationRoot config)
{
_service = service;
_config = config;
}
[Command("help")]
public async Task HelpAsync()
{
string prefix = _config["prefix"];
var builder = new EmbedBuilder()
{
Color = new Color(114, 137, 218),
Description = "These are the commands you can use"
};
foreach (var module in _service.Modules)
{
string description = null;
foreach (var cmd in module.Commands)
{
var result = await cmd.CheckPreconditionsAsync(Context);
if (result.IsSuccess)
description += $"{prefix}{cmd.Aliases.First()}\n";
}
if (!string.IsNullOrWhiteSpace(description))
{
builder.AddField(x =>
{
x.Name = module.Name;
x.Value = description;
x.IsInline = false;
});
}
}
await ReplyAsync("", false, builder.Build());
}
[Command("help")]
public async Task HelpAsync(string command)
{
var result = _service.Search(Context, command);
if (!result.IsSuccess)
{
await ReplyAsync($"Sorry, I couldn't find a command like **{command}**.");
return;
}
string prefix = _config["prefix"];
var builder = new EmbedBuilder()
{
Color = new Color(114, 137, 218),
Description = $"Here are some commands like **{command}**"
};
foreach (var match in result.Commands)
{
var cmd = match.Command;
builder.AddField(x =>
{
x.Name = string.Join(", ", cmd.Aliases);
x.Value = $"Parameters: {string.Join(", ", cmd.Parameters.Select(p => p.Name))}\n" +
$"Summary: {cmd.Summary}";
x.IsInline = false;
});
}
await ReplyAsync("", false, builder.Build());
}
}
}

View File

@ -22,7 +22,6 @@ namespace dotbot.Commands
[Group("sample")]
public class Sample : ModuleBase<SocketCommandContext>
{
// ~sample square 20 -> 400
[Command("square")]
[Summary("Squares a number.")]
public async Task SquareAsync([Summary("The number to square.")] int num)
@ -31,12 +30,6 @@ namespace dotbot.Commands
await Context.Channel.SendMessageAsync($"{num}^2 = {Math.Pow(num, 2)}");
}
// ~sample userinfo --> foxbot#0282
// ~sample userinfo @Khionu --> Khionu#8708
// ~sample userinfo Khionu#8708 --> Khionu#8708
// ~sample userinfo Khionu --> Khionu#8708
// ~sample userinfo 96642168176807936 --> Khionu#8708
// ~sample whois 96642168176807936 --> Khionu#8708
[Command("userinfo")]
[Summary("Returns info about the current user, or the user parameter, if one passed.")]
[Alias("user", "whois")]

View File

@ -1,6 +1,7 @@
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Reflection;
@ -12,27 +13,39 @@ namespace dotbot
{
private CommandService _commands;
private DiscordSocketClient _client;
private IConfigurationRoot _config;
private IServiceProvider _services;
public static void Main(string[] args)
=> new Program().MainAsync().GetAwaiter().GetResult();
=> new Program().StartAsync().GetAwaiter().GetResult();
public async Task MainAsync()
public async Task StartAsync()
{
var builder = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("_config.json");
_config = builder.Build();
// get token from _config.json file
// if your bot isn't connecting, rename _config.example.json to _config.json
// and then place your bot token between the quotes
string token = _config["tokens:discord"];
Console.WriteLine(token);
_client = new DiscordSocketClient();
_commands = new CommandService();
_client.Log += Log;
DotNetEnv.Env.Load();
string token = Environment.GetEnvironmentVariable("TOKEN");
_services = new ServiceCollection()
.AddSingleton(_client)
.AddSingleton(_commands)
.AddSingleton(_config)
.AddSingleton<Random>()
.BuildServiceProvider();
await InstallCommandsAsync();
// install all commands from the assembly
_client.MessageReceived += HandleCommandAsync;
await _commands.AddModulesAsync(Assembly.GetEntryAssembly());
await _client.LoginAsync(TokenType.Bot, token);
await _client.StartAsync();
@ -40,12 +53,6 @@ namespace dotbot
await Task.Delay(-1);
}
public async Task InstallCommandsAsync()
{
_client.MessageReceived += HandleCommandAsync;
await _commands.AddModulesAsync(Assembly.GetEntryAssembly());
}
private async Task HandleCommandAsync(SocketMessage arg)
{
var message = arg as SocketUserMessage;
@ -53,7 +60,7 @@ namespace dotbot
int argPos = 0;
if (!(message.HasCharPrefix(';', ref argPos) || message.HasMentionPrefix(_client.CurrentUser, ref argPos))) return;
if (!(message.HasStringPrefix(_config["prefix"], ref argPos) || message.HasMentionPrefix(_client.CurrentUser, ref argPos))) return;
var context = new SocketCommandContext(_client, message);

6
_config.example.json Normal file
View File

@ -0,0 +1,6 @@
{
"prefix": "!",
"tokens": {
"discord": ""
}
}

View File

@ -5,6 +5,13 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Discord.Net" Version="1.0.2" />
<PackageReference Include="DotNetEnv" Version="1.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<None Update="_config.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>