geekbot/Geekbot.net/Program.cs

240 lines
10 KiB
C#
Raw Normal View History

2017-04-26 14:12:42 +02:00
using System;
using System.Linq;
using System.Net;
2017-04-26 14:12:42 +02:00
using System.Reflection;
2017-09-26 13:02:38 +02:00
using System.Text;
2017-04-26 14:12:42 +02:00
using System.Threading.Tasks;
2018-05-02 20:19:11 +02:00
using CommandLine;
2017-04-26 14:12:42 +02:00
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using Geekbot.net.Database;
2017-04-26 14:12:42 +02:00
using Geekbot.net.Lib;
2018-05-04 00:54:01 +02:00
using Geekbot.net.Lib.Audio;
using Geekbot.net.Lib.Clients;
using Geekbot.net.Lib.Converters;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.Levels;
using Geekbot.net.Lib.Localization;
using Geekbot.net.Lib.Logger;
using Geekbot.net.Lib.Media;
using Geekbot.net.Lib.ReactionListener;
using Geekbot.net.Lib.UserRepository;
using Microsoft.EntityFrameworkCore;
2017-09-15 22:56:03 +02:00
using Microsoft.Extensions.DependencyInjection;
using Nancy.Hosting.Self;
2017-04-26 14:12:42 +02:00
using StackExchange.Redis;
using WikipediaApi;
2017-04-26 14:12:42 +02:00
namespace Geekbot.net
{
2017-09-15 22:56:03 +02:00
internal class Program
2017-04-26 14:12:42 +02:00
{
2018-04-30 23:44:19 +02:00
private DiscordSocketClient _client;
private CommandService _commands;
private IDatabase _redis;
private IServiceCollection _services;
private IServiceProvider _servicesProvider;
private RedisValue _token;
private GeekbotLogger _logger;
2018-04-30 23:44:19 +02:00
private IUserRepository _userRepository;
private bool _firstStart;
2018-05-02 20:19:11 +02:00
private RunParameters _runParameters;
2017-04-26 14:12:42 +02:00
2017-09-26 13:02:38 +02:00
private static void Main(string[] args)
2017-04-26 14:12:42 +02:00
{
2018-05-02 20:19:11 +02:00
RunParameters runParameters = null;
Parser.Default.ParseArguments<RunParameters>(args)
.WithParsed(e => runParameters = e)
2018-05-06 02:00:45 +02:00
.WithNotParsed(_ => Environment.Exit(GeekbotExitCode.InvalidArguments.GetHashCode()));
2018-05-02 20:19:11 +02:00
2017-09-26 22:09:57 +02:00
var logo = new StringBuilder();
2017-09-26 13:02:38 +02:00
logo.AppendLine(@" ____ _____ _____ _ ______ ___ _____");
logo.AppendLine(@" / ___| ____| ____| |/ / __ ) / _ \\_ _|");
logo.AppendLine(@"| | _| _| | _| | ' /| _ \| | | || |");
logo.AppendLine(@"| |_| | |___| |___| . \| |_) | |_| || |");
logo.AppendLine(@" \____|_____|_____|_|\_\____/ \___/ |_|");
logo.AppendLine("=========================================");
Console.WriteLine(logo.ToString());
2018-05-01 16:50:48 +02:00
var sumologicActive = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("GEEKBOT_SUMO"));
2018-05-02 20:19:11 +02:00
var logger = new GeekbotLogger(runParameters, sumologicActive);
logger.Information(LogSource.Geekbot, "Starting...");
try
{
2018-05-02 20:19:11 +02:00
new Program().MainAsync(runParameters, logger).GetAwaiter().GetResult();
}
catch (Exception e)
{
logger.Error(LogSource.Geekbot, "RIP", e);
}
2017-04-26 14:12:42 +02:00
}
private async Task MainAsync(RunParameters runParameters, GeekbotLogger logger)
2017-04-26 14:12:42 +02:00
{
2018-04-30 23:44:19 +02:00
_logger = logger;
2018-05-02 20:19:11 +02:00
_runParameters = runParameters;
logger.Information(LogSource.Geekbot, "Initing Stuff");
var discordLogger = new DiscordLogger(logger);
2017-09-26 22:09:57 +02:00
2018-04-30 23:44:19 +02:00
_client = new DiscordSocketClient(new DiscordSocketConfig
2017-09-26 22:09:57 +02:00
{
LogLevel = LogSeverity.Verbose,
2017-11-10 21:37:39 +01:00
MessageCacheSize = 1000
2017-09-26 22:09:57 +02:00
});
_client.Log += discordLogger.Log;
2018-04-30 23:44:19 +02:00
_commands = new CommandService();
2017-04-26 14:12:42 +02:00
try
{
var redisMultiplexer = ConnectionMultiplexer.Connect("127.0.0.1:6379");
2018-04-30 23:44:19 +02:00
_redis = redisMultiplexer.GetDatabase(6);
logger.Information(LogSource.Redis, $"Connected to db {_redis.Database}");
}
catch (Exception e)
{
logger.Error(LogSource.Redis, "Redis Connection Failed", e);
2018-05-06 02:00:45 +02:00
Environment.Exit(GeekbotExitCode.RedisConnectionFailed.GetHashCode());
}
2018-05-06 02:00:45 +02:00
_token = runParameters.Token ?? _redis.StringGet("discordToken");
2018-04-30 23:44:19 +02:00
if (_token.IsNullOrEmpty)
2017-04-26 14:12:42 +02:00
{
Console.Write("Your bot Token: ");
var newToken = Console.ReadLine();
2018-04-30 23:44:19 +02:00
_redis.StringSet("discordToken", newToken);
_redis.StringSet("Game", "Ping Pong");
_token = newToken;
_firstStart = true;
2017-09-26 22:09:57 +02:00
}
2017-04-26 14:12:42 +02:00
DatabaseContext database = null;
try
{
database = new DatabaseContext();
database.Database.EnsureCreated();
}
catch (Exception e)
{
logger.Error(LogSource.Geekbot, "Could not Connect to datbase", e);
Environment.Exit(GeekbotExitCode.DatabaseConnectionFailed.GetHashCode());
}
2018-04-30 23:44:19 +02:00
_services = new ServiceCollection();
2018-04-30 23:44:19 +02:00
_userRepository = new UserRepository(_redis, logger);
var fortunes = new FortunesProvider(logger);
var mediaProvider = new MediaProvider(logger);
2018-04-30 23:44:19 +02:00
var malClient = new MalClient(_redis, logger);
var levelCalc = new LevelCalc();
2017-11-06 23:55:28 +01:00
var emojiConverter = new EmojiConverter();
2018-02-19 21:35:45 +01:00
var mtgManaConverter = new MtgManaConverter();
var wikipediaClient = new WikipediaClient();
2018-05-04 00:54:01 +02:00
var audioUtils = new AudioUtils();
_services.AddSingleton<IDatabase>(_redis);
_services.AddSingleton<IUserRepository>(_userRepository);
_services.AddSingleton<IGeekbotLogger>(logger);
2018-04-30 23:44:19 +02:00
_services.AddSingleton<ILevelCalc>(levelCalc);
_services.AddSingleton<IEmojiConverter>(emojiConverter);
_services.AddSingleton<IFortunesProvider>(fortunes);
_services.AddSingleton<IMediaProvider>(mediaProvider);
_services.AddSingleton<IMalClient>(malClient);
_services.AddSingleton<IMtgManaConverter>(mtgManaConverter);
_services.AddSingleton<IWikipediaClient>(wikipediaClient);
2018-05-04 00:54:01 +02:00
_services.AddSingleton<IAudioUtils>(audioUtils);
_services.AddSingleton<DatabaseContext>(database);
2017-04-26 14:12:42 +02:00
logger.Information(LogSource.Geekbot, "Connecting to Discord");
2017-04-26 14:12:42 +02:00
await Login();
await Task.Delay(-1);
}
2017-09-26 22:09:57 +02:00
private async Task Login()
2017-04-26 14:12:42 +02:00
{
try
{
2018-04-30 23:44:19 +02:00
await _client.LoginAsync(TokenType.Bot, _token);
await _client.StartAsync();
var isConneted = await IsConnected();
2017-04-27 19:50:03 +02:00
if (isConneted)
{
2018-04-30 23:44:19 +02:00
await _client.SetGameAsync(_redis.StringGet("Game"));
_logger.Information(LogSource.Geekbot, $"Now Connected as {_client.CurrentUser.Username} to {_client.Guilds.Count} Servers");
2018-04-30 23:44:19 +02:00
_logger.Information(LogSource.Geekbot, "Registering Stuff");
2018-04-30 23:44:19 +02:00
var translationHandler = new TranslationHandler(_client.Guilds, _redis, _logger);
2018-05-02 20:19:11 +02:00
var errorHandler = new ErrorHandler(_logger, translationHandler, _runParameters.ExposeErrors);
2018-04-30 23:44:19 +02:00
var reactionListener = new ReactionListener(_redis);
await _commands.AddModulesAsync(Assembly.GetEntryAssembly());
_services.AddSingleton(_commands);
_services.AddSingleton<IErrorHandler>(errorHandler);
_services.AddSingleton<ITranslationHandler>(translationHandler);
_services.AddSingleton(_client);
_services.AddSingleton<IReactionListener>(reactionListener);
_servicesProvider = _services.BuildServiceProvider();
2018-04-30 23:44:19 +02:00
var handlers = new Handlers(_client, _logger, _redis, _servicesProvider, _commands, _userRepository, reactionListener);
2018-04-30 23:44:19 +02:00
_client.MessageReceived += handlers.RunCommand;
_client.MessageReceived += handlers.UpdateStats;
_client.MessageDeleted += handlers.MessageDeleted;
_client.UserJoined += handlers.UserJoined;
_client.UserUpdated += handlers.UserUpdated;
_client.UserLeft += handlers.UserLeft;
_client.ReactionAdded += handlers.ReactionAdded;
_client.ReactionRemoved += handlers.ReactionRemoved;
2018-05-02 20:19:11 +02:00
if (_firstStart || _runParameters.Reset)
{
_logger.Information(LogSource.Geekbot, "Finishing setup");
await FinishSetup();
_logger.Information(LogSource.Geekbot, "Setup finished");
}
2018-05-02 20:19:11 +02:00
if (!_runParameters.DisableApi)
{
2018-04-30 23:44:19 +02:00
StartWebApi();
}
_logger.Information(LogSource.Geekbot, "Done and ready for use");
2017-04-27 19:50:03 +02:00
}
2017-04-26 14:12:42 +02:00
}
catch (Exception e)
2017-04-26 14:12:42 +02:00
{
_logger.Error(LogSource.Geekbot, "Could not connect...", e);
2018-05-06 02:00:45 +02:00
Environment.Exit(GeekbotExitCode.CouldNotLogin.GetHashCode());
2017-04-26 14:12:42 +02:00
}
}
2018-04-30 23:44:19 +02:00
private async Task<bool> IsConnected()
2017-04-27 19:50:03 +02:00
{
2018-04-30 23:44:19 +02:00
while (!_client.ConnectionState.Equals(ConnectionState.Connected))
2017-04-27 19:50:03 +02:00
await Task.Delay(25);
return true;
}
2018-04-30 23:44:19 +02:00
private void StartWebApi()
2017-10-12 16:34:10 +02:00
{
_logger.Information(LogSource.Api, "Starting Webserver");
2017-10-12 16:34:10 +02:00
var webApiUrl = new Uri("http://localhost:12995");
new NancyHost(webApiUrl).Start();
_logger.Information(LogSource.Api, $"Webserver now running on {webApiUrl}");
2017-10-12 16:34:10 +02:00
}
private async Task<Task> FinishSetup()
{
2017-11-10 21:36:41 +01:00
try
{
// ToDo: Set bot avatar
var appInfo = await _client.GetApplicationInfoAsync();
2018-04-30 23:44:19 +02:00
_redis.StringSet("botOwner", appInfo.Owner.Id);
2017-11-10 21:36:41 +01:00
}
catch (Exception e)
{
_logger.Warning(LogSource.Geekbot, "Setup Failed, couldn't retrieve discord application data", e);
}
return Task.CompletedTask;
2017-04-26 14:12:42 +02:00
}
}
2017-09-15 22:56:03 +02:00
}