NadekoBot/src/NadekoBot/NadekoBot.cs

397 lines
16 KiB
C#
Raw Normal View History

2016-08-15 14:57:40 +00:00
using Discord;
using Discord.Commands;
2016-08-13 18:45:08 +00:00
using Discord.WebSocket;
2016-08-15 14:57:40 +00:00
using NadekoBot.Services;
using NadekoBot.Services.Impl;
2016-08-18 21:00:54 +00:00
using NLog;
using NLog.Config;
using NLog.Targets;
2016-08-13 18:45:08 +00:00
using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using NadekoBot.Modules.Permissions;
using NadekoBot.TypeReaders;
2017-02-14 14:53:51 +00:00
using System.Collections.Immutable;
using System.Diagnostics;
2016-10-26 14:30:49 +00:00
using NadekoBot.Services.Database.Models;
2017-04-15 00:54:19 +00:00
using System.Threading;
2017-05-22 23:59:31 +00:00
using NadekoBot.Services.Searches;
2017-05-24 04:43:00 +00:00
using NadekoBot.Services.ClashOfClans;
using NadekoBot.Services.Music;
2017-05-25 02:24:43 +00:00
using NadekoBot.Services.CustomReactions;
2017-05-27 08:19:27 +00:00
using NadekoBot.Services.Games;
using NadekoBot.Services.Administration;
using NadekoBot.Services.Permissions;
using NadekoBot.Services.Utility;
using NadekoBot.Services.Help;
2017-06-04 09:40:34 +00:00
using System.IO;
2017-06-12 09:30:31 +00:00
using NadekoBot.Services.Pokemon;
using NadekoBot.DataStructures.ShardCom;
2016-08-13 18:45:08 +00:00
namespace NadekoBot
{
public class NadekoBot
{
2016-08-18 21:00:54 +00:00
private Logger _log;
2017-05-22 23:59:31 +00:00
/* I don't know how to make this not be static
* and keep the convenience of .WithOkColor
* and .WithErrorColor extensions methods.
* I don't want to pass botconfig every time I
* want to send a confirm or error message, so
* I'll keep this for now */
public static Color OkColor { get; private set; }
public static Color ErrorColor { get; private set; }
public ImmutableArray<GuildConfig> AllGuildConfigs { get; private set; }
2017-05-22 23:59:31 +00:00
public BotConfig BotConfig { get; }
public DbService Db { get; }
public CommandService CommandService { get; }
2017-06-01 08:11:05 +00:00
public CommandHandler CommandHandler { get; private set; }
public Localization Localization { get; private set; }
public NadekoStrings Strings { get; private set; }
public StatsService Stats { get; private set; }
2017-06-01 08:11:05 +00:00
public ImagesService Images { get; }
public CurrencyService Currency { get; }
public GoogleApiService GoogleApi { get; }
2016-09-15 15:31:02 +00:00
public DiscordSocketClient Client { get; }
2017-05-22 23:59:31 +00:00
public bool Ready { get; private set; }
2016-10-26 14:30:49 +00:00
public INServiceProvider Services { get; private set; }
public BotCredentials Credentials { get; }
2017-05-10 14:08:31 +00:00
private const string _mutexName = @"Global\nadeko_shards_lock";
private readonly Semaphore sem = new Semaphore(1, 1, _mutexName);
public int ShardId { get; }
private readonly Thread waitForParentKill;
private readonly ShardComClient _comClient = new ShardComClient();
public NadekoBot(int shardId, int parentProcessId)
2016-10-26 14:30:49 +00:00
{
if (shardId < 0)
throw new ArgumentOutOfRangeException(nameof(shardId));
ShardId = shardId;
LogSetup.SetupLogger();
2017-05-22 23:59:31 +00:00
_log = LogManager.GetCurrentClassLogger();
2017-06-04 09:40:34 +00:00
TerribleElevatedPermissionCheck();
waitForParentKill = new Thread(new ThreadStart(() =>
{
try
{
var p = Process.GetProcessById(parentProcessId);
if (p == null)
return;
p.WaitForExit();
}
finally
{
Environment.Exit(10);
}
}));
waitForParentKill.Start();
Credentials = new BotCredentials();
Db = new DbService(Credentials);
using (var uow = Db.UnitOfWork)
2016-10-26 14:30:49 +00:00
{
2017-01-12 00:21:32 +00:00
BotConfig = uow.BotConfig.GetOrCreate();
OkColor = new Color(Convert.ToUInt32(BotConfig.OkColor, 16));
ErrorColor = new Color(Convert.ToUInt32(BotConfig.ErrorColor, 16));
2016-10-26 14:30:49 +00:00
}
2017-05-22 23:59:31 +00:00
Client = new DiscordSocketClient(new DiscordSocketConfig
2016-08-13 18:45:08 +00:00
{
2016-09-06 21:34:00 +00:00
MessageCacheSize = 10,
2016-08-15 14:57:40 +00:00
LogLevel = LogSeverity.Warning,
2017-02-01 16:50:14 +00:00
ConnectionTimeout = int.MaxValue,
TotalShards = Credentials.TotalShards,
ShardId = shardId,
2017-06-17 12:07:15 +00:00
AlwaysDownloadUsers = false,
2016-08-13 18:45:08 +00:00
});
CommandService = new CommandService(new CommandServiceConfig()
2017-05-22 23:59:31 +00:00
{
2017-01-28 23:38:09 +00:00
CaseSensitiveCommands = false,
2017-06-16 22:17:07 +00:00
DefaultRunMode = RunMode.Async,
2016-12-31 16:34:21 +00:00
});
2016-08-18 21:00:54 +00:00
2017-06-01 08:11:05 +00:00
//foundation services
Images = new ImagesService();
Currency = new CurrencyService(BotConfig, Db);
GoogleApi = new GoogleApiService(Credentials);
StartSendingData();
#if GLOBAL_NADEKO
Client.Log += Client_Log;
#endif
}
2016-08-13 18:45:08 +00:00
private void StartSendingData()
{
Task.Run(async () =>
{
while (true)
{
await _comClient.Send(new ShardComMessage()
{
ConnectionState = Client.ConnectionState,
Guilds = Client.ConnectionState == ConnectionState.Connected ? Client.Guilds.Count : 0,
ShardId = Client.ShardId,
});
await Task.Delay(1000);
}
});
}
private void AddServices()
{
using (var uow = Db.UnitOfWork)
{
AllGuildConfigs = uow.GuildConfigs.GetAllGuildConfigs(Client.Guilds.Select(x => (long)x.Id).ToList()).ToImmutableArray();
}
Localization = new Localization(BotConfig.Locale, AllGuildConfigs.ToDictionary(x => x.GuildId, x => x.Locale), Db);
Strings = new NadekoStrings(Localization);
CommandHandler = new CommandHandler(Client, Db, BotConfig, AllGuildConfigs, CommandService, Credentials, this);
Stats = new StatsService(Client, CommandHandler, Credentials);
var soundcloudApiService = new SoundCloudApiService(Credentials);
2017-05-24 04:43:00 +00:00
#region help
var helpService = new HelpService(BotConfig, CommandHandler, Strings);
#endregion
2017-05-22 23:59:31 +00:00
//module services
//todo 90 - autodiscover, DI, and add instead of manual like this
#region utility
2017-05-29 23:53:16 +00:00
var crossServerTextService = new CrossServerTextService(AllGuildConfigs, Client);
var remindService = new RemindService(Client, BotConfig, Db);
2017-06-12 23:40:39 +00:00
var repeaterService = new MessageRepeaterService(this, Client, AllGuildConfigs);
var converterService = new ConverterService(Db);
2017-05-29 23:53:16 +00:00
var commandMapService = new CommandMapService(AllGuildConfigs);
2017-06-01 08:11:05 +00:00
var patreonRewardsService = new PatreonRewardsService(Credentials, Db, Currency);
var verboseErrorsService = new VerboseErrorsService(AllGuildConfigs, Db, CommandHandler, helpService);
2017-06-16 22:17:07 +00:00
var pruneService = new PruneService();
#endregion
#region permissions
2017-06-01 08:11:05 +00:00
var permissionsService = new PermissionService(Db, BotConfig, CommandHandler);
var blacklistService = new BlacklistService(BotConfig);
var cmdcdsService = new CmdCdService(AllGuildConfigs);
var filterService = new FilterService(Client, AllGuildConfigs);
var globalPermsService = new GlobalPermissionService(BotConfig);
#endregion
#region Searches
2017-06-01 08:11:05 +00:00
var searchesService = new SearchesService(Client, GoogleApi, Db);
var streamNotificationService = new StreamNotificationService(Db, Client, Strings);
var animeSearchService = new AnimeSearchService();
#endregion
2017-06-01 08:11:05 +00:00
var clashService = new ClashOfClansService(Client, Db, Localization, Strings);
var musicService = new MusicService(GoogleApi, Strings, Localization, Db, soundcloudApiService, Credentials, AllGuildConfigs);
var crService = new CustomReactionsService(permissionsService, Db, Client, CommandHandler, BotConfig);
#region Games
2017-06-01 08:11:05 +00:00
var gamesService = new GamesService(Client, BotConfig, AllGuildConfigs, Strings, Images, CommandHandler);
var chatterBotService = new ChatterBotService(Client, permissionsService, AllGuildConfigs, CommandHandler);
var pollService = new PollService(Client, Strings);
#endregion
#region administration
2017-06-01 08:11:05 +00:00
var administrationService = new AdministrationService(AllGuildConfigs, CommandHandler);
var greetSettingsService = new GreetSettingsService(Client, AllGuildConfigs, Db);
2017-06-01 08:11:05 +00:00
var selfService = new SelfService(Client, this, CommandHandler, Db, BotConfig, Localization, Strings, Credentials);
var vcRoleService = new VcRoleService(Client, AllGuildConfigs, Db);
2017-06-01 08:11:05 +00:00
var vPlusTService = new VplusTService(Client, AllGuildConfigs, Strings, Db);
var muteService = new MuteService(Client, AllGuildConfigs, Db);
2017-05-30 00:05:11 +00:00
var ratelimitService = new SlowmodeService(Client, AllGuildConfigs);
var protectionService = new ProtectionService(Client, AllGuildConfigs, muteService);
var playingRotateService = new PlayingRotateService(Client, BotConfig, musicService);
var gameVcService = new GameVoiceChannelService(Client, Db, AllGuildConfigs);
var autoAssignRoleService = new AutoAssignRoleService(Client, AllGuildConfigs);
2017-06-01 08:11:05 +00:00
var logCommandService = new LogCommandService(Client, Strings, AllGuildConfigs, Db, muteService, protectionService);
2017-06-12 23:40:39 +00:00
var guildTimezoneService = new GuildTimezoneService(AllGuildConfigs, Db);
#endregion
2017-05-27 08:19:27 +00:00
2017-06-12 09:30:31 +00:00
#region pokemon
var pokemonService = new PokemonService();
#endregion
2017-05-22 23:59:31 +00:00
//initialize Services
Services = new NServiceProvider.ServiceProviderBuilder()
2017-06-01 08:11:05 +00:00
.Add<ILocalization>(Localization)
.Add<IStatsService>(Stats)
.Add<IImagesService>(Images)
.Add<IGoogleApiService>(GoogleApi)
.Add<IStatsService>(Stats)
.Add<IBotCredentials>(Credentials)
.Add<CommandService>(CommandService)
2017-06-01 08:11:05 +00:00
.Add<NadekoStrings>(Strings)
.Add<DiscordSocketClient>(Client)
2017-05-24 04:43:00 +00:00
.Add<BotConfig>(BotConfig)
2017-06-01 08:11:05 +00:00
.Add<CurrencyService>(Currency)
.Add<CommandHandler>(CommandHandler)
.Add<DbService>(Db)
2017-05-22 23:59:31 +00:00
//modules
2017-05-29 23:53:16 +00:00
.Add(crossServerTextService)
.Add(commandMapService)
.Add(remindService)
.Add(repeaterService)
.Add(converterService)
.Add(verboseErrorsService)
2017-06-15 11:09:55 +00:00
.Add(patreonRewardsService)
2017-06-16 22:17:07 +00:00
.Add(pruneService)
2017-05-22 23:59:31 +00:00
.Add<SearchesService>(searchesService)
.Add(streamNotificationService)
.Add(animeSearchService)
2017-05-24 04:43:00 +00:00
.Add<ClashOfClansService>(clashService)
2017-05-25 02:24:43 +00:00
.Add<MusicService>(musicService)
.Add<GreetSettingsService>(greetSettingsService)
.Add<CustomReactionsService>(crService)
.Add<HelpService>(helpService)
2017-05-27 08:19:27 +00:00
.Add<GamesService>(gamesService)
.Add(chatterBotService)
.Add(pollService)
.Add<AdministrationService>(administrationService)
.Add(selfService)
.Add(vcRoleService)
.Add(vPlusTService)
.Add(muteService)
.Add(ratelimitService)
.Add(playingRotateService)
.Add(gameVcService)
.Add(autoAssignRoleService)
.Add(protectionService)
.Add(logCommandService)
2017-06-12 23:40:39 +00:00
.Add(guildTimezoneService)
.Add<PermissionService>(permissionsService)
.Add(blacklistService)
.Add(cmdcdsService)
.Add(filterService)
.Add(globalPermsService)
2017-06-12 09:30:31 +00:00
.Add<PokemonService>(pokemonService)
2017-05-22 23:59:31 +00:00
.Build();
2017-06-01 08:11:05 +00:00
CommandHandler.AddServices(Services);
//setup typereaders
CommandService.AddTypeReader<PermissionAction>(new PermissionActionTypeReader());
2017-06-01 08:11:05 +00:00
CommandService.AddTypeReader<CommandInfo>(new CommandTypeReader(CommandService, CommandHandler));
CommandService.AddTypeReader<CommandOrCrInfo>(new CommandOrCrTypeReader(crService, CommandService, CommandHandler));
CommandService.AddTypeReader<ModuleInfo>(new ModuleTypeReader(CommandService));
CommandService.AddTypeReader<ModuleOrCrInfo>(new ModuleOrCrTypeReader(CommandService));
CommandService.AddTypeReader<IGuild>(new GuildTypeReader(Client));
CommandService.AddTypeReader<GuildDateTime>(new GuildDateTimeTypeReader(guildTimezoneService));
2017-05-22 23:59:31 +00:00
}
private Task LoginAsync(string token)
2017-05-22 23:59:31 +00:00
{
2016-08-15 14:57:40 +00:00
//connect
try { sem.WaitOne(); } catch (AbandonedMutexException) { }
_log.Info("Shard {0} logging in ...", ShardId);
try
{
Client.LoginAsync(TokenType.Bot, token).GetAwaiter().GetResult();
Client.StartAsync().GetAwaiter().GetResult();
while (Client.ConnectionState != ConnectionState.Connected)
Task.Delay(100).GetAwaiter().GetResult();
}
finally
{
_log.Info("Shard {0} logged in ...", ShardId);
sem.Release();
}
return Task.CompletedTask;
//_log.Info("Waiting for all shards to connect...");
//while (!Client.Shards.All(x => x.ConnectionState == ConnectionState.Connected))
//{
// _log.Info("Connecting... {0}/{1}", Client.Shards.Count(x => x.ConnectionState == ConnectionState.Connected), Client.Shards.Count);
// await Task.Delay(1000).ConfigureAwait(false);
//}
}
public async Task RunAsync(params string[] args)
{
_log.Info("Starting NadekoBot v" + StatsService.BotVersion);
var sw = Stopwatch.StartNew();
await LoginAsync(Credentials.Token).ConfigureAwait(false);
_log.Info($"Shard {ShardId} loading services...");
AddServices();
2016-08-18 21:00:54 +00:00
sw.Stop();
_log.Info($"Shard {ShardId} connected in {sw.Elapsed.TotalSeconds:F2} s");
2016-08-18 21:00:54 +00:00
var stats = Services.GetService<IStatsService>();
stats.Initialize();
var commandHandler = Services.GetService<CommandHandler>();
var CommandService = Services.GetService<CommandService>();
// start handling messages received in commandhandler
2017-05-22 23:59:31 +00:00
await commandHandler.StartHandling().ConfigureAwait(false);
var _ = await CommandService.AddModulesAsync(this.GetType().GetTypeInfo().Assembly);
2017-06-15 17:16:50 +00:00
//Console.WriteLine(string.Join(", ", CommandService.Commands
// .Distinct(x => x.Name + x.Module.Name)
// .SelectMany(x => x.Aliases)
// .GroupBy(x => x)
// .Where(x => x.Count() > 1)
// .Select(x => x.Key + $"({x.Count()})")));
2017-06-15 17:16:50 +00:00
//unload modules which are not available on the public bot
2017-06-15 18:20:34 +00:00
#if GLOBAL_NADEKO
CommandService
.Modules
.ToArray()
.Where(x => x.Preconditions.Any(y => y.GetType() == typeof(NoPublicBot)))
.ForEach(x => CommandService.RemoveModuleAsync(x));
#endif
2016-10-12 22:32:11 +00:00
Ready = true;
_log.Info($"Shard {ShardId} ready.");
//_log.Info(await stats.Print().ConfigureAwait(false));
}
2016-08-13 18:45:08 +00:00
2017-01-15 01:08:14 +00:00
private Task Client_Log(LogMessage arg)
{
_log.Warn(arg.Source + " | " + arg.Message);
2017-01-15 01:08:14 +00:00
if (arg.Exception != null)
_log.Warn(arg.Exception);
return Task.CompletedTask;
}
public async Task RunAndBlockAsync(params string[] args)
{
await RunAsync(args).ConfigureAwait(false);
await Task.Delay(-1).ConfigureAwait(false);
2016-08-13 18:45:08 +00:00
}
2016-08-15 14:57:40 +00:00
2017-06-04 09:40:34 +00:00
private void TerribleElevatedPermissionCheck()
{
try
{
File.WriteAllText("test", "test");
File.Delete("test");
}
catch
{
_log.Error("You must run the application as an ADMINISTRATOR.");
Console.ReadKey();
Environment.Exit(2);
}
}
2016-08-13 18:45:08 +00:00
}
}