2019-07-26 10:05:09 +00:00
|
|
|
using System.Collections.Generic;
|
2019-12-22 11:50:47 +00:00
|
|
|
using System.Diagnostics;
|
2019-07-16 19:59:06 +00:00
|
|
|
using System.Linq;
|
2020-02-01 12:03:02 +00:00
|
|
|
using System.Text.RegularExpressions;
|
2019-04-29 18:21:16 +00:00
|
|
|
using System.Threading.Tasks;
|
2020-02-12 14:16:19 +00:00
|
|
|
|
2019-07-16 19:59:06 +00:00
|
|
|
using App.Metrics;
|
2019-12-22 11:50:47 +00:00
|
|
|
|
2019-07-26 10:05:09 +00:00
|
|
|
using Humanizer;
|
2019-04-29 18:21:16 +00:00
|
|
|
|
2019-12-22 11:50:47 +00:00
|
|
|
using NodaTime;
|
|
|
|
|
|
|
|
using PluralKit.Core;
|
2020-12-24 13:52:44 +00:00
|
|
|
|
|
|
|
using Myriad.Builders;
|
|
|
|
using Myriad.Cache;
|
|
|
|
using Myriad.Extensions;
|
|
|
|
using Myriad.Gateway;
|
|
|
|
using Myriad.Rest;
|
|
|
|
using Myriad.Rest.Types.Requests;
|
|
|
|
using Myriad.Types;
|
|
|
|
|
2020-02-12 14:16:19 +00:00
|
|
|
namespace PluralKit.Bot {
|
2020-02-01 12:03:02 +00:00
|
|
|
public class Misc
|
2019-10-05 05:41:00 +00:00
|
|
|
{
|
2020-08-29 11:46:27 +00:00
|
|
|
private readonly BotConfig _botConfig;
|
|
|
|
private readonly IMetrics _metrics;
|
|
|
|
private readonly CpuStatService _cpu;
|
|
|
|
private readonly ShardInfoService _shards;
|
|
|
|
private readonly EmbedService _embeds;
|
|
|
|
private readonly IDatabase _db;
|
|
|
|
private readonly ModelRepository _repo;
|
2020-12-24 13:52:44 +00:00
|
|
|
private readonly IDiscordCache _cache;
|
|
|
|
private readonly DiscordApiClient _rest;
|
|
|
|
private readonly Cluster _cluster;
|
|
|
|
private readonly Bot _bot;
|
2020-08-29 11:46:27 +00:00
|
|
|
|
2020-12-24 13:52:44 +00:00
|
|
|
public Misc(BotConfig botConfig, IMetrics metrics, CpuStatService cpu, ShardInfoService shards, EmbedService embeds, ModelRepository repo, IDatabase db, IDiscordCache cache, DiscordApiClient rest, Bot bot, Cluster cluster)
|
2019-10-05 05:41:00 +00:00
|
|
|
{
|
|
|
|
_botConfig = botConfig;
|
|
|
|
_metrics = metrics;
|
2019-12-22 11:50:47 +00:00
|
|
|
_cpu = cpu;
|
|
|
|
_shards = shards;
|
2020-02-01 12:03:02 +00:00
|
|
|
_embeds = embeds;
|
2020-08-29 11:46:27 +00:00
|
|
|
_repo = repo;
|
|
|
|
_db = db;
|
2020-12-24 13:52:44 +00:00
|
|
|
_cache = cache;
|
|
|
|
_rest = rest;
|
|
|
|
_bot = bot;
|
|
|
|
_cluster = cluster;
|
2019-10-05 05:41:00 +00:00
|
|
|
}
|
2019-06-15 10:03:07 +00:00
|
|
|
|
2019-10-05 05:41:00 +00:00
|
|
|
public async Task Invite(Context ctx)
|
2019-06-15 10:03:07 +00:00
|
|
|
{
|
2020-12-24 13:52:44 +00:00
|
|
|
var clientId = _botConfig.ClientId ?? _cluster.Application?.Id;
|
|
|
|
|
|
|
|
var permissions =
|
|
|
|
PermissionSet.AddReactions |
|
|
|
|
PermissionSet.AttachFiles |
|
|
|
|
PermissionSet.EmbedLinks |
|
|
|
|
PermissionSet.ManageMessages |
|
|
|
|
PermissionSet.ManageWebhooks |
|
|
|
|
PermissionSet.ReadMessageHistory |
|
|
|
|
PermissionSet.SendMessages;
|
|
|
|
|
|
|
|
var invite = $"https://discord.com/oauth2/authorize?client_id={clientId}&scope=bot%20applications.commands&permissions={(ulong)permissions}";
|
2019-10-05 05:41:00 +00:00
|
|
|
await ctx.Reply($"{Emojis.Success} Use this link to add PluralKit to your server:\n<{invite}>");
|
2019-04-29 18:21:16 +00:00
|
|
|
}
|
2019-10-05 05:41:00 +00:00
|
|
|
|
|
|
|
public async Task Stats(Context ctx)
|
2019-07-16 19:59:06 +00:00
|
|
|
{
|
2020-05-01 15:30:12 +00:00
|
|
|
var timeBefore = SystemClock.Instance.GetCurrentInstant();
|
2019-12-22 11:50:47 +00:00
|
|
|
var msg = await ctx.Reply($"...");
|
2020-05-01 15:30:12 +00:00
|
|
|
var timeAfter = SystemClock.Instance.GetCurrentInstant();
|
|
|
|
var apiLatency = timeAfter - timeBefore;
|
2019-12-22 11:50:47 +00:00
|
|
|
|
2020-05-01 15:30:12 +00:00
|
|
|
var messagesReceived = _metrics.Snapshot.GetForContext("Bot").Meters.FirstOrDefault(m => m.MultidimensionalName == BotMetrics.MessagesReceived.Name)?.Value;
|
|
|
|
var messagesProxied = _metrics.Snapshot.GetForContext("Bot").Meters.FirstOrDefault(m => m.MultidimensionalName == BotMetrics.MessagesProxied.Name)?.Value;
|
|
|
|
var commandsRun = _metrics.Snapshot.GetForContext("Bot").Meters.FirstOrDefault(m => m.MultidimensionalName == BotMetrics.CommandsRun.Name)?.Value;
|
2019-12-22 11:50:47 +00:00
|
|
|
|
2020-05-01 15:30:12 +00:00
|
|
|
var totalSystems = _metrics.Snapshot.GetForContext("Application").Gauges.FirstOrDefault(m => m.MultidimensionalName == CoreMetrics.SystemCount.Name)?.Value ?? 0;
|
|
|
|
var totalMembers = _metrics.Snapshot.GetForContext("Application").Gauges.FirstOrDefault(m => m.MultidimensionalName == CoreMetrics.MemberCount.Name)?.Value ?? 0;
|
2020-09-12 22:10:37 +00:00
|
|
|
var totalGroups = _metrics.Snapshot.GetForContext("Application").Gauges.FirstOrDefault(m => m.MultidimensionalName == CoreMetrics.GroupCount.Name)?.Value ?? 0;
|
2020-05-01 15:30:12 +00:00
|
|
|
var totalSwitches = _metrics.Snapshot.GetForContext("Application").Gauges.FirstOrDefault(m => m.MultidimensionalName == CoreMetrics.SwitchCount.Name)?.Value ?? 0;
|
|
|
|
var totalMessages = _metrics.Snapshot.GetForContext("Application").Gauges.FirstOrDefault(m => m.MultidimensionalName == CoreMetrics.MessageCount.Name)?.Value ?? 0;
|
2019-12-22 11:50:47 +00:00
|
|
|
|
2021-01-31 15:16:52 +00:00
|
|
|
var shardId = ctx.Shard.ShardInfo.ShardId;
|
2021-01-15 10:29:43 +00:00
|
|
|
var shardTotal = ctx.Cluster.Shards.Count;
|
2020-05-01 15:30:12 +00:00
|
|
|
var shardUpTotal = _shards.Shards.Where(x => x.Connected).Count();
|
2021-01-31 15:16:52 +00:00
|
|
|
var shardInfo = _shards.GetShardInfo(ctx.Shard);
|
2019-07-16 19:59:06 +00:00
|
|
|
|
2019-12-22 11:50:47 +00:00
|
|
|
var process = Process.GetCurrentProcess();
|
|
|
|
var memoryUsage = process.WorkingSet64;
|
|
|
|
|
|
|
|
var shardUptime = SystemClock.Instance.GetCurrentInstant() - shardInfo.LastConnectionTime;
|
|
|
|
|
2020-12-24 13:52:44 +00:00
|
|
|
var embed = new EmbedBuilder();
|
|
|
|
if (messagesReceived != null) embed.Field(new("Messages processed",$"{messagesReceived.OneMinuteRate * 60:F1}/m ({messagesReceived.FifteenMinuteRate * 60:F1}/m over 15m)", true));
|
|
|
|
if (messagesProxied != null) embed.Field(new("Messages proxied", $"{messagesProxied.OneMinuteRate * 60:F1}/m ({messagesProxied.FifteenMinuteRate * 60:F1}/m over 15m)", true));
|
|
|
|
if (commandsRun != null) embed.Field(new("Commands executed", $"{commandsRun.OneMinuteRate * 60:F1}/m ({commandsRun.FifteenMinuteRate * 60:F1}/m over 15m)", true));
|
2020-05-01 15:30:12 +00:00
|
|
|
|
|
|
|
embed
|
2020-12-24 13:52:44 +00:00
|
|
|
.Field(new("Current shard", $"Shard #{shardId} (of {shardTotal} total, {shardUpTotal} are up)", true))
|
|
|
|
.Field(new("Shard uptime", $"{shardUptime.FormatDuration()} ({shardInfo.DisconnectionCount} disconnections)", true))
|
|
|
|
.Field(new("CPU usage", $"{_cpu.LastCpuMeasure:P1}", true))
|
|
|
|
.Field(new("Memory usage", $"{memoryUsage / 1024 / 1024} MiB", true))
|
|
|
|
.Field(new("Latency", $"API: {apiLatency.TotalMilliseconds:F0} ms, shard: {shardInfo.ShardLatency.Milliseconds} ms", true))
|
|
|
|
.Field(new("Total numbers", $"{totalSystems:N0} systems, {totalMembers:N0} members, {totalGroups:N0} groups, {totalSwitches:N0} switches, {totalMessages:N0} messages"));
|
2021-01-31 15:16:52 +00:00
|
|
|
await ctx.Rest.EditMessage(msg.ChannelId, msg.Id,
|
2020-12-24 13:52:44 +00:00
|
|
|
new MessageEditRequest {Content = "", Embed = embed.Build()});
|
2019-07-16 19:59:06 +00:00
|
|
|
}
|
2020-04-24 19:50:28 +00:00
|
|
|
|
2019-10-05 05:41:00 +00:00
|
|
|
public async Task PermCheckGuild(Context ctx)
|
2019-07-26 10:05:09 +00:00
|
|
|
{
|
2020-12-24 13:52:44 +00:00
|
|
|
Guild guild;
|
|
|
|
GuildMemberPartial senderGuildUser = null;
|
2019-10-27 20:58:04 +00:00
|
|
|
|
2021-01-31 15:16:52 +00:00
|
|
|
if (ctx.Guild != null && !ctx.HasNext())
|
2019-10-27 20:58:04 +00:00
|
|
|
{
|
2021-01-31 15:16:52 +00:00
|
|
|
guild = ctx.Guild;
|
|
|
|
senderGuildUser = ctx.Member;
|
2019-10-27 20:58:04 +00:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2020-07-25 10:25:45 +00:00
|
|
|
var guildIdStr = ctx.RemainderOrNull() ?? throw new PKSyntaxError("You must pass a server ID or run this command in a server.");
|
2019-10-27 20:58:04 +00:00
|
|
|
if (!ulong.TryParse(guildIdStr, out var guildId))
|
2020-08-25 20:44:52 +00:00
|
|
|
throw new PKSyntaxError($"Could not parse {guildIdStr.AsCode()} as an ID.");
|
2019-10-27 20:58:04 +00:00
|
|
|
|
2021-04-19 20:38:03 +00:00
|
|
|
try {
|
|
|
|
guild = await _rest.GetGuild(guildId);
|
|
|
|
} catch (Myriad.Rest.Exceptions.ForbiddenException) {
|
|
|
|
throw Errors.GuildNotFound(guildId);
|
|
|
|
}
|
|
|
|
|
2020-12-24 13:52:44 +00:00
|
|
|
if (guild != null)
|
2021-01-31 15:16:52 +00:00
|
|
|
senderGuildUser = await _rest.GetGuildMember(guildId, ctx.Author.Id);
|
2020-12-24 13:52:44 +00:00
|
|
|
if (guild == null || senderGuildUser == null)
|
|
|
|
throw Errors.GuildNotFound(guildId);
|
2019-10-27 20:58:04 +00:00
|
|
|
}
|
2020-05-01 13:21:55 +00:00
|
|
|
|
2019-07-26 10:05:09 +00:00
|
|
|
var requiredPermissions = new []
|
|
|
|
{
|
2020-12-24 13:52:44 +00:00
|
|
|
PermissionSet.ViewChannel,
|
|
|
|
PermissionSet.SendMessages,
|
|
|
|
PermissionSet.AddReactions,
|
|
|
|
PermissionSet.AttachFiles,
|
|
|
|
PermissionSet.EmbedLinks,
|
|
|
|
PermissionSet.ManageMessages,
|
|
|
|
PermissionSet.ManageWebhooks
|
2019-07-26 10:05:09 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
// Loop through every channel and group them by sets of permissions missing
|
2020-12-24 13:52:44 +00:00
|
|
|
var permissionsMissing = new Dictionary<ulong, List<Channel>>();
|
2020-04-28 20:06:48 +00:00
|
|
|
var hiddenChannels = 0;
|
2020-12-24 13:52:44 +00:00
|
|
|
foreach (var channel in await _rest.GetGuildChannels(guild.Id))
|
2019-07-26 10:05:09 +00:00
|
|
|
{
|
2020-12-24 13:52:44 +00:00
|
|
|
var botPermissions = _bot.PermissionsIn(channel.Id);
|
2021-01-31 15:16:52 +00:00
|
|
|
var userPermissions = PermissionExtensions.PermissionsFor(guild, channel, ctx.Author.Id, senderGuildUser.Roles);
|
2020-04-28 20:56:43 +00:00
|
|
|
|
2020-12-24 13:52:44 +00:00
|
|
|
if ((userPermissions & PermissionSet.ViewChannel) == 0)
|
2020-04-28 20:06:48 +00:00
|
|
|
{
|
|
|
|
// If the user can't see this channel, don't calculate permissions for it
|
|
|
|
// (to prevent info-leaking, mostly)
|
|
|
|
// Instead, count how many hidden channels and show the user (so they don't get confused)
|
|
|
|
hiddenChannels++;
|
|
|
|
continue;
|
|
|
|
}
|
2019-07-26 10:05:09 +00:00
|
|
|
|
|
|
|
// We use a bitfield so we can set individual permission bits in the loop
|
2020-05-01 13:21:55 +00:00
|
|
|
// TODO: Rewrite with proper bitfield math
|
2019-07-26 10:05:09 +00:00
|
|
|
ulong missingPermissionField = 0;
|
|
|
|
foreach (var requiredPermission in requiredPermissions)
|
2020-05-01 13:21:55 +00:00
|
|
|
if ((botPermissions & requiredPermission) == 0)
|
2019-07-26 10:05:09 +00:00
|
|
|
missingPermissionField |= (ulong) requiredPermission;
|
|
|
|
|
|
|
|
// If we're not missing any permissions, don't bother adding it to the dict
|
|
|
|
// This means we can check if the dict is empty to see if all channels are proxyable
|
|
|
|
if (missingPermissionField != 0)
|
|
|
|
{
|
2020-12-24 13:52:44 +00:00
|
|
|
permissionsMissing.TryAdd(missingPermissionField, new List<Channel>());
|
2019-07-26 10:05:09 +00:00
|
|
|
permissionsMissing[missingPermissionField].Add(channel);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Generate the output embed
|
2020-12-24 13:52:44 +00:00
|
|
|
var eb = new EmbedBuilder()
|
|
|
|
.Title($"Permission check for **{guild.Name}**");
|
2019-07-26 10:05:09 +00:00
|
|
|
|
|
|
|
if (permissionsMissing.Count == 0)
|
|
|
|
{
|
2021-01-15 10:29:43 +00:00
|
|
|
eb.Description($"No errors found, all channels proxyable :)").Color(DiscordUtils.Green);
|
2019-07-26 10:05:09 +00:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
foreach (var (missingPermissionField, channels) in permissionsMissing)
|
|
|
|
{
|
|
|
|
// Each missing permission field can have multiple missing channels
|
|
|
|
// so we extract them all and generate a comma-separated list
|
2021-01-15 10:29:43 +00:00
|
|
|
var missingPermissionNames = ((PermissionSet) missingPermissionField).ToPermissionString();
|
2019-07-26 10:05:09 +00:00
|
|
|
|
|
|
|
var channelsList = string.Join("\n", channels
|
|
|
|
.OrderBy(c => c.Position)
|
|
|
|
.Select(c => $"#{c.Name}"));
|
2020-12-24 13:52:44 +00:00
|
|
|
eb.Field(new($"Missing *{missingPermissionNames}*", channelsList.Truncate(1000)));
|
2021-01-15 10:29:43 +00:00
|
|
|
eb.Color(DiscordUtils.Red);
|
2019-07-26 10:05:09 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-28 20:06:48 +00:00
|
|
|
if (hiddenChannels > 0)
|
2020-12-24 13:52:44 +00:00
|
|
|
eb.Footer(new($"{"channel".ToQuantity(hiddenChannels)} were ignored as you do not have view access to them."));
|
2020-04-28 20:06:48 +00:00
|
|
|
|
2019-07-26 10:05:09 +00:00
|
|
|
// Send! :)
|
2019-10-05 05:41:00 +00:00
|
|
|
await ctx.Reply(embed: eb.Build());
|
2019-07-26 10:05:09 +00:00
|
|
|
}
|
2020-02-01 12:03:02 +00:00
|
|
|
|
|
|
|
public async Task GetMessage(Context ctx)
|
|
|
|
{
|
|
|
|
var word = ctx.PopArgument() ?? throw new PKSyntaxError("You must pass a message ID or link.");
|
|
|
|
|
|
|
|
ulong messageId;
|
|
|
|
if (ulong.TryParse(word, out var id))
|
|
|
|
messageId = id;
|
2021-04-09 09:51:24 +00:00
|
|
|
else if (Regex.Match(word, "https://(?:\\w+.)?discord(?:app)?.com/channels/\\d+/\\d+/(\\d+)") is Match match && match.Success)
|
2020-02-01 12:03:02 +00:00
|
|
|
messageId = ulong.Parse(match.Groups[1].Value);
|
2020-08-25 20:44:52 +00:00
|
|
|
else throw new PKSyntaxError($"Could not parse {word.AsCode()} as a message ID or link.");
|
2020-02-01 12:03:02 +00:00
|
|
|
|
2020-08-29 11:46:27 +00:00
|
|
|
var message = await _db.Execute(c => _repo.GetMessage(c, messageId));
|
2020-02-01 12:03:02 +00:00
|
|
|
if (message == null) throw Errors.MessageNotFound(messageId);
|
|
|
|
|
2021-03-21 09:45:26 +00:00
|
|
|
if (ctx.Match("delete") || ctx.MatchFlag("delete"))
|
|
|
|
{
|
|
|
|
if (message.System.Id != ctx.System.Id)
|
|
|
|
throw new PKError("You can only delete your own messages.");
|
|
|
|
await ctx.Rest.DeleteMessage(message.Message.Channel, message.Message.Mid);
|
|
|
|
await ctx.Rest.DeleteMessage(ctx.Message);
|
|
|
|
return;
|
|
|
|
}
|
2021-04-14 14:50:15 +00:00
|
|
|
if (ctx.Match("author") || ctx.MatchFlag("author"))
|
|
|
|
{
|
|
|
|
var user = await _cache.GetOrFetchUser(_rest, message.Message.Sender);
|
|
|
|
var eb = new EmbedBuilder()
|
|
|
|
.Author(new(user != null ? $"{user.Username}#{user.Discriminator}" : $"Deleted user ${message.Message.Sender}", IconUrl: user != null ? user.AvatarUrl() : null))
|
|
|
|
.Description(message.Message.Sender.ToString());
|
|
|
|
|
|
|
|
await ctx.Reply(user != null ? $"{user.Mention()} ({user.Id})" : $"*(deleted user {message.Message.Sender})*", embed: eb.Build());
|
|
|
|
return;
|
|
|
|
}
|
2021-03-21 09:45:26 +00:00
|
|
|
|
2020-12-25 12:58:45 +00:00
|
|
|
await ctx.Reply(embed: await _embeds.CreateMessageInfoEmbed(message));
|
2020-02-01 12:03:02 +00:00
|
|
|
}
|
2019-04-29 18:21:16 +00:00
|
|
|
}
|
2021-04-09 09:51:24 +00:00
|
|
|
}
|