Reworked Database, using hashtables now (mostly), ability to change game, several small improvents
This commit is contained in:
parent
7308e5257a
commit
29c181ddda
13 changed files with 264 additions and 178 deletions
24
Geekbot.net/Lib/LoggerFactory.cs
Normal file
24
Geekbot.net/Lib/LoggerFactory.cs
Normal 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();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -19,7 +19,7 @@ namespace Geekbot.net.Lib.Media
|
|||
checkEmImageArray = rawCheckEmPics.Split("\n");
|
||||
totalCheckEmImages = checkEmImageArray.Length;
|
||||
this.rnd = rnd;
|
||||
logger.Information($"[Geekbot] [CheckEm] Loaded {totalCheckEmImages} CheckEm Images");
|
||||
logger.Verbose($"[Geekbot] [CheckEm] Loaded {totalCheckEmImages} CheckEm Images");
|
||||
}
|
||||
else
|
||||
{
|
||||
|
|
|
@ -19,7 +19,7 @@ namespace Geekbot.net.Lib.Media
|
|||
fortuneArray = rawFortunes.Split("%");
|
||||
totalFortunes = fortuneArray.Length;
|
||||
this.rnd = rnd;
|
||||
logger.Information($"[Geekbot] [Fortunes] Loaded {totalFortunes} Fortunes");
|
||||
logger.Verbose($"[Geekbot] [Fortunes] Loaded {totalFortunes} Fortunes");
|
||||
}
|
||||
else
|
||||
{
|
||||
|
|
|
@ -19,7 +19,7 @@ namespace Geekbot.net.Lib.Media
|
|||
PandaArray = rawFortunes.Split("\n");
|
||||
totalPandas = PandaArray.Length;
|
||||
this.rnd = rnd;
|
||||
logger.Information($"[Geekbot] [Pandas] Loaded {totalPandas} Panda Images");
|
||||
logger.Verbose($"[Geekbot] [Pandas] Loaded {totalPandas} Panda Images");
|
||||
}
|
||||
else
|
||||
{
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,6 +1,8 @@
|
|||
using System.Threading.Tasks;
|
||||
using Discord;
|
||||
using Discord.Commands;
|
||||
using Discord.WebSocket;
|
||||
using Serilog;
|
||||
using StackExchange.Redis;
|
||||
|
||||
namespace Geekbot.net.Modules
|
||||
|
@ -9,10 +11,14 @@ namespace Geekbot.net.Modules
|
|||
public class AdminCmd : ModuleBase
|
||||
{
|
||||
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.client = client;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
[RequireUserPermission(GuildPermission.Administrator)]
|
||||
|
@ -20,8 +26,7 @@ namespace Geekbot.net.Modules
|
|||
[Summary("Set a Welcome Message (use '$user' to mention the new joined user).")]
|
||||
public async Task SetWelcomeMessage([Remainder] [Summary("message")] string welcomeMessage)
|
||||
{
|
||||
var key = Context.Guild.Id + "-welcomeMsg";
|
||||
redis.StringSet(key, welcomeMessage);
|
||||
redis.HashSet($"{Context.Guild.Id}:Settings", new HashEntry[] { new HashEntry("WelcomeMsg", welcomeMessage) });
|
||||
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" +
|
||||
formatedMessage);
|
||||
|
@ -41,5 +46,22 @@ namespace Geekbot.net.Modules
|
|||
redis.StringSet("youtubeKey", key);
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -2,41 +2,47 @@
|
|||
using System.Threading.Tasks;
|
||||
using Discord;
|
||||
using Discord.Commands;
|
||||
using Geekbot.net.Lib;
|
||||
using StackExchange.Redis;
|
||||
using Serilog;
|
||||
|
||||
namespace Geekbot.net.Modules
|
||||
{
|
||||
public class Counters : ModuleBase
|
||||
{
|
||||
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.logger = logger;
|
||||
this.errorHandler = errorHandler;
|
||||
}
|
||||
|
||||
[Command("good", RunMode = RunMode.Async)]
|
||||
[Summary("Increase Someones Karma")]
|
||||
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)
|
||||
{
|
||||
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(
|
||||
$"Sorry {Context.User.Username}, but you have to wait {GetTimeLeft(lastKarma)} before you can give karma again...");
|
||||
}
|
||||
else
|
||||
{
|
||||
var key = Context.Guild.Id + "-" + user.Id + "-karma";
|
||||
var badJokes = (int) redis.StringGet(key);
|
||||
var newBadJokes = badJokes + 1;
|
||||
redis.StringSet(key, newBadJokes.ToString());
|
||||
var lastKey = Context.Guild.Id + "-" + Context.User.Id + "-karma-timeout";
|
||||
redis.StringSet(lastKey, GetNewLastKarma());
|
||||
var newKarma = redis.HashIncrement($"{Context.Guild.Id}:Karma", user.Id.ToString());
|
||||
redis.HashSet($"{Context.Guild.Id}:KarmaTimeout",
|
||||
new HashEntry[] {new HashEntry(Context.User.Id.ToString(), DateTimeOffset.Now.ToString("u"))});
|
||||
|
||||
var eb = new EmbedBuilder();
|
||||
eb.WithAuthor(new EmbedAuthorBuilder()
|
||||
|
@ -47,33 +53,38 @@ namespace Geekbot.net.Modules
|
|||
eb.Title = "Karma Increased";
|
||||
eb.AddInlineField("By", Context.User.Username);
|
||||
eb.AddInlineField("amount", "+1");
|
||||
eb.AddInlineField("Current Karma", newBadJokes);
|
||||
eb.AddInlineField("Current Karma", newKarma);
|
||||
await ReplyAsync("", false, eb.Build());
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
errorHandler.HandleCommandException(e, Context);
|
||||
}
|
||||
}
|
||||
|
||||
[Command("bad", RunMode = RunMode.Async)]
|
||||
[Summary("Decrease Someones Karma")]
|
||||
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)
|
||||
{
|
||||
await ReplyAsync($"Sorry {Context.User.Username}, but you can't lower your own karma");
|
||||
}
|
||||
else if (lastKarma > GetUnixTimestamp())
|
||||
else if (TimeoutFinished(lastKarma))
|
||||
{
|
||||
await ReplyAsync(
|
||||
$"Sorry {Context.User.Username}, but you have to wait {GetTimeLeft(lastKarma)} before you can take karma again...");
|
||||
}
|
||||
else
|
||||
{
|
||||
var key = Context.Guild.Id + "-" + user.Id + "-karma";
|
||||
var badJokes = (int) redis.StringGet(key);
|
||||
var newBadJokes = badJokes - 1;
|
||||
redis.StringSet(key, newBadJokes.ToString());
|
||||
var lastKey = Context.Guild.Id + "-" + Context.User.Id + "-karma-timeout";
|
||||
redis.StringSet(lastKey, GetNewLastKarma());
|
||||
var newKarma = redis.HashDecrement($"{Context.Guild.Id}:Karma", user.Id.ToString());
|
||||
redis.HashSet($"{Context.Guild.Id}:KarmaTimeout",
|
||||
new HashEntry[] {new HashEntry(Context.User.Id.ToString(), DateTimeOffset.Now.ToString())});
|
||||
|
||||
var eb = new EmbedBuilder();
|
||||
eb.WithAuthor(new EmbedAuthorBuilder()
|
||||
|
@ -84,36 +95,30 @@ namespace Geekbot.net.Modules
|
|||
eb.Title = "Karma Decreased";
|
||||
eb.AddInlineField("By", Context.User.Username);
|
||||
eb.AddInlineField("amount", "-1");
|
||||
eb.AddInlineField("Current Karma", newBadJokes);
|
||||
eb.AddInlineField("Current Karma", newKarma);
|
||||
await ReplyAsync("", false, eb.Build());
|
||||
}
|
||||
}
|
||||
|
||||
private int GetLastKarma()
|
||||
catch (Exception e)
|
||||
{
|
||||
var lastKey = Context.Guild.Id + "-" + Context.User.Id + "-karma-timeout";
|
||||
var redisReturn = redis.StringGet(lastKey);
|
||||
if (!int.TryParse(redisReturn.ToString(), out var i))
|
||||
i = GetUnixTimestamp();
|
||||
return i;
|
||||
errorHandler.HandleCommandException(e, Context);
|
||||
}
|
||||
}
|
||||
|
||||
private int GetNewLastKarma()
|
||||
private DateTimeOffset ConvertToDateTimeOffset(string dateTimeOffsetString)
|
||||
{
|
||||
var timeout = TimeSpan.FromMinutes(3);
|
||||
return (int) DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).Add(timeout).TotalSeconds;
|
||||
if(string.IsNullOrEmpty(dateTimeOffsetString)) return DateTimeOffset.Now.Subtract(new TimeSpan(7, 18, 0, 0));
|
||||
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);
|
||||
dtDateTime = dtDateTime.AddSeconds(time).ToLocalTime();
|
||||
var dt = dtDateTime.Subtract(DateTime.Now);
|
||||
var dt = lastKarma.AddMinutes(3).Subtract(DateTimeOffset.Now);
|
||||
return $"{dt.Minutes} Minutes and {dt.Seconds} Seconds";
|
||||
}
|
||||
}
|
||||
|
|
|
@ -30,7 +30,7 @@ namespace Geekbot.net.Modules
|
|||
var created = Context.Guild.CreatedAt;
|
||||
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);
|
||||
|
||||
eb.AddField("Server Age", $"{created.Day}/{created.Month}/{created.Year} ({age} days)");
|
||||
|
|
|
@ -20,7 +20,7 @@ namespace Geekbot.net.Modules
|
|||
{
|
||||
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;
|
||||
|
||||
|
|
|
@ -29,9 +29,7 @@ namespace Geekbot.net.Modules
|
|||
if (guess == number)
|
||||
{
|
||||
await ReplyAsync($"Congratulations {Context.User.Username}, your guess was correct!");
|
||||
var key = $"{Context.Guild.Id}-{Context.User.Id}-correctRolls";
|
||||
var messages = (int) redis.StringGet(key);
|
||||
redis.StringSet(key, (messages + 1).ToString());
|
||||
redis.HashIncrement($"{Context.Guild.Id}:Rolls", Context.User.Id.ToString());
|
||||
}
|
||||
}
|
||||
else
|
||||
|
|
|
@ -27,15 +27,13 @@ namespace Geekbot.net.Modules
|
|||
dbstring = $"{user1.Id}-{user2.Id}";
|
||||
else
|
||||
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;
|
||||
if (dbval.IsNullOrEmpty)
|
||||
{
|
||||
shippingRate = rnd.Next(1, 100);
|
||||
redis.StringSet(dbstring, shippingRate);
|
||||
redis.HashSet($"{Context.Guild.Id}:Ships", dbstring, shippingRate);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
|
|
@ -1,11 +1,11 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Discord;
|
||||
using Discord.Commands;
|
||||
using Geekbot.net.Lib;
|
||||
using Serilog;
|
||||
using StackExchange.Redis;
|
||||
|
||||
namespace Geekbot.net.Modules
|
||||
|
@ -13,10 +13,14 @@ namespace Geekbot.net.Modules
|
|||
public class UserInfo : ModuleBase
|
||||
{
|
||||
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.errorHandler = errorHandler;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
[Command("stats", RunMode = RunMode.Async)]
|
||||
|
@ -27,12 +31,11 @@ namespace Geekbot.net.Modules
|
|||
|
||||
var age = Math.Floor((DateTime.Now - userInfo.CreatedAt).TotalDays);
|
||||
|
||||
var key = Context.Guild.Id + "-" + userInfo.Id;
|
||||
var messages = (int) redis.StringGet(key + "-messages");
|
||||
var messages = (int) redis.HashGet($"{Context.Guild.Id}:Messages", userInfo.Id.ToString());
|
||||
var level = LevelCalc.GetLevelAtExperience(messages);
|
||||
|
||||
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);
|
||||
|
||||
|
@ -49,11 +52,11 @@ namespace Geekbot.net.Modules
|
|||
.AddInlineField("Messages Sent", messages)
|
||||
.AddInlineField("Server Total", $"{percent}%");
|
||||
|
||||
var karma = redis.StringGet(key + "-karma");
|
||||
var karma = redis.HashGet($"{Context.Guild.Id}:Karma", userInfo.Id.ToString());
|
||||
if (!karma.IsNullOrEmpty)
|
||||
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)
|
||||
eb.AddInlineField("Guessed Rolls", correctRolls);
|
||||
|
||||
|
@ -64,34 +67,43 @@ namespace Geekbot.net.Modules
|
|||
[Summary("get user top 10")]
|
||||
public async Task Rank()
|
||||
{
|
||||
await ReplyAsync("this will take a moment...");
|
||||
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)
|
||||
try
|
||||
{
|
||||
var key = Context.Guild.Id + "-" + user.Id;
|
||||
var messages = (int) redis.StringGet(key + "-messages");
|
||||
if (messages > 0)
|
||||
unsortedDict.Add($"{user.Username}#{user.Discriminator}", messages);
|
||||
}
|
||||
var sortedDict = unsortedDict.OrderByDescending(x => x.Value);
|
||||
var reply = new StringBuilder();
|
||||
reply.AppendLine($"Total Messages on {Context.Guild.Name}: {guildMessages}");
|
||||
var count = 1;
|
||||
foreach (var entry in sortedDict)
|
||||
if (count < 11)
|
||||
var messageList = redis.HashGetAll($"{Context.Guild.Id}:Messages");
|
||||
var sortedList = messageList.OrderByDescending(e => e.Value).ToList().Take(11).ToList();
|
||||
var guildMessages = (int) sortedList.First().Value;
|
||||
sortedList.RemoveAt(0);
|
||||
var highScore = new StringBuilder();
|
||||
highScore.AppendLine($":bar_chart: **Highscore for {Context.Guild.Name}**");
|
||||
var counter = 1;
|
||||
foreach (var user in sortedList)
|
||||
{
|
||||
var percent = Math.Round((double) (100 * entry.Value) / guildMessages, 2);
|
||||
reply.AppendLine($"#{count} - **{entry.Key}** - {percent}% of total - {entry.Value} messages");
|
||||
count++;
|
||||
var guildUser = Context.Guild.GetUserAsync((ulong) user.Name).Result;
|
||||
var percent = Math.Round((double) (100 * (int) user.Value) / guildMessages, 2);
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,4 +1,6 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
@ -26,12 +28,7 @@ namespace Geekbot.net
|
|||
|
||||
private static void Main(string[] args)
|
||||
{
|
||||
var logger = new LoggerConfiguration()
|
||||
.MinimumLevel.Debug()
|
||||
.WriteTo.LiterateConsole()
|
||||
.WriteTo.RollingFile("Logs/geekbot-{Date}.txt", shared: true)
|
||||
.CreateLogger();
|
||||
|
||||
var logger = LoggerFactory.createLogger(args);
|
||||
var logo = new StringBuilder();
|
||||
logo.AppendLine(@" ____ _____ _____ _ ______ ___ _____");
|
||||
logo.AppendLine(@" / ___| ____| ____| |/ / __ ) / _ \\_ _|");
|
||||
|
@ -41,10 +38,10 @@ namespace Geekbot.net
|
|||
logo.AppendLine("=========================================");
|
||||
Console.WriteLine(logo.ToString());
|
||||
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;
|
||||
logger.Information("[Geekbot] Initing Stuff");
|
||||
|
@ -64,16 +61,35 @@ namespace Geekbot.net
|
|||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.Fatal(e, "Redis Connection Failed");
|
||||
logger.Fatal(e, "[Redis] Redis Connection Failed");
|
||||
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");
|
||||
if (token.IsNullOrEmpty)
|
||||
{
|
||||
Console.Write("Your bot Token: ");
|
||||
var newToken = Console.ReadLine();
|
||||
redis.StringSet("discordToken", newToken);
|
||||
redis.StringSet("Game", "Ping Pong");
|
||||
token = newToken;
|
||||
}
|
||||
|
||||
|
@ -92,6 +108,7 @@ namespace Geekbot.net
|
|||
var checkEmImages = new CheckEmImageProvider(RandomClient, logger);
|
||||
var pandaImages = new PandaProvider(RandomClient, logger);
|
||||
var errorHandler = new ErrorHandler(logger);
|
||||
|
||||
services.AddSingleton<IErrorHandler>(errorHandler);
|
||||
services.AddSingleton(redis);
|
||||
services.AddSingleton(RandomClient);
|
||||
|
@ -116,7 +133,7 @@ namespace Geekbot.net
|
|||
var isConneted = await isConnected();
|
||||
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] Registering Stuff");
|
||||
|
@ -126,13 +143,14 @@ namespace Geekbot.net
|
|||
client.UserJoined += HandleUserJoined;
|
||||
await commands.AddModulesAsync(Assembly.GetEntryAssembly());
|
||||
services.AddSingleton(commands);
|
||||
services.AddSingleton<DiscordSocketClient>(client);
|
||||
this.servicesProvider = services.BuildServiceProvider();
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
@ -172,22 +190,20 @@ namespace Geekbot.net
|
|||
var message = messsageParam;
|
||||
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;
|
||||
|
||||
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}");
|
||||
await userRec;
|
||||
await guildRec;
|
||||
}
|
||||
|
||||
private async Task HandleUserJoined(SocketGuildUser user)
|
||||
{
|
||||
if (!user.IsBot)
|
||||
{
|
||||
var message = redis.StringGet(user.Guild.Id + "-welcomeMsg");
|
||||
var message = redis.HashGet($"{user.Guild.Id}:Settings", "WelcomeMsg");
|
||||
if (!message.IsNullOrEmpty)
|
||||
{
|
||||
message = message.ToString().Replace("$user", user.Mention);
|
||||
|
@ -221,5 +237,48 @@ namespace Geekbot.net
|
|||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue