Port !stats, !role, !wiki and !slap, fix messages in rank, add roleselfservicemodel to db

This commit is contained in:
runebaas 2018-05-13 21:06:41 +02:00
parent a1b5bd1955
commit 08015c6102
No known key found for this signature in database
GPG key ID: 2677AF508D0300D6
8 changed files with 141 additions and 74 deletions

View file

@ -5,24 +5,25 @@ using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Discord.Net;
using Geekbot.net.Lib;
using Geekbot.net.Database;
using Geekbot.net.Database.Models;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.Extensions;
using Geekbot.net.Lib.ReactionListener;
using StackExchange.Redis;
namespace Geekbot.net.Commands.Admin
{
[Group("role")]
public class Role : ModuleBase
{
private readonly DatabaseContext _database;
private readonly IErrorHandler _errorHandler;
private readonly IDatabase _redis;
private readonly IReactionListener _reactionListener;
public Role(IErrorHandler errorHandler, IDatabase redis, IReactionListener reactionListener)
public Role(DatabaseContext database, IErrorHandler errorHandler, IReactionListener reactionListener)
{
_database = database;
_errorHandler = errorHandler;
_redis = redis;
_reactionListener = reactionListener;
}
@ -32,8 +33,8 @@ namespace Geekbot.net.Commands.Admin
{
try
{
var roles = _redis.HashGetAll($"{Context.Guild.Id}:RoleWhitelist");
if (roles.Length == 0)
var roles = _database.RoleSelfService.Where(g => g.GuildId.Equals(Context.Guild.Id.AsLong())).ToList();
if (roles.Count == 0)
{
await ReplyAsync("There are no roles configured for this server");
return;
@ -42,7 +43,7 @@ namespace Geekbot.net.Commands.Admin
var sb = new StringBuilder();
sb.AppendLine($"**Self Service Roles on {Context.Guild.Name}**");
sb.AppendLine("To get a role, use `!role name`");
foreach (var role in roles) sb.AppendLine($"- {role.Name}");
foreach (var role in roles) sb.AppendLine($"- {role.WhiteListName}");
await ReplyAsync(sb.ToString());
}
catch (Exception e)
@ -58,18 +59,19 @@ namespace Geekbot.net.Commands.Admin
try
{
var roleName = roleNameRaw.ToLower();
if (_redis.HashExists($"{Context.Guild.Id}:RoleWhitelist", roleName))
var roleFromDb = _database.RoleSelfService.FirstOrDefault(e =>
e.GuildId.Equals(Context.Guild.Id.AsLong()) && e.WhiteListName.Equals(roleName));
if (roleFromDb != null)
{
var guildUser = (IGuildUser) Context.User;
var roleId = ulong.Parse(_redis.HashGet($"{Context.Guild.Id}:RoleWhitelist", roleName));
var role = Context.Guild.Roles.First(r => r.Id == roleId);
var role = Context.Guild.Roles.First(r => r.Id == roleFromDb.RoleId.AsUlong());
if (role == null)
{
await ReplyAsync("That role doesn't seem to exist");
return;
}
if (guildUser.RoleIds.Contains(roleId))
if (guildUser.RoleIds.Contains(role.Id))
{
await guildUser.RemoveRoleAsync(role);
await ReplyAsync($"Removed you from {role.Name}");
@ -113,12 +115,17 @@ namespace Geekbot.net.Commands.Admin
|| role.Permissions.KickMembers)
{
await ReplyAsync(
"Woah, i don't think you want to add that role to self service as it contains some dangerous permissions");
"You cannot add that role to self service because it contains one or more dangerous permissions");
return;
}
_redis.HashSet($"{Context.Guild.Id}:RoleWhitelist",
new[] {new HashEntry(roleName.ToLower(), role.Id.ToString())});
_database.RoleSelfService.Add(new RoleSelfServiceModel
{
GuildId = Context.Guild.Id.AsLong(),
RoleId = role.Id.AsLong(),
WhiteListName = roleName
});
_database.SaveChanges();
await ReplyAsync($"Added {role.Name} to the whitelist");
}
catch (Exception e)
@ -134,16 +141,17 @@ namespace Geekbot.net.Commands.Admin
{
try
{
var success = _redis.HashDelete($"{Context.Guild.Id}:RoleWhitelist", roleName.ToLower());
if (success)
var roleFromDb = _database.RoleSelfService.FirstOrDefault(e =>
e.GuildId.Equals(Context.Guild.Id.AsLong()) && e.WhiteListName.Equals(roleName));
if (roleFromDb != null)
{
_database.RoleSelfService.Remove(roleFromDb);
_database.SaveChanges();
await ReplyAsync($"Removed {roleName} from the whitelist");
return;
}
await ReplyAsync("There is not whitelisted role with that name...");
await ReplyAsync("There is not whitelisted role with that name");
}
catch (Exception e)
{

View file

@ -5,10 +5,10 @@ using System.Text;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Geekbot.net.Lib;
using Geekbot.net.Database;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.Extensions;
using HtmlAgilityPack;
using StackExchange.Redis;
using WikipediaApi;
using WikipediaApi.Page;
@ -18,13 +18,13 @@ namespace Geekbot.net.Commands.Integrations
{
private readonly IErrorHandler _errorHandler;
private readonly IWikipediaClient _wikipediaClient;
private readonly IDatabase _redis;
private readonly DatabaseContext _database;
public Wikipedia(IErrorHandler errorHandler, IWikipediaClient wikipediaClient, IDatabase redis)
public Wikipedia(IErrorHandler errorHandler, IWikipediaClient wikipediaClient, DatabaseContext database)
{
_errorHandler = errorHandler;
_wikipediaClient = wikipediaClient;
_redis = redis;
_database = database;
}
[Command("wiki", RunMode = RunMode.Async)]
@ -33,7 +33,7 @@ namespace Geekbot.net.Commands.Integrations
{
try
{
var wikiLang = _redis.HashGet($"{Context.Guild.Id}:Settings", "WikiLang").ToString();
var wikiLang = _database.GuildSettings.FirstOrDefault(g => g.GuildId.Equals(Context.Guild.Id.AsLong()))?.WikiLang;
if (string.IsNullOrEmpty(wikiLang))
{
wikiLang = "en";

View file

@ -1,21 +1,23 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Geekbot.net.Lib;
using Geekbot.net.Database;
using Geekbot.net.Database.Models;
using Geekbot.net.Lib.ErrorHandling;
using StackExchange.Redis;
using Geekbot.net.Lib.Extensions;
namespace Geekbot.net.Commands.Randomness
{
public class Ship : ModuleBase
{
private readonly IErrorHandler _errorHandler;
private readonly IDatabase _redis;
private readonly DatabaseContext _database;
public Ship(IDatabase redis, IErrorHandler errorHandler)
public Ship(DatabaseContext database, IErrorHandler errorHandler)
{
_redis = redis;
_database = database;
_errorHandler = errorHandler;
}
@ -25,22 +27,29 @@ namespace Geekbot.net.Commands.Randomness
{
try
{
var dbstring = "";
if (user1.Id > user2.Id)
dbstring = $"{user1.Id}-{user2.Id}";
else
dbstring = $"{user2.Id}-{user1.Id}";
var userKeys = user1.Id < user2.Id
? new Tuple<long, long>(user1.Id.AsLong(), user2.Id.AsLong())
: new Tuple<long, long>(user2.Id.AsLong(), user1.Id.AsLong());
var dbval = _redis.HashGet($"{Context.Guild.Id}:Ships", dbstring);
var dbval = _database.Ships.FirstOrDefault(s =>
s.FirstUserId.Equals(userKeys.Item1) &&
s.SecondUserId.Equals(userKeys.Item2));
var shippingRate = 0;
if (dbval.IsNullOrEmpty)
if (dbval == null)
{
shippingRate = new Random().Next(1, 100);
_redis.HashSet($"{Context.Guild.Id}:Ships", dbstring, shippingRate);
_database.Ships.Add(new ShipsModel()
{
FirstUserId = userKeys.Item1,
SecondUserId = userKeys.Item2,
Strength = shippingRate
});
_database.SaveChanges();
}
else
{
shippingRate = int.Parse(dbval.ToString());
shippingRate = dbval.Strength;
}
var reply = ":heartpulse: **Matchmaking** :heartpulse:\r\n";

View file

@ -1,23 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Geekbot.net.Lib;
using Geekbot.net.Database;
using Geekbot.net.Database.Models;
using Geekbot.net.Lib.ErrorHandling;
using StackExchange.Redis;
using Geekbot.net.Lib.Extensions;
namespace Geekbot.net.Commands.Randomness
{
public class Slap : ModuleBase
{
private readonly IErrorHandler _errorHandler;
private readonly IDatabase _redis;
private readonly DatabaseContext _database;
public Slap(IErrorHandler errorHandler, IDatabase redis)
public Slap(IErrorHandler errorHandler, DatabaseContext database)
{
_errorHandler = errorHandler;
_redis = redis;
_database = database;
}
[Command("slap", RunMode = RunMode.Async)]
@ -76,16 +78,53 @@ namespace Geekbot.net.Commands.Randomness
"dictionary",
"powerless banhammer"
};
_redis.HashIncrement($"{Context.Guild.Id}:SlapsRecieved", user.Id.ToString());
_redis.HashIncrement($"{Context.Guild.Id}:SlapsGiven", Context.User.Id.ToString());
await ReplyAsync($"{Context.User.Username} slapped {user.Username} with a {things[new Random().Next(things.Count - 1)]}");
UpdateRecieved(user.Id);
UpdateGiven(Context.User.Id);
_database.SaveChanges();
}
catch (Exception e)
{
_errorHandler.HandleCommandException(e, Context);
}
}
private void UpdateGiven(ulong userId)
{
var user = GetUser(userId);
user.Given++;
_database.Slaps.Update(user);
}
private void UpdateRecieved(ulong userId)
{
var user = GetUser(userId);
user.Recieved++;
_database.Slaps.Update(user);
}
private SlapsModel GetUser(ulong userId)
{
var user = _database.Slaps.FirstOrDefault(e =>
e.GuildId.Equals(Context.Guild.Id.AsLong()) &&
e.UserId.Equals(userId.AsLong())
);
if (user != null) return user;
_database.Slaps.Add(new SlapsModel
{
GuildId = Context.Guild.Id.AsLong(),
UserId = userId.AsLong(),
Recieved = 0,
Given = 0
});
_database.SaveChanges();
return _database.Slaps.FirstOrDefault(e =>
e.GuildId.Equals(Context.Guild.Id.AsLong()) &&
e.UserId.Equals(userId.AsLong()));
}
}
}

View file

@ -6,12 +6,12 @@ using System.Threading.Tasks;
using Discord.Commands;
using Discord.WebSocket;
using Geekbot.net.Database;
using Geekbot.net.Lib;
using Geekbot.net.Lib.Converters;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.Extensions;
using Geekbot.net.Lib.Logger;
using Geekbot.net.Lib.UserRepository;
using StackExchange.Redis;
namespace Geekbot.net.Commands.User.Ranking
{
@ -23,9 +23,10 @@ namespace Geekbot.net.Commands.User.Ranking
private readonly DatabaseContext _database;
private readonly IUserRepository _userRepository;
private readonly DiscordSocketClient _client;
private readonly IDatabase _redis;
public Rank(DatabaseContext database, IErrorHandler errorHandler, IGeekbotLogger logger, IUserRepository userRepository,
IEmojiConverter emojiConverter, DiscordSocketClient client)
IEmojiConverter emojiConverter, DiscordSocketClient client, IDatabase redis)
{
_database = database;
_errorHandler = errorHandler;
@ -33,6 +34,7 @@ namespace Geekbot.net.Commands.User.Ranking
_userRepository = userRepository;
_emojiConverter = emojiConverter;
_client = client;
_redis = redis;
}
[Command("rank", RunMode = RunMode.Async)]
@ -74,8 +76,8 @@ namespace Geekbot.net.Commands.User.Ranking
list = GetRollsList(amount);
break;
default:
list = new Dictionary<ulong, int>();
break;
await ReplyAsync("Valid types are '`messages`' '`karma`', '`rolls`'");
return;
}
if (!list.Any())
@ -142,18 +144,10 @@ namespace Geekbot.net.Commands.User.Ranking
private Dictionary<ulong, int> GetMessageList(int amount)
{
var data = _database.Messages
.Where(k => k.GuildId.Equals(Context.Guild.Id.AsLong()))
.OrderByDescending(o => o.MessageCount)
.Take(amount);
var dict = new Dictionary<ulong, int>();
foreach (var user in data)
{
dict.Add(user.UserId.AsUlong(), user.MessageCount);
}
return dict;
var data = _redis.HashGetAll($"{Context.Guild.Id}:Messages").ToDictionary().Take(amount + 1);
return data.Where(user => !user.Key.Equals(0)).ToDictionary(user => ulong.Parse(user.Key), user => int.Parse(user.Value));
}
private Dictionary<ulong, int> GetKarmaList(int amount)

View file

@ -1,9 +1,11 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Geekbot.net.Lib;
using Geekbot.net.Database;
using Geekbot.net.Lib.ErrorHandling;
using Geekbot.net.Lib.Extensions;
using Geekbot.net.Lib.Levels;
using StackExchange.Redis;
@ -14,10 +16,12 @@ namespace Geekbot.net.Commands.User
private readonly IErrorHandler _errorHandler;
private readonly ILevelCalc _levelCalc;
private readonly IDatabase _redis;
private readonly DatabaseContext _database;
public Stats(IDatabase redis, IErrorHandler errorHandler, ILevelCalc levelCalc)
public Stats(IDatabase redis, DatabaseContext database, IErrorHandler errorHandler, ILevelCalc levelCalc)
{
_redis = redis;
_database = database;
_errorHandler = errorHandler;
_levelCalc = levelCalc;
}
@ -47,20 +51,23 @@ namespace Geekbot.net.Commands.User
.WithName(userInfo.Username));
eb.WithColor(new Color(221, 255, 119));
var karma = _redis.HashGet($"{Context.Guild.Id}:Karma", userInfo.Id.ToString());
var correctRolls = _redis.HashGet($"{Context.Guild.Id}:Rolls", userInfo.Id.ToString());
var karma = _database.Karma.FirstOrDefault(e =>
e.GuildId.Equals(Context.Guild.Id.AsLong()) &&
e.UserId.Equals(userInfo.Id.AsLong()));
var correctRolls = _database.Rolls.FirstOrDefault(e =>
e.GuildId.Equals(Context.Guild.Id.AsLong()) &&
e.UserId.Equals(userInfo.Id.AsLong()));
eb.AddInlineField("Discordian Since",
$"{createdAt.Day}.{createdAt.Month}.{createdAt.Year} ({age} days)")
.AddInlineField("Joined Server",
$"{joinedAt.Day}.{joinedAt.Month}.{joinedAt.Year} ({joinedDayAgo} days)")
.AddInlineField("Karma", karma.ToString() ?? "0")
.AddInlineField("Karma", karma?.Karma ?? 0)
.AddInlineField("Level", level)
.AddInlineField("Messages Sent", messages)
.AddInlineField("Server Total", $"{percent}%");
if (!correctRolls.IsNullOrEmpty)
eb.AddInlineField("Guessed Rolls", correctRolls);
if (correctRolls != null) eb.AddInlineField("Guessed Rolls", correctRolls.Rolls);
await ReplyAsync("", false, eb.Build());
}

View file

@ -15,8 +15,8 @@ namespace Geekbot.net.Database
public DbSet<MessagesModel> Messages { get; set; }
public DbSet<SlapsModel> Slaps { get; set; }
public DbSet<GlobalsModel> Globals { get; set; }
public DbSet<RoleSelfServiceModel> RoleSelfService { get; set; }
// public DbSet<UserSettingsModel> UserSettings { get; set; }
// public DbSet<RoleSelfServiceModel> RoleSelfService { get; set; }
}
}

View file

@ -1,7 +1,17 @@
namespace Geekbot.net.Database.Models
using System.ComponentModel.DataAnnotations;
namespace Geekbot.net.Database.Models
{
public class RoleSelfServiceModel
{
[Key]
public int Id { get; set; }
[Required]
public long GuildId { get; set; }
public long RoleId { get; set; }
public string WhiteListName { get; set; }
}
}