Created GetUserDataFromString in base class

This commit is contained in:
Noikoio 2018-03-10 10:38:50 -08:00
parent 99fe2967b6
commit 800956e2aa
3 changed files with 61 additions and 49 deletions

View file

@ -59,9 +59,7 @@ namespace Noikoio.RegexBot.Module.ModCommands.Commands
#region Strings
const string FailPrefix = ":x: **Failed to {0} user:** ";
const string Fail403 = "I do not have the required permissions to perform that action.";
const string Fail404 = "The target user is no longer available.";
const string FailDefault = "An unknown error occurred. Notify the bot operator.";
const string Fail404 = "The specified user is no longer in the server.";
const string NotifyDefault = "You have been {0} from $s for the following reason:\n$r";
const string NotifyReasonNone = "No reason specified.";
const string NotifyFailed = "\n(User was unable to receive notification message.)";
@ -98,32 +96,25 @@ namespace Noikoio.RegexBot.Module.ModCommands.Commands
reason = null;
}
// Getting SocketGuildUser target
SocketGuildUser targetobj = null;
// Extract snowflake value from mention (if a mention was given)
Match m = UserMention.Match(targetstr);
if (m.Success) targetstr = m.Groups["snowflake"].Value;
EntityCache.CacheUser qres;
try
// Retrieve target user
var (targetId, targetData) = await GetUserDataFromString(g.Id, targetstr);
if (targetId == 1)
{
qres = (await EntityCache.EntityCache.QueryAsync(g.Id, targetstr)).FirstOrDefault();
}
catch (Npgsql.NpgsqlException ex)
{
await Log("A database error occurred during user lookup: " + ex.Message);
await msg.Channel.SendMessageAsync(FailPrefix + FailDefault);
return;
}
if (qres == null)
if (targetId == 0)
{
await SendUsageMessageAsync(msg.Channel, TargetNotFound);
return;
}
ulong targetuid = qres.UserId;
targetobj = g.GetUser(targetuid);
string targetdisp = targetobj?.ToString() ?? $"ID {targetuid}";
SocketGuildUser targetobj = g.GetUser(targetId);
string targetdisp;
if (targetData != null)
targetdisp = $"{targetData.Username}#{targetData.Discriminator}";
else
targetdisp = $"ID {targetId}";
if (_mode == CommandMode.Kick && targetobj == null)
{
@ -143,7 +134,7 @@ namespace Noikoio.RegexBot.Module.ModCommands.Commands
reasonlog = Uri.EscapeDataString(reasonlog);
#warning Remove EscapeDataString call on next Discord.Net update
#if !DEBUG
if (_mode == CommandMode.Ban) await g.AddBanAsync(targetuid, _purgeDays, reasonlog);
if (_mode == CommandMode.Ban) await g.AddBanAsync(targetId, _purgeDays, reasonlog);
else await targetobj.KickAsync(reason);
#else
#warning "Actual kick/ban action is DISABLED during debug."

View file

@ -19,9 +19,7 @@ namespace Noikoio.RegexBot.Module.ModCommands.Commands
#region Strings
const string FailPrefix = ":x: **Unable to unban:** ";
const string Fail403 = "I do not have the required permissions to perform that action.";
const string Fail404 = "The target user is no longer available.";
const string FailDefault = "An unknown error occurred. Notify the bot operator.";
protected const string Fail404 = "The specified user does not exist or is not in the ban list.";
const string TargetNotFound = ":x: **Unable to determine the target user.**";
const string Success = ":white_check_mark: Unbanned user **{0}**.";
#endregion
@ -29,8 +27,6 @@ namespace Noikoio.RegexBot.Module.ModCommands.Commands
// Usage: (command) (user query)
public override async Task Invoke(SocketGuild g, SocketMessage msg)
{
// TODO oh god there's so much boilerplate copypasted from BanKick make it stop
string[] line = msg.Content.Split(new char[] { ' ' }, 3, StringSplitOptions.RemoveEmptyEntries);
string targetstr;
if (line.Length < 2)
@ -40,39 +36,29 @@ namespace Noikoio.RegexBot.Module.ModCommands.Commands
}
targetstr = line[1];
// Getting SocketGuildUser target
SocketGuildUser targetobj = null;
// Extract snowflake value from mention (if a mention was given)
Match m = UserMention.Match(targetstr);
if (m.Success) targetstr = m.Groups["snowflake"].Value;
EntityCache.CacheUser qres;
try
// Retrieve target user
var (targetId, targetData) = await GetUserDataFromString(g.Id, targetstr);
if (targetId == 1)
{
qres = (await EntityCache.EntityCache.QueryAsync(g.Id, targetstr)).FirstOrDefault();
}
catch (Npgsql.NpgsqlException ex)
{
await Log("A database error occurred during user lookup: " + ex.Message);
await msg.Channel.SendMessageAsync(FailPrefix + FailDefault);
return;
}
if (qres == null)
if (targetId == 0)
{
await SendUsageMessageAsync(msg.Channel, TargetNotFound);
return;
}
ulong targetuid = qres.UserId;
targetobj = g.GetUser(targetuid);
string targetdisp = targetobj?.ToString() ?? $"ID {targetuid}";
string targetdisp;
if (targetData != null)
targetdisp = $"{targetData.Username}#{targetData.Discriminator}";
else
targetdisp = $"ID {targetId}";
// Do the action
try
{
await g.RemoveBanAsync(targetuid);
await g.RemoveBanAsync(targetId);
await msg.Channel.SendMessageAsync(string.Format(Success, targetdisp));
}
catch (Discord.Net.HttpException ex)

View file

@ -6,6 +6,7 @@ using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
@ -95,9 +96,9 @@ namespace Noikoio.RegexBot.Module.ModCommands.Commands
protected static readonly Regex RoleMention = new Regex(@"<@&(?<snowflake>\d+)>", RegexOptions.Compiled);
protected static readonly Regex ChannelMention = new Regex(@"<#(?<snowflake>\d+)>", RegexOptions.Compiled);
protected static readonly Regex EmojiMatch = new Regex(@"<:(?<name>[A-Za-z0-9_]{2,}):(?<ID>\d+)>", RegexOptions.Compiled);
#endregion
protected const string Fail403 = "I do not have the required permissions to perform that action.";
protected const string FailDefault = "An unknown error occurred. Notify the bot operator.";
#region Usage message
protected string DefaultUsageMsg { get; set; }
/// <summary>
/// Sends out the default usage message (<see cref="DefaultUsageMsg"/>) within an embed.
@ -117,6 +118,40 @@ namespace Noikoio.RegexBot.Module.ModCommands.Commands
};
await target.SendMessageAsync(message ?? "", embed: usageEmbed);
}
/// <summary>
/// Helper method for turning input into user data. Only returns the first cache result.
/// </summary>
/// <returns>
/// First value: 0 for no data, 1 for no data + exception.
/// May return a partial result: a valid ulong value but no CacheUser.
/// </returns>
protected async Task<(ulong, EntityCache.CacheUser)> GetUserDataFromString(ulong guild, string input)
{
ulong uid = 0;
EntityCache.CacheUser cdata = null;
Match m = UserMention.Match(input);
if (m.Success)
{
input = m.Groups["snowflake"].Value;
uid = ulong.Parse(input);
}
try
{
cdata = (await EntityCache.EntityCache.QueryAsync(guild, input))
.FirstOrDefault();
if (cdata != null) uid = cdata.UserId;
}
catch (Npgsql.NpgsqlException ex)
{
await Log("A databasae error occurred during user lookup: " + ex.Message);
if (uid == 0) uid = 1;
}
return (uid, cdata);
}
#endregion
}
}