Reworked Database, using hashtables now (mostly), ability to change game, several small improvents

This commit is contained in:
Runebaas 2017-09-27 22:48:09 +02:00
parent 7308e5257a
commit 29c181ddda
No known key found for this signature in database
GPG key ID: 2677AF508D0300D6
13 changed files with 264 additions and 178 deletions

View file

@ -0,0 +1,24 @@
using Serilog;
using System.Linq;
namespace Geekbot.net.Lib
{
public class LoggerFactory
{
public static ILogger createLogger(string[] args)
{
var loggerCreation = new LoggerConfiguration()
.WriteTo.LiterateConsole()
.WriteTo.RollingFile("Logs/geekbot-{Date}.txt", shared: true);
if (args.Length != 0 && args.Contains("--verbose"))
{
loggerCreation.MinimumLevel.Verbose();
}
else
{
loggerCreation.MinimumLevel.Information();
}
return loggerCreation.CreateLogger();
}
}
}

View file

@ -19,7 +19,7 @@ namespace Geekbot.net.Lib.Media
checkEmImageArray = rawCheckEmPics.Split("\n"); checkEmImageArray = rawCheckEmPics.Split("\n");
totalCheckEmImages = checkEmImageArray.Length; totalCheckEmImages = checkEmImageArray.Length;
this.rnd = rnd; this.rnd = rnd;
logger.Information($"[Geekbot] [CheckEm] Loaded {totalCheckEmImages} CheckEm Images"); logger.Verbose($"[Geekbot] [CheckEm] Loaded {totalCheckEmImages} CheckEm Images");
} }
else else
{ {

View file

@ -19,7 +19,7 @@ namespace Geekbot.net.Lib.Media
fortuneArray = rawFortunes.Split("%"); fortuneArray = rawFortunes.Split("%");
totalFortunes = fortuneArray.Length; totalFortunes = fortuneArray.Length;
this.rnd = rnd; this.rnd = rnd;
logger.Information($"[Geekbot] [Fortunes] Loaded {totalFortunes} Fortunes"); logger.Verbose($"[Geekbot] [Fortunes] Loaded {totalFortunes} Fortunes");
} }
else else
{ {

View file

@ -19,7 +19,7 @@ namespace Geekbot.net.Lib.Media
PandaArray = rawFortunes.Split("\n"); PandaArray = rawFortunes.Split("\n");
totalPandas = PandaArray.Length; totalPandas = PandaArray.Length;
this.rnd = rnd; this.rnd = rnd;
logger.Information($"[Geekbot] [Pandas] Loaded {totalPandas} Panda Images"); logger.Verbose($"[Geekbot] [Pandas] Loaded {totalPandas} Panda Images");
} }
else else
{ {

View file

@ -1,32 +0,0 @@
using System.Threading.Tasks;
using Discord.WebSocket;
using StackExchange.Redis;
namespace Geekbot.net.Lib
{
public class StatsRecorder
{
private readonly SocketMessage message;
private readonly IDatabase redis;
public StatsRecorder(SocketMessage message, IDatabase redis)
{
this.message = message;
this.redis = redis;
}
public async Task UpdateUserRecordAsync()
{
var guildId = ((SocketGuildChannel) message.Channel).Guild.Id;
var key = guildId + "-" + message.Author.Id + "-messages";
await redis.StringIncrementAsync(key);
}
public async Task UpdateGuildRecordAsync()
{
var guildId = ((SocketGuildChannel) message.Channel).Guild.Id;
var key = guildId + "-messages";
await redis.StringIncrementAsync(key);
}
}
}

View file

@ -1,6 +1,8 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket;
using Serilog;
using StackExchange.Redis; using StackExchange.Redis;
namespace Geekbot.net.Modules namespace Geekbot.net.Modules
@ -9,10 +11,14 @@ namespace Geekbot.net.Modules
public class AdminCmd : ModuleBase public class AdminCmd : ModuleBase
{ {
private readonly IDatabase redis; private readonly IDatabase redis;
private readonly DiscordSocketClient client;
private readonly ILogger logger;
public AdminCmd(IDatabase redis) public AdminCmd(IDatabase redis, DiscordSocketClient client, ILogger logger)
{ {
this.redis = redis; this.redis = redis;
this.client = client;
this.logger = logger;
} }
[RequireUserPermission(GuildPermission.Administrator)] [RequireUserPermission(GuildPermission.Administrator)]
@ -20,8 +26,7 @@ namespace Geekbot.net.Modules
[Summary("Set a Welcome Message (use '$user' to mention the new joined user).")] [Summary("Set a Welcome Message (use '$user' to mention the new joined user).")]
public async Task SetWelcomeMessage([Remainder] [Summary("message")] string welcomeMessage) public async Task SetWelcomeMessage([Remainder] [Summary("message")] string welcomeMessage)
{ {
var key = Context.Guild.Id + "-welcomeMsg"; redis.HashSet($"{Context.Guild.Id}:Settings", new HashEntry[] { new HashEntry("WelcomeMsg", welcomeMessage) });
redis.StringSet(key, welcomeMessage);
var formatedMessage = welcomeMessage.Replace("$user", Context.User.Mention); var formatedMessage = welcomeMessage.Replace("$user", Context.User.Mention);
await ReplyAsync("Welcome message has been changed\r\nHere is an example of how it would look:\r\n" + await ReplyAsync("Welcome message has been changed\r\nHere is an example of how it would look:\r\n" +
formatedMessage); formatedMessage);
@ -41,5 +46,22 @@ namespace Geekbot.net.Modules
redis.StringSet("youtubeKey", key); redis.StringSet("youtubeKey", key);
await ReplyAsync("Apikey has been set"); await ReplyAsync("Apikey has been set");
} }
[Command("game", RunMode = RunMode.Async)]
[Summary("Set the game that the bot is playing")]
public async Task SetGame([Remainder] [Summary("Game")] string key)
{
var botOwner = redis.StringGet("botOwner");
if (!Context.User.Id.ToString().Equals(botOwner.ToString()))
{
await ReplyAsync($"Sorry, only the botowner can do this ({botOwner}");
return;
}
redis.StringSet("Game", key);
await client.SetGameAsync(key);
logger.Information($"[Geekbot] Changed game to {key}");
await ReplyAsync($"Now Playing {key}");
}
} }
} }

View file

@ -2,41 +2,47 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib;
using StackExchange.Redis; using StackExchange.Redis;
using Serilog;
namespace Geekbot.net.Modules namespace Geekbot.net.Modules
{ {
public class Counters : ModuleBase public class Counters : ModuleBase
{ {
private readonly IDatabase redis; private readonly IDatabase redis;
private readonly ILogger logger;
private readonly IErrorHandler errorHandler;
public Counters(IDatabase redis) public Counters(IDatabase redis, ILogger logger, IErrorHandler errorHandler)
{ {
this.redis = redis; this.redis = redis;
this.logger = logger;
this.errorHandler = errorHandler;
} }
[Command("good", RunMode = RunMode.Async)] [Command("good", RunMode = RunMode.Async)]
[Summary("Increase Someones Karma")] [Summary("Increase Someones Karma")]
public async Task Good([Summary("@someone")] IUser user) public async Task Good([Summary("@someone")] IUser user)
{ {
var lastKarma = GetLastKarma(); try
{
var lastKarmaFromRedis = redis.HashGet($"{Context.Guild.Id}:KarmaTimeout", Context.User.Id.ToString());
var lastKarma = ConvertToDateTimeOffset(lastKarmaFromRedis.ToString());
if (user.Id == Context.User.Id) if (user.Id == Context.User.Id)
{ {
await ReplyAsync($"Sorry {Context.User.Username}, but you can't give yourself karma"); await ReplyAsync($"Sorry {Context.User.Username}, but you can't lower your own karma");
} }
else if (lastKarma > GetUnixTimestamp()) else if (TimeoutFinished(lastKarma))
{ {
await ReplyAsync( await ReplyAsync(
$"Sorry {Context.User.Username}, but you have to wait {GetTimeLeft(lastKarma)} before you can give karma again..."); $"Sorry {Context.User.Username}, but you have to wait {GetTimeLeft(lastKarma)} before you can give karma again...");
} }
else else
{ {
var key = Context.Guild.Id + "-" + user.Id + "-karma"; var newKarma = redis.HashIncrement($"{Context.Guild.Id}:Karma", user.Id.ToString());
var badJokes = (int) redis.StringGet(key); redis.HashSet($"{Context.Guild.Id}:KarmaTimeout",
var newBadJokes = badJokes + 1; new HashEntry[] {new HashEntry(Context.User.Id.ToString(), DateTimeOffset.Now.ToString("u"))});
redis.StringSet(key, newBadJokes.ToString());
var lastKey = Context.Guild.Id + "-" + Context.User.Id + "-karma-timeout";
redis.StringSet(lastKey, GetNewLastKarma());
var eb = new EmbedBuilder(); var eb = new EmbedBuilder();
eb.WithAuthor(new EmbedAuthorBuilder() eb.WithAuthor(new EmbedAuthorBuilder()
@ -47,33 +53,38 @@ namespace Geekbot.net.Modules
eb.Title = "Karma Increased"; eb.Title = "Karma Increased";
eb.AddInlineField("By", Context.User.Username); eb.AddInlineField("By", Context.User.Username);
eb.AddInlineField("amount", "+1"); eb.AddInlineField("amount", "+1");
eb.AddInlineField("Current Karma", newBadJokes); eb.AddInlineField("Current Karma", newKarma);
await ReplyAsync("", false, eb.Build()); await ReplyAsync("", false, eb.Build());
} }
} }
catch (Exception e)
{
errorHandler.HandleCommandException(e, Context);
}
}
[Command("bad", RunMode = RunMode.Async)] [Command("bad", RunMode = RunMode.Async)]
[Summary("Decrease Someones Karma")] [Summary("Decrease Someones Karma")]
public async Task Bad([Summary("@someone")] IUser user) public async Task Bad([Summary("@someone")] IUser user)
{ {
var lastKarma = GetLastKarma(); try
{
var lastKarmaFromRedis = redis.HashGet($"{Context.Guild.Id}:KarmaTimeout", Context.User.Id.ToString());
var lastKarma = ConvertToDateTimeOffset(lastKarmaFromRedis.ToString());
if (user.Id == Context.User.Id) if (user.Id == Context.User.Id)
{ {
await ReplyAsync($"Sorry {Context.User.Username}, but you can't lower your own karma"); await ReplyAsync($"Sorry {Context.User.Username}, but you can't lower your own karma");
} }
else if (lastKarma > GetUnixTimestamp()) else if (TimeoutFinished(lastKarma))
{ {
await ReplyAsync( await ReplyAsync(
$"Sorry {Context.User.Username}, but you have to wait {GetTimeLeft(lastKarma)} before you can take karma again..."); $"Sorry {Context.User.Username}, but you have to wait {GetTimeLeft(lastKarma)} before you can take karma again...");
} }
else else
{ {
var key = Context.Guild.Id + "-" + user.Id + "-karma"; var newKarma = redis.HashDecrement($"{Context.Guild.Id}:Karma", user.Id.ToString());
var badJokes = (int) redis.StringGet(key); redis.HashSet($"{Context.Guild.Id}:KarmaTimeout",
var newBadJokes = badJokes - 1; new HashEntry[] {new HashEntry(Context.User.Id.ToString(), DateTimeOffset.Now.ToString())});
redis.StringSet(key, newBadJokes.ToString());
var lastKey = Context.Guild.Id + "-" + Context.User.Id + "-karma-timeout";
redis.StringSet(lastKey, GetNewLastKarma());
var eb = new EmbedBuilder(); var eb = new EmbedBuilder();
eb.WithAuthor(new EmbedAuthorBuilder() eb.WithAuthor(new EmbedAuthorBuilder()
@ -84,36 +95,30 @@ namespace Geekbot.net.Modules
eb.Title = "Karma Decreased"; eb.Title = "Karma Decreased";
eb.AddInlineField("By", Context.User.Username); eb.AddInlineField("By", Context.User.Username);
eb.AddInlineField("amount", "-1"); eb.AddInlineField("amount", "-1");
eb.AddInlineField("Current Karma", newBadJokes); eb.AddInlineField("Current Karma", newKarma);
await ReplyAsync("", false, eb.Build()); await ReplyAsync("", false, eb.Build());
} }
} }
catch (Exception e)
private int GetLastKarma()
{ {
var lastKey = Context.Guild.Id + "-" + Context.User.Id + "-karma-timeout"; errorHandler.HandleCommandException(e, Context);
var redisReturn = redis.StringGet(lastKey); }
if (!int.TryParse(redisReturn.ToString(), out var i))
i = GetUnixTimestamp();
return i;
} }
private int GetNewLastKarma() private DateTimeOffset ConvertToDateTimeOffset(string dateTimeOffsetString)
{ {
var timeout = TimeSpan.FromMinutes(3); if(string.IsNullOrEmpty(dateTimeOffsetString)) return DateTimeOffset.Now.Subtract(new TimeSpan(7, 18, 0, 0));
return (int) DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).Add(timeout).TotalSeconds; return DateTimeOffset.Parse(dateTimeOffsetString);
} }
private int GetUnixTimestamp() private bool TimeoutFinished(DateTimeOffset lastKarma)
{ {
return (int) DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; return lastKarma.AddMinutes(3) > DateTimeOffset.Now;
} }
private string GetTimeLeft(int time) private string GetTimeLeft(DateTimeOffset lastKarma)
{ {
var dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var dt = lastKarma.AddMinutes(3).Subtract(DateTimeOffset.Now);
dtDateTime = dtDateTime.AddSeconds(time).ToLocalTime();
var dt = dtDateTime.Subtract(DateTime.Now);
return $"{dt.Minutes} Minutes and {dt.Seconds} Seconds"; return $"{dt.Minutes} Minutes and {dt.Seconds} Seconds";
} }
} }

View file

@ -30,7 +30,7 @@ namespace Geekbot.net.Modules
var created = Context.Guild.CreatedAt; var created = Context.Guild.CreatedAt;
var age = Math.Floor((DateTime.Now - created).TotalDays); var age = Math.Floor((DateTime.Now - created).TotalDays);
var messages = redis.StringGet($"{Context.Guild.Id}-messages"); var messages = redis.HashGet($"{Context.Guild.Id}:Messages", 0.ToString());
var level = LevelCalc.GetLevelAtExperience((int) messages); var level = LevelCalc.GetLevelAtExperience((int) messages);
eb.AddField("Server Age", $"{created.Day}/{created.Month}/{created.Year} ({age} days)"); eb.AddField("Server Age", $"{created.Day}/{created.Month}/{created.Year} ({age} days)");

View file

@ -20,7 +20,7 @@ namespace Geekbot.net.Modules
{ {
var eb = new EmbedBuilder(); var eb = new EmbedBuilder();
eb.WithTitle("Geekbot V3.1"); eb.WithTitle("Geekbot V3.2");
var botOwner = Context.Guild.GetUserAsync(ulong.Parse(redis.StringGet("botOwner"))).Result; var botOwner = Context.Guild.GetUserAsync(ulong.Parse(redis.StringGet("botOwner"))).Result;

View file

@ -29,9 +29,7 @@ namespace Geekbot.net.Modules
if (guess == number) if (guess == number)
{ {
await ReplyAsync($"Congratulations {Context.User.Username}, your guess was correct!"); await ReplyAsync($"Congratulations {Context.User.Username}, your guess was correct!");
var key = $"{Context.Guild.Id}-{Context.User.Id}-correctRolls"; redis.HashIncrement($"{Context.Guild.Id}:Rolls", Context.User.Id.ToString());
var messages = (int) redis.StringGet(key);
redis.StringSet(key, (messages + 1).ToString());
} }
} }
else else

View file

@ -27,15 +27,13 @@ namespace Geekbot.net.Modules
dbstring = $"{user1.Id}-{user2.Id}"; dbstring = $"{user1.Id}-{user2.Id}";
else else
dbstring = $"{user2.Id}-{user1.Id}"; dbstring = $"{user2.Id}-{user1.Id}";
dbstring = $"{Context.Guild.Id}-{dbstring}";
Console.WriteLine(dbstring);
var dbval = redis.StringGet(dbstring); var dbval = redis.HashGet($"{Context.Guild.Id}:Ships", dbstring);
var shippingRate = 0; var shippingRate = 0;
if (dbval.IsNullOrEmpty) if (dbval.IsNullOrEmpty)
{ {
shippingRate = rnd.Next(1, 100); shippingRate = rnd.Next(1, 100);
redis.StringSet(dbstring, shippingRate); redis.HashSet($"{Context.Guild.Id}:Ships", dbstring, shippingRate);
} }
else else
{ {

View file

@ -1,11 +1,11 @@
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Serilog;
using StackExchange.Redis; using StackExchange.Redis;
namespace Geekbot.net.Modules namespace Geekbot.net.Modules
@ -13,10 +13,14 @@ namespace Geekbot.net.Modules
public class UserInfo : ModuleBase public class UserInfo : ModuleBase
{ {
private readonly IDatabase redis; private readonly IDatabase redis;
private readonly IErrorHandler errorHandler;
private readonly ILogger logger;
public UserInfo(IDatabase redis) public UserInfo(IDatabase redis, IErrorHandler errorHandler, ILogger logger)
{ {
this.redis = redis; this.redis = redis;
this.errorHandler = errorHandler;
this.logger = logger;
} }
[Command("stats", RunMode = RunMode.Async)] [Command("stats", RunMode = RunMode.Async)]
@ -27,12 +31,11 @@ namespace Geekbot.net.Modules
var age = Math.Floor((DateTime.Now - userInfo.CreatedAt).TotalDays); var age = Math.Floor((DateTime.Now - userInfo.CreatedAt).TotalDays);
var key = Context.Guild.Id + "-" + userInfo.Id; var messages = (int) redis.HashGet($"{Context.Guild.Id}:Messages", userInfo.Id.ToString());
var messages = (int) redis.StringGet(key + "-messages");
var level = LevelCalc.GetLevelAtExperience(messages); var level = LevelCalc.GetLevelAtExperience(messages);
var guildKey = Context.Guild.Id.ToString(); var guildKey = Context.Guild.Id.ToString();
var guildMessages = (int) redis.StringGet(guildKey + "-messages"); var guildMessages = (int) redis.HashGet($"{Context.Guild.Id}:Messages", 0.ToString());
var percent = Math.Round((double) (100 * messages) / guildMessages, 2); var percent = Math.Round((double) (100 * messages) / guildMessages, 2);
@ -49,11 +52,11 @@ namespace Geekbot.net.Modules
.AddInlineField("Messages Sent", messages) .AddInlineField("Messages Sent", messages)
.AddInlineField("Server Total", $"{percent}%"); .AddInlineField("Server Total", $"{percent}%");
var karma = redis.StringGet(key + "-karma"); var karma = redis.HashGet($"{Context.Guild.Id}:Karma", userInfo.Id.ToString());
if (!karma.IsNullOrEmpty) if (!karma.IsNullOrEmpty)
eb.AddInlineField("Karma", karma); eb.AddInlineField("Karma", karma);
var correctRolls = redis.StringGet($"{Context.Guild.Id}-{userInfo.Id}-correctRolls"); var correctRolls = redis.HashGet($"{Context.Guild.Id}:Rolls", userInfo.Id.ToString());
if (!correctRolls.IsNullOrEmpty) if (!correctRolls.IsNullOrEmpty)
eb.AddInlineField("Guessed Rolls", correctRolls); eb.AddInlineField("Guessed Rolls", correctRolls);
@ -64,34 +67,43 @@ namespace Geekbot.net.Modules
[Summary("get user top 10")] [Summary("get user top 10")]
public async Task Rank() public async Task Rank()
{ {
await ReplyAsync("this will take a moment..."); try
var guildKey = Context.Guild.Id.ToString();
var guildMessages = (int) redis.StringGet(guildKey + "-messages");
var allGuildUsers = await Context.Guild.GetUsersAsync();
var unsortedDict = new Dictionary<string, int>();
foreach (var user in allGuildUsers)
{ {
var key = Context.Guild.Id + "-" + user.Id; var messageList = redis.HashGetAll($"{Context.Guild.Id}:Messages");
var messages = (int) redis.StringGet(key + "-messages"); var sortedList = messageList.OrderByDescending(e => e.Value).ToList().Take(11).ToList();
if (messages > 0) var guildMessages = (int) sortedList.First().Value;
unsortedDict.Add($"{user.Username}#{user.Discriminator}", messages); sortedList.RemoveAt(0);
} var highScore = new StringBuilder();
var sortedDict = unsortedDict.OrderByDescending(x => x.Value); highScore.AppendLine($":bar_chart: **Highscore for {Context.Guild.Name}**");
var reply = new StringBuilder(); var counter = 1;
reply.AppendLine($"Total Messages on {Context.Guild.Name}: {guildMessages}"); foreach (var user in sortedList)
var count = 1;
foreach (var entry in sortedDict)
if (count < 11)
{ {
var percent = Math.Round((double) (100 * entry.Value) / guildMessages, 2); var guildUser = Context.Guild.GetUserAsync((ulong) user.Name).Result;
reply.AppendLine($"#{count} - **{entry.Key}** - {percent}% of total - {entry.Value} messages"); var percent = Math.Round((double) (100 * (int) user.Value) / guildMessages, 2);
count++; highScore.AppendLine(
$"{NumerToEmoji(counter)} **{guildUser.Username}#{guildUser.Discriminator}** - {percent}% of total - {user.Value} messages");
counter++;
} }
else await ReplyAsync(highScore.ToString());
}
catch (Exception e)
{ {
break; errorHandler.HandleCommandException(e, Context);
}
}
private string NumerToEmoji(int number)
{
var emojis = new string[] {":one:", ":two:", ":three:", ":four:", ":five:", ":six", ":seven:", ":eight:", ":nine:", ":keycap_ten:"};
try
{
return emojis[number - 1];
}
catch (Exception e)
{
logger.Warning(e, $"Can't provide emoji number {number}");
return ":zero:";
} }
await ReplyAsync(reply.ToString());
} }
} }
} }

View file

@ -1,4 +1,6 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection; using System.Reflection;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -26,12 +28,7 @@ namespace Geekbot.net
private static void Main(string[] args) private static void Main(string[] args)
{ {
var logger = new LoggerConfiguration() var logger = LoggerFactory.createLogger(args);
.MinimumLevel.Debug()
.WriteTo.LiterateConsole()
.WriteTo.RollingFile("Logs/geekbot-{Date}.txt", shared: true)
.CreateLogger();
var logo = new StringBuilder(); var logo = new StringBuilder();
logo.AppendLine(@" ____ _____ _____ _ ______ ___ _____"); logo.AppendLine(@" ____ _____ _____ _ ______ ___ _____");
logo.AppendLine(@" / ___| ____| ____| |/ / __ ) / _ \\_ _|"); logo.AppendLine(@" / ___| ____| ____| |/ / __ ) / _ \\_ _|");
@ -41,10 +38,10 @@ namespace Geekbot.net
logo.AppendLine("========================================="); logo.AppendLine("=========================================");
Console.WriteLine(logo.ToString()); Console.WriteLine(logo.ToString());
logger.Information("[Geekbot] Starting..."); logger.Information("[Geekbot] Starting...");
new Program().MainAsync(logger).GetAwaiter().GetResult(); new Program().MainAsync(args, logger).GetAwaiter().GetResult();
} }
private async Task MainAsync(ILogger logger) private async Task MainAsync(string[] args, ILogger logger)
{ {
this.logger = logger; this.logger = logger;
logger.Information("[Geekbot] Initing Stuff"); logger.Information("[Geekbot] Initing Stuff");
@ -64,16 +61,35 @@ namespace Geekbot.net
} }
catch (Exception e) catch (Exception e)
{ {
logger.Fatal(e, "Redis Connection Failed"); logger.Fatal(e, "[Redis] Redis Connection Failed");
Environment.Exit(102); Environment.Exit(102);
} }
if (args.Length != 0 && args.Contains("--migrate"))
{
Console.WriteLine("\nYou are about to migrate the database, this will overwrite an already migrated database?");
Console.Write("Are you sure [y:N]: ");
var migrateDbConfirm = Console.ReadKey();
Console.WriteLine();
if (migrateDbConfirm.Key == ConsoleKey.Y)
{
logger.Warning("[Geekbot] Starting Migration");
await MigrateDatabaseToHash();
logger.Warning("[Geekbot] Finished Migration");
}
else
{
logger.Information("[Geekbot] Not Migrating db");
}
}
token = redis.StringGet("discordToken"); token = redis.StringGet("discordToken");
if (token.IsNullOrEmpty) if (token.IsNullOrEmpty)
{ {
Console.Write("Your bot Token: "); Console.Write("Your bot Token: ");
var newToken = Console.ReadLine(); var newToken = Console.ReadLine();
redis.StringSet("discordToken", newToken); redis.StringSet("discordToken", newToken);
redis.StringSet("Game", "Ping Pong");
token = newToken; token = newToken;
} }
@ -92,6 +108,7 @@ namespace Geekbot.net
var checkEmImages = new CheckEmImageProvider(RandomClient, logger); var checkEmImages = new CheckEmImageProvider(RandomClient, logger);
var pandaImages = new PandaProvider(RandomClient, logger); var pandaImages = new PandaProvider(RandomClient, logger);
var errorHandler = new ErrorHandler(logger); var errorHandler = new ErrorHandler(logger);
services.AddSingleton<IErrorHandler>(errorHandler); services.AddSingleton<IErrorHandler>(errorHandler);
services.AddSingleton(redis); services.AddSingleton(redis);
services.AddSingleton(RandomClient); services.AddSingleton(RandomClient);
@ -116,7 +133,7 @@ namespace Geekbot.net
var isConneted = await isConnected(); var isConneted = await isConnected();
if (isConneted) if (isConneted)
{ {
await client.SetGameAsync("Ping Pong"); await client.SetGameAsync(redis.StringGet("Game"));
logger.Information($"[Geekbot] Now Connected to {client.Guilds.Count} Servers"); logger.Information($"[Geekbot] Now Connected to {client.Guilds.Count} Servers");
logger.Information("[Geekbot] Registering Stuff"); logger.Information("[Geekbot] Registering Stuff");
@ -126,13 +143,14 @@ namespace Geekbot.net
client.UserJoined += HandleUserJoined; client.UserJoined += HandleUserJoined;
await commands.AddModulesAsync(Assembly.GetEntryAssembly()); await commands.AddModulesAsync(Assembly.GetEntryAssembly());
services.AddSingleton(commands); services.AddSingleton(commands);
services.AddSingleton<DiscordSocketClient>(client);
this.servicesProvider = services.BuildServiceProvider(); this.servicesProvider = services.BuildServiceProvider();
logger.Information("[Geekbot] Done and ready for use\n"); logger.Information("[Geekbot] Done and ready for use\n");
} }
} }
catch (AggregateException) catch (Exception e)
{ {
logger.Information("Could not connect to discord..."); logger.Fatal(e, "Could not connect to discord...");
Environment.Exit(103); Environment.Exit(103);
} }
} }
@ -172,22 +190,20 @@ namespace Geekbot.net
var message = messsageParam; var message = messsageParam;
if (message == null) return; if (message == null) return;
var statsRecorder = new StatsRecorder(message, redis);
var userRec = statsRecorder.UpdateUserRecordAsync();
var guildRec = statsRecorder.UpdateGuildRecordAsync();
if (message.Author.Id == client.CurrentUser.Id) return;
var channel = (SocketGuildChannel) message.Channel; var channel = (SocketGuildChannel) message.Channel;
await redis.HashIncrementAsync($"{channel.Guild.Id}:Messages", message.Author.Id.ToString());
await redis.HashIncrementAsync($"{channel.Guild.Id}:Messages", 0.ToString());
if (message.Author.IsBot) return;
logger.Information($"[Message] {channel.Guild.Name} - {message.Channel} - {message.Author.Username} - {message.Content}"); logger.Information($"[Message] {channel.Guild.Name} - {message.Channel} - {message.Author.Username} - {message.Content}");
await userRec;
await guildRec;
} }
private async Task HandleUserJoined(SocketGuildUser user) private async Task HandleUserJoined(SocketGuildUser user)
{ {
if (!user.IsBot) if (!user.IsBot)
{ {
var message = redis.StringGet(user.Guild.Id + "-welcomeMsg"); var message = redis.HashGet($"{user.Guild.Id}:Settings", "WelcomeMsg");
if (!message.IsNullOrEmpty) if (!message.IsNullOrEmpty)
{ {
message = message.ToString().Replace("$user", user.Mention); message = message.ToString().Replace("$user", user.Mention);
@ -221,5 +237,48 @@ namespace Geekbot.net
} }
return Task.CompletedTask; return Task.CompletedTask;
} }
// temporary db migration script
private Task MigrateDatabaseToHash()
{
foreach (var key in redis.Multiplexer.GetServer("127.0.0.1", 6379).Keys(6))
{
var keyParts = key.ToString().Split("-");
if (keyParts.Length == 2 || keyParts.Length == 3)
{
logger.Verbose($"Migrating key {key}");
var stuff = new List<string>();
stuff.Add("messages");
stuff.Add("karma");
stuff.Add("welcomeMsg");
stuff.Add("correctRolls");
if(stuff.Contains(keyParts[keyParts.Length - 1]))
{
var val = redis.StringGet(key);
ulong.TryParse(keyParts[0], out ulong guildId);
ulong.TryParse(keyParts[1], out ulong userId);
switch (keyParts[keyParts.Length - 1])
{
case "messages":
redis.HashSet($"{guildId}:Messages", new HashEntry[] { new HashEntry(userId.ToString(), val) });
break;
case "karma":
redis.HashSet($"{guildId}:Karma", new HashEntry[] { new HashEntry(userId.ToString(), val) });
break;
case "correctRolls":
redis.HashSet($"{guildId}:Rolls", new HashEntry[] { new HashEntry(userId.ToString(), val) });
break;
case "welcomeMsg":
redis.HashSet($"{guildId}:Settings", new HashEntry[] { new HashEntry("WelcomeMsg", val) });
break;
}
//redis.KeyDelete(key);
}
}
}
return Task.CompletedTask;
}
} }
} }