dotbot/Program.cs

84 lines
2.6 KiB
C#
Raw Normal View History

2017-12-03 20:22:18 +00:00
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using Microsoft.Extensions.Configuration;
2017-12-03 20:22:18 +00:00
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Reflection;
using System.Threading.Tasks;
namespace dotbot
{
public class Program
{
private CommandService _commands;
private DiscordSocketClient _client;
private IConfigurationRoot _config;
2017-12-03 20:22:18 +00:00
private IServiceProvider _services;
2017-12-04 13:01:02 +00:00
private Random _rand;
2017-12-03 20:22:18 +00:00
public static void Main(string[] args)
=> new Program().StartAsync().GetAwaiter().GetResult();
2017-12-03 20:22:18 +00:00
public async Task StartAsync()
2017-12-03 20:22:18 +00:00
{
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);
2017-12-03 20:22:18 +00:00
_client = new DiscordSocketClient();
_commands = new CommandService();
_client.Log += Log;
2017-12-04 13:01:02 +00:00
_rand = new Random();
2017-12-03 20:22:18 +00:00
_services = new ServiceCollection()
.AddSingleton(_client)
.AddSingleton(_commands)
.AddSingleton(_config)
2017-12-04 13:01:02 +00:00
.AddSingleton(_rand)
2017-12-03 20:22:18 +00:00
.BuildServiceProvider();
// install all commands from the assembly
_client.MessageReceived += HandleCommandAsync;
await _commands.AddModulesAsync(Assembly.GetEntryAssembly());
2017-12-03 20:22:18 +00:00
await _client.LoginAsync(TokenType.Bot, token);
await _client.StartAsync();
await Task.Delay(-1);
}
private async Task HandleCommandAsync(SocketMessage arg)
{
var message = arg as SocketUserMessage;
if (message == null) return;
int argPos = 0;
if (!(message.HasStringPrefix(_config["prefix"], ref argPos) || message.HasMentionPrefix(_client.CurrentUser, ref argPos))) return;
2017-12-03 20:22:18 +00:00
var context = new SocketCommandContext(_client, message);
var result = await _commands.ExecuteAsync(context, argPos, _services);
if (!result.IsSuccess)
await context.Channel.SendMessageAsync(result.ErrorReason);
}
private Task Log(LogMessage msg)
{
Console.WriteLine(msg.ToString());
return Task.CompletedTask;
}
}
}