Do the Big Rename

This commit is contained in:
Ske 2021-01-31 16:16:52 +01:00
parent 80c572f594
commit ef614d07c3
18 changed files with 119 additions and 119 deletions

View File

@ -21,12 +21,12 @@ namespace PluralKit.Bot
{ {
private readonly ILifetimeScope _provider; private readonly ILifetimeScope _provider;
private readonly DiscordApiClient _newRest; private readonly DiscordApiClient _rest;
private readonly Cluster _cluster; private readonly Cluster _cluster;
private readonly Shard _shardNew; private readonly Shard _shard;
private readonly Guild? _guild; private readonly Guild? _guild;
private readonly Channel _channel; private readonly Channel _channel;
private readonly MessageCreateEvent _messageNew; private readonly MessageCreateEvent _message;
private readonly Parameters _parameters; private readonly Parameters _parameters;
private readonly MessageContext _messageContext; private readonly MessageContext _messageContext;
private readonly PermissionSet _botPermissions; private readonly PermissionSet _botPermissions;
@ -44,8 +44,8 @@ namespace PluralKit.Bot
public Context(ILifetimeScope provider, Shard shard, Guild? guild, Channel channel, MessageCreateEvent message, int commandParseOffset, public Context(ILifetimeScope provider, Shard shard, Guild? guild, Channel channel, MessageCreateEvent message, int commandParseOffset,
PKSystem senderSystem, MessageContext messageContext, PermissionSet botPermissions) PKSystem senderSystem, MessageContext messageContext, PermissionSet botPermissions)
{ {
_messageNew = message; _message = message;
_shardNew = shard; _shard = shard;
_guild = guild; _guild = guild;
_channel = channel; _channel = channel;
_senderSystem = senderSystem; _senderSystem = senderSystem;
@ -57,7 +57,7 @@ namespace PluralKit.Bot
_provider = provider; _provider = provider;
_commandMessageService = provider.Resolve<CommandMessageService>(); _commandMessageService = provider.Resolve<CommandMessageService>();
_parameters = new Parameters(message.Content?.Substring(commandParseOffset)); _parameters = new Parameters(message.Content?.Substring(commandParseOffset));
_newRest = provider.Resolve<DiscordApiClient>(); _rest = provider.Resolve<DiscordApiClient>();
_cluster = provider.Resolve<Cluster>(); _cluster = provider.Resolve<Cluster>();
_botPermissions = botPermissions; _botPermissions = botPermissions;
@ -66,20 +66,20 @@ namespace PluralKit.Bot
public IDiscordCache Cache => _cache; public IDiscordCache Cache => _cache;
public Channel ChannelNew => _channel; public Channel Channel => _channel;
public User AuthorNew => _messageNew.Author; public User Author => _message.Author;
public GuildMemberPartial MemberNew => _messageNew.Member; public GuildMemberPartial Member => _message.Member;
public Message MessageNew => _messageNew; public Message Message => _message;
public Guild GuildNew => _guild; public Guild Guild => _guild;
public Shard ShardNew => _shardNew; public Shard Shard => _shard;
public Cluster Cluster => _cluster; public Cluster Cluster => _cluster;
public MessageContext MessageContext => _messageContext; public MessageContext MessageContext => _messageContext;
public PermissionSet BotPermissions => _botPermissions; public PermissionSet BotPermissions => _botPermissions;
public PermissionSet UserPermissions => _userPermissions; public PermissionSet UserPermissions => _userPermissions;
public DiscordApiClient RestNew => _newRest; public DiscordApiClient Rest => _rest;
public PKSystem System => _senderSystem; public PKSystem System => _senderSystem;
@ -97,7 +97,7 @@ namespace PluralKit.Bot
if (embed != null && !BotPermissions.HasFlag(PermissionSet.EmbedLinks)) if (embed != null && !BotPermissions.HasFlag(PermissionSet.EmbedLinks))
throw new PKError("PluralKit does not have permission to send embeds in this channel. Please ensure I have the **Embed Links** permission enabled."); throw new PKError("PluralKit does not have permission to send embeds in this channel. Please ensure I have the **Embed Links** permission enabled.");
var msg = await _newRest.CreateMessage(_channel.Id, new MessageRequest var msg = await _rest.CreateMessage(_channel.Id, new MessageRequest
{ {
Content = text, Content = text,
Embed = embed, Embed = embed,
@ -109,7 +109,7 @@ namespace PluralKit.Bot
{ {
// Sensitive information that might want to be deleted by :x: reaction is typically in an embed format (member cards, for example) // Sensitive information that might want to be deleted by :x: reaction is typically in an embed format (member cards, for example)
// This may need to be changed at some point but works well enough for now // This may need to be changed at some point but works well enough for now
await _commandMessageService.RegisterMessage(msg.Id, AuthorNew.Id); await _commandMessageService.RegisterMessage(msg.Id, Author.Id);
} }
return msg; return msg;

View File

@ -8,7 +8,7 @@ namespace PluralKit.Bot
{ {
public static Context CheckGuildContext(this Context ctx) public static Context CheckGuildContext(this Context ctx)
{ {
if (ctx.ChannelNew.GuildId != null) return ctx; if (ctx.Channel.GuildId != null) return ctx;
throw new PKError("This command can not be run in a DM."); throw new PKError("This command can not be run in a DM.");
} }

View File

@ -14,7 +14,7 @@ namespace PluralKit.Bot
{ {
var text = ctx.PeekArgument(); var text = ctx.PeekArgument();
if (text.TryParseMention(out var id)) if (text.TryParseMention(out var id))
return await ctx.Cache.GetOrFetchUser(ctx.RestNew, id); return await ctx.Cache.GetOrFetchUser(ctx.Rest, id);
return null; return null;
} }

View File

@ -89,7 +89,7 @@ namespace PluralKit.Bot
{ {
var commandList = "**pk;autoproxy latch** - Autoproxies as last-proxied member\n**pk;autoproxy front** - Autoproxies as current (first) fronter\n**pk;autoproxy <member>** - Autoproxies as a specific member"; var commandList = "**pk;autoproxy latch** - Autoproxies as last-proxied member\n**pk;autoproxy front** - Autoproxies as current (first) fronter\n**pk;autoproxy <member>** - Autoproxies as a specific member";
var eb = new EmbedBuilder() var eb = new EmbedBuilder()
.Title($"Current autoproxy status (for {ctx.GuildNew.Name.EscapeMarkdown()})"); .Title($"Current autoproxy status (for {ctx.Guild.Name.EscapeMarkdown()})");
var fronters = ctx.MessageContext.LastSwitchMembers; var fronters = ctx.MessageContext.LastSwitchMembers;
var relevantMember = ctx.MessageContext.AutoproxyMode switch var relevantMember = ctx.MessageContext.AutoproxyMode switch
@ -129,7 +129,7 @@ namespace PluralKit.Bot
} }
if (!ctx.MessageContext.AllowAutoproxy) if (!ctx.MessageContext.AllowAutoproxy)
eb.Field(new("\u200b", $"{Emojis.Note} Autoproxy is currently **disabled** for your account (<@{ctx.AuthorNew.Id}>). To enable it, use `pk;autoproxy account enable`.")); eb.Field(new("\u200b", $"{Emojis.Note} Autoproxy is currently **disabled** for your account (<@{ctx.Author.Id}>). To enable it, use `pk;autoproxy account enable`."));
return eb.Build(); return eb.Build();
} }
@ -191,7 +191,7 @@ namespace PluralKit.Bot
else else
{ {
var statusString = ctx.MessageContext.AllowAutoproxy ? "enabled" : "disabled"; var statusString = ctx.MessageContext.AllowAutoproxy ? "enabled" : "disabled";
await ctx.Reply($"Autoproxy is currently **{statusString}** for account <@{ctx.AuthorNew.Id}>."); await ctx.Reply($"Autoproxy is currently **{statusString}** for account <@{ctx.Author.Id}>.");
} }
} }
@ -200,18 +200,18 @@ namespace PluralKit.Bot
var statusString = allow ? "enabled" : "disabled"; var statusString = allow ? "enabled" : "disabled";
if (ctx.MessageContext.AllowAutoproxy == allow) if (ctx.MessageContext.AllowAutoproxy == allow)
{ {
await ctx.Reply($"{Emojis.Note} Autoproxy is already {statusString} for account <@{ctx.AuthorNew.Id}>."); await ctx.Reply($"{Emojis.Note} Autoproxy is already {statusString} for account <@{ctx.Author.Id}>.");
return; return;
} }
var patch = new AccountPatch { AllowAutoproxy = allow }; var patch = new AccountPatch { AllowAutoproxy = allow };
await _db.Execute(conn => _repo.UpdateAccount(conn, ctx.AuthorNew.Id, patch)); await _db.Execute(conn => _repo.UpdateAccount(conn, ctx.Author.Id, patch));
await ctx.Reply($"{Emojis.Success} Autoproxy {statusString} for account <@{ctx.AuthorNew.Id}>."); await ctx.Reply($"{Emojis.Success} Autoproxy {statusString} for account <@{ctx.Author.Id}>.");
} }
private Task UpdateAutoproxy(Context ctx, AutoproxyMode autoproxyMode, MemberId? autoproxyMember) private Task UpdateAutoproxy(Context ctx, AutoproxyMode autoproxyMode, MemberId? autoproxyMember)
{ {
var patch = new SystemGuildPatch {AutoproxyMode = autoproxyMode, AutoproxyMember = autoproxyMember}; var patch = new SystemGuildPatch {AutoproxyMode = autoproxyMode, AutoproxyMember = autoproxyMember};
return _db.Execute(conn => _repo.UpsertSystemGuild(conn, ctx.System.Id, ctx.GuildNew.Id, patch)); return _db.Execute(conn => _repo.UpsertSystemGuild(conn, ctx.System.Id, ctx.Guild.Id, patch));
} }
} }
} }

View File

@ -45,7 +45,7 @@ namespace PluralKit.Bot
} }
// If we have an attachment, use that // If we have an attachment, use that
if (ctx.MessageNew.Attachments.FirstOrDefault() is {} attachment) if (ctx.Message.Attachments.FirstOrDefault() is {} attachment)
{ {
var url = TryRewriteCdnUrl(attachment.ProxyUrl); var url = TryRewriteCdnUrl(attachment.ProxyUrl);
return new ParsedImage {Url = url, Source = AvatarSource.Attachment}; return new ParsedImage {Url = url, Source = AvatarSource.Attachment};

View File

@ -524,7 +524,7 @@ namespace PluralKit.Bot
{ {
// Try to resolve the user ID to find the associated account, // Try to resolve the user ID to find the associated account,
// so we can print their username. // so we can print their username.
var user = await ctx.RestNew.GetUser(id); var user = await ctx.Rest.GetUser(id);
if (user != null) if (user != null)
return $"Account **{user.Username}#{user.Discriminator}** does not have a system registered."; return $"Account **{user.Username}#{user.Discriminator}** does not have a system registered.";
else else

View File

@ -34,7 +34,7 @@ namespace PluralKit.Bot
public async Task Import(Context ctx) public async Task Import(Context ctx)
{ {
var url = ctx.RemainderOrNull() ?? ctx.MessageNew.Attachments.FirstOrDefault()?.Url; var url = ctx.RemainderOrNull() ?? ctx.Message.Attachments.FirstOrDefault()?.Url;
if (url == null) throw Errors.NoImportFilePassed; if (url == null) throw Errors.NoImportFilePassed;
await ctx.BusyIndicator(async () => await ctx.BusyIndicator(async () =>
@ -69,7 +69,7 @@ namespace PluralKit.Bot
if (!data.Valid) if (!data.Valid)
throw Errors.InvalidImportFile; throw Errors.InvalidImportFile;
if (data.LinkedAccounts != null && !data.LinkedAccounts.Contains(ctx.AuthorNew.Id)) if (data.LinkedAccounts != null && !data.LinkedAccounts.Contains(ctx.Author.Id))
{ {
var msg = $"{Emojis.Warn} You seem to importing a system profile belonging to another account. Are you sure you want to proceed?"; var msg = $"{Emojis.Warn} You seem to importing a system profile belonging to another account. Are you sure you want to proceed?";
if (!await ctx.PromptYesNo(msg)) throw Errors.ImportCancelled; if (!await ctx.PromptYesNo(msg)) throw Errors.ImportCancelled;
@ -77,7 +77,7 @@ namespace PluralKit.Bot
// If passed system is null, it'll create a new one // If passed system is null, it'll create a new one
// (and that's okay!) // (and that's okay!)
var result = await _dataFiles.ImportSystem(data, ctx.System, ctx.AuthorNew.Id); var result = await _dataFiles.ImportSystem(data, ctx.System, ctx.Author.Id);
if (!result.Success) if (!result.Success)
await ctx.Reply($"{Emojis.Error} The provided system profile could not be imported. {result.Message}"); await ctx.Reply($"{Emojis.Error} The provided system profile could not be imported. {result.Message}");
else if (ctx.System == null) else if (ctx.System == null)
@ -143,15 +143,15 @@ namespace PluralKit.Bot
try try
{ {
var dm = await ctx.RestNew.CreateDm(ctx.AuthorNew.Id); var dm = await ctx.Rest.CreateDm(ctx.Author.Id);
var msg = await ctx.RestNew.CreateMessage(dm.Id, var msg = await ctx.Rest.CreateMessage(dm.Id,
new MessageRequest {Content = $"{Emojis.Success} Here you go!"}, new MessageRequest {Content = $"{Emojis.Success} Here you go!"},
new[] {new MultipartFile("system.json", stream)}); new[] {new MultipartFile("system.json", stream)});
await ctx.RestNew.CreateMessage(dm.Id, new MessageRequest { Content = $"<{msg.Attachments[0].Url}>" }); await ctx.Rest.CreateMessage(dm.Id, new MessageRequest { Content = $"<{msg.Attachments[0].Url}>" });
// If the original message wasn't posted in DMs, send a public reminder // If the original message wasn't posted in DMs, send a public reminder
if (ctx.ChannelNew.Type != Channel.ChannelType.Dm) if (ctx.Channel.Type != Channel.ChannelType.Dm)
await ctx.Reply($"{Emojis.Success} Check your DMs!"); await ctx.Reply($"{Emojis.Success} Check your DMs!");
} }
catch (UnauthorizedException) catch (UnauthorizedException)

View File

@ -71,7 +71,7 @@ namespace PluralKit.Bot
public async Task ViewMember(Context ctx, PKMember target) public async Task ViewMember(Context ctx, PKMember target)
{ {
var system = await _db.Execute(c => _repo.GetSystem(c, target.System)); var system = await _db.Execute(c => _repo.GetSystem(c, target.System));
await ctx.Reply(embed: await _embeds.CreateMemberEmbed(system, target, ctx.GuildNew, ctx.LookupContextFor(system))); await ctx.Reply(embed: await _embeds.CreateMemberEmbed(system, target, ctx.Guild, ctx.LookupContextFor(system)));
} }
public async Task Soulscream(Context ctx, PKMember target) public async Task Soulscream(Context ctx, PKMember target)

View File

@ -25,7 +25,7 @@ namespace PluralKit.Bot
if (location == AvatarLocation.Server) if (location == AvatarLocation.Server)
{ {
if (target.AvatarUrl != null) if (target.AvatarUrl != null)
await ctx.Reply($"{Emojis.Success} Member server avatar cleared. This member will now use the global avatar in this server (**{ctx.GuildNew.Name}**)."); await ctx.Reply($"{Emojis.Success} Member server avatar cleared. This member will now use the global avatar in this server (**{ctx.Guild.Name}**).");
else else
await ctx.Reply($"{Emojis.Success} Member server avatar cleared. This member now has no avatar."); await ctx.Reply($"{Emojis.Success} Member server avatar cleared. This member now has no avatar.");
} }
@ -55,7 +55,7 @@ namespace PluralKit.Bot
throw new PKError($"This member does not have a server avatar set. Type `pk;member {target.Reference()} avatar` to see their global avatar."); throw new PKError($"This member does not have a server avatar set. Type `pk;member {target.Reference()} avatar` to see their global avatar.");
} }
var field = location == AvatarLocation.Server ? $"server avatar (for {ctx.GuildNew.Name})" : "avatar"; var field = location == AvatarLocation.Server ? $"server avatar (for {ctx.Guild.Name})" : "avatar";
var cmd = location == AvatarLocation.Server ? "serveravatar" : "avatar"; var cmd = location == AvatarLocation.Server ? "serveravatar" : "avatar";
var eb = new EmbedBuilder() var eb = new EmbedBuilder()
@ -69,14 +69,14 @@ namespace PluralKit.Bot
public async Task ServerAvatar(Context ctx, PKMember target) public async Task ServerAvatar(Context ctx, PKMember target)
{ {
ctx.CheckGuildContext(); ctx.CheckGuildContext();
var guildData = await _db.Execute(c => _repo.GetMemberGuild(c, ctx.GuildNew.Id, target.Id)); var guildData = await _db.Execute(c => _repo.GetMemberGuild(c, ctx.Guild.Id, target.Id));
await AvatarCommandTree(AvatarLocation.Server, ctx, target, guildData); await AvatarCommandTree(AvatarLocation.Server, ctx, target, guildData);
} }
public async Task Avatar(Context ctx, PKMember target) public async Task Avatar(Context ctx, PKMember target)
{ {
var guildData = ctx.GuildNew != null ? var guildData = ctx.Guild != null ?
await _db.Execute(c => _repo.GetMemberGuild(c, ctx.GuildNew.Id, target.Id)) await _db.Execute(c => _repo.GetMemberGuild(c, ctx.Guild.Id, target.Id))
: null; : null;
await AvatarCommandTree(AvatarLocation.Member, ctx, target, guildData); await AvatarCommandTree(AvatarLocation.Member, ctx, target, guildData);
@ -119,8 +119,8 @@ namespace PluralKit.Bot
var serverFrag = location switch var serverFrag = location switch
{ {
AvatarLocation.Server => $" This avatar will now be used when proxying in this server (**{ctx.GuildNew.Name}**).", AvatarLocation.Server => $" This avatar will now be used when proxying in this server (**{ctx.Guild.Name}**).",
AvatarLocation.Member when targetGuildData?.AvatarUrl != null => $"\n{Emojis.Note} Note that this member *also* has a server-specific avatar set in this server (**{ctx.GuildNew.Name}**), and thus changing the global avatar will have no effect here.", AvatarLocation.Member when targetGuildData?.AvatarUrl != null => $"\n{Emojis.Note} Note that this member *also* has a server-specific avatar set in this server (**{ctx.Guild.Name}**), and thus changing the global avatar will have no effect here.",
_ => "" _ => ""
}; };
@ -145,7 +145,7 @@ namespace PluralKit.Bot
{ {
case AvatarLocation.Server: case AvatarLocation.Server:
var serverPatch = new MemberGuildPatch { AvatarUrl = url }; var serverPatch = new MemberGuildPatch { AvatarUrl = url };
return _db.Execute(c => _repo.UpsertMemberGuild(c, target.Id, ctx.GuildNew.Id, serverPatch)); return _db.Execute(c => _repo.UpsertMemberGuild(c, target.Id, ctx.Guild.Id, serverPatch));
case AvatarLocation.Member: case AvatarLocation.Member:
var memberPatch = new MemberPatch { AvatarUrl = url }; var memberPatch = new MemberPatch { AvatarUrl = url };
return _db.Execute(c => _repo.UpdateMember(c, target.Id, memberPatch)); return _db.Execute(c => _repo.UpdateMember(c, target.Id, memberPatch));

View File

@ -46,11 +46,11 @@ namespace PluralKit.Bot
if (newName.Contains(" ")) await ctx.Reply($"{Emojis.Note} Note that this member's name now contains spaces. You will need to surround it with \"double quotes\" when using commands referring to it."); if (newName.Contains(" ")) await ctx.Reply($"{Emojis.Note} Note that this member's name now contains spaces. You will need to surround it with \"double quotes\" when using commands referring to it.");
if (target.DisplayName != null) await ctx.Reply($"{Emojis.Note} Note that this member has a display name set ({target.DisplayName}), and will be proxied using that name instead."); if (target.DisplayName != null) await ctx.Reply($"{Emojis.Note} Note that this member has a display name set ({target.DisplayName}), and will be proxied using that name instead.");
if (ctx.GuildNew != null) if (ctx.Guild != null)
{ {
var memberGuildConfig = await _db.Execute(c => _repo.GetMemberGuild(c, ctx.GuildNew.Id, target.Id)); var memberGuildConfig = await _db.Execute(c => _repo.GetMemberGuild(c, ctx.Guild.Id, target.Id));
if (memberGuildConfig.DisplayName != null) if (memberGuildConfig.DisplayName != null)
await ctx.Reply($"{Emojis.Note} Note that this member has a server name set ({memberGuildConfig.DisplayName}) in this server ({ctx.GuildNew.Name}), and will be proxied using that name here."); await ctx.Reply($"{Emojis.Note} Note that this member has a server name set ({memberGuildConfig.DisplayName}) in this server ({ctx.Guild.Name}), and will be proxied using that name here.");
} }
} }
@ -226,8 +226,8 @@ namespace PluralKit.Bot
var lcx = ctx.LookupContextFor(target); var lcx = ctx.LookupContextFor(target);
MemberGuildSettings memberGuildConfig = null; MemberGuildSettings memberGuildConfig = null;
if (ctx.GuildNew != null) if (ctx.Guild != null)
memberGuildConfig = await _db.Execute(c => _repo.GetMemberGuild(c, ctx.GuildNew.Id, target.Id)); memberGuildConfig = await _db.Execute(c => _repo.GetMemberGuild(c, ctx.Guild.Id, target.Id));
var eb = new EmbedBuilder() var eb = new EmbedBuilder()
.Title($"Member names") .Title($"Member names")
@ -246,12 +246,12 @@ namespace PluralKit.Bot
eb.Field(new("Display Name", target.DisplayName ?? "*(none)*")); eb.Field(new("Display Name", target.DisplayName ?? "*(none)*"));
} }
if (ctx.GuildNew != null) if (ctx.Guild != null)
{ {
if (memberGuildConfig?.DisplayName != null) if (memberGuildConfig?.DisplayName != null)
eb.Field(new($"Server Name (in {ctx.GuildNew.Name})", $"**{memberGuildConfig.DisplayName}**")); eb.Field(new($"Server Name (in {ctx.Guild.Name})", $"**{memberGuildConfig.DisplayName}**"));
else else
eb.Field(new($"Server Name (in {ctx.GuildNew.Name})", memberGuildConfig?.DisplayName ?? "*(none)*")); eb.Field(new($"Server Name (in {ctx.Guild.Name})", memberGuildConfig?.DisplayName ?? "*(none)*"));
} }
return eb; return eb;
@ -262,11 +262,11 @@ namespace PluralKit.Bot
async Task PrintSuccess(string text) async Task PrintSuccess(string text)
{ {
var successStr = text; var successStr = text;
if (ctx.GuildNew != null) if (ctx.Guild != null)
{ {
var memberGuildConfig = await _db.Execute(c => _repo.GetMemberGuild(c, ctx.GuildNew.Id, target.Id)); var memberGuildConfig = await _db.Execute(c => _repo.GetMemberGuild(c, ctx.Guild.Id, target.Id));
if (memberGuildConfig.DisplayName != null) if (memberGuildConfig.DisplayName != null)
successStr += $" However, this member has a server name set in this server ({ctx.GuildNew.Name}), and will be proxied using that name, \"{memberGuildConfig.DisplayName}\", here."; successStr += $" However, this member has a server name set in this server ({ctx.Guild.Name}), and will be proxied using that name, \"{memberGuildConfig.DisplayName}\", here.";
} }
await ctx.Reply(successStr); await ctx.Reply(successStr);
@ -311,12 +311,12 @@ namespace PluralKit.Bot
ctx.CheckOwnMember(target); ctx.CheckOwnMember(target);
var patch = new MemberGuildPatch {DisplayName = null}; var patch = new MemberGuildPatch {DisplayName = null};
await _db.Execute(conn => _repo.UpsertMemberGuild(conn, target.Id, ctx.GuildNew.Id, patch)); await _db.Execute(conn => _repo.UpsertMemberGuild(conn, target.Id, ctx.Guild.Id, patch));
if (target.DisplayName != null) if (target.DisplayName != null)
await ctx.Reply($"{Emojis.Success} Member server name cleared. This member will now be proxied using their global display name \"{target.DisplayName}\" in this server ({ctx.GuildNew.Name})."); await ctx.Reply($"{Emojis.Success} Member server name cleared. This member will now be proxied using their global display name \"{target.DisplayName}\" in this server ({ctx.Guild.Name}).");
else else
await ctx.Reply($"{Emojis.Success} Member server name cleared. This member will now be proxied using their member name \"{target.NameFor(ctx)}\" in this server ({ctx.GuildNew.Name})."); await ctx.Reply($"{Emojis.Success} Member server name cleared. This member will now be proxied using their member name \"{target.NameFor(ctx)}\" in this server ({ctx.Guild.Name}).");
} }
else if (!ctx.HasNext()) else if (!ctx.HasNext())
{ {
@ -333,9 +333,9 @@ namespace PluralKit.Bot
var newServerName = ctx.RemainderOrNull(); var newServerName = ctx.RemainderOrNull();
var patch = new MemberGuildPatch {DisplayName = newServerName}; var patch = new MemberGuildPatch {DisplayName = newServerName};
await _db.Execute(conn => _repo.UpsertMemberGuild(conn, target.Id, ctx.GuildNew.Id, patch)); await _db.Execute(conn => _repo.UpsertMemberGuild(conn, target.Id, ctx.Guild.Id, patch));
await ctx.Reply($"{Emojis.Success} Member server name changed. This member will now be proxied using the name \"{newServerName}\" in this server ({ctx.GuildNew.Name})."); await ctx.Reply($"{Emojis.Success} Member server name changed. This member will now be proxied using the name \"{newServerName}\" in this server ({ctx.Guild.Name}).");
} }
} }
@ -415,8 +415,8 @@ namespace PluralKit.Bot
// Get guild settings (mostly for warnings and such) // Get guild settings (mostly for warnings and such)
MemberGuildSettings guildSettings = null; MemberGuildSettings guildSettings = null;
if (ctx.GuildNew != null) if (ctx.Guild != null)
guildSettings = await _db.Execute(c => _repo.GetMemberGuild(c, ctx.GuildNew.Id, target.Id)); guildSettings = await _db.Execute(c => _repo.GetMemberGuild(c, ctx.Guild.Id, target.Id));
async Task SetAll(PrivacyLevel level) async Task SetAll(PrivacyLevel level)
{ {

View File

@ -84,10 +84,10 @@ namespace PluralKit.Bot {
var totalSwitches = _metrics.Snapshot.GetForContext("Application").Gauges.FirstOrDefault(m => m.MultidimensionalName == CoreMetrics.SwitchCount.Name)?.Value ?? 0; 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; var totalMessages = _metrics.Snapshot.GetForContext("Application").Gauges.FirstOrDefault(m => m.MultidimensionalName == CoreMetrics.MessageCount.Name)?.Value ?? 0;
var shardId = ctx.ShardNew.ShardInfo.ShardId; var shardId = ctx.Shard.ShardInfo.ShardId;
var shardTotal = ctx.Cluster.Shards.Count; var shardTotal = ctx.Cluster.Shards.Count;
var shardUpTotal = _shards.Shards.Where(x => x.Connected).Count(); var shardUpTotal = _shards.Shards.Where(x => x.Connected).Count();
var shardInfo = _shards.GetShardInfo(ctx.ShardNew); var shardInfo = _shards.GetShardInfo(ctx.Shard);
var process = Process.GetCurrentProcess(); var process = Process.GetCurrentProcess();
var memoryUsage = process.WorkingSet64; var memoryUsage = process.WorkingSet64;
@ -106,7 +106,7 @@ namespace PluralKit.Bot {
.Field(new("Memory usage", $"{memoryUsage / 1024 / 1024} MiB", 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("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")); .Field(new("Total numbers", $"{totalSystems:N0} systems, {totalMembers:N0} members, {totalGroups:N0} groups, {totalSwitches:N0} switches, {totalMessages:N0} messages"));
await ctx.RestNew.EditMessage(msg.ChannelId, msg.Id, await ctx.Rest.EditMessage(msg.ChannelId, msg.Id,
new MessageEditRequest {Content = "", Embed = embed.Build()}); new MessageEditRequest {Content = "", Embed = embed.Build()});
} }
@ -115,10 +115,10 @@ namespace PluralKit.Bot {
Guild guild; Guild guild;
GuildMemberPartial senderGuildUser = null; GuildMemberPartial senderGuildUser = null;
if (ctx.GuildNew != null && !ctx.HasNext()) if (ctx.Guild != null && !ctx.HasNext())
{ {
guild = ctx.GuildNew; guild = ctx.Guild;
senderGuildUser = ctx.MemberNew; senderGuildUser = ctx.Member;
} }
else else
{ {
@ -128,7 +128,7 @@ namespace PluralKit.Bot {
guild = await _rest.GetGuild(guildId); guild = await _rest.GetGuild(guildId);
if (guild != null) if (guild != null)
senderGuildUser = await _rest.GetGuildMember(guildId, ctx.AuthorNew.Id); senderGuildUser = await _rest.GetGuildMember(guildId, ctx.Author.Id);
if (guild == null || senderGuildUser == null) if (guild == null || senderGuildUser == null)
throw Errors.GuildNotFound(guildId); throw Errors.GuildNotFound(guildId);
} }
@ -150,7 +150,7 @@ namespace PluralKit.Bot {
foreach (var channel in await _rest.GetGuildChannels(guild.Id)) foreach (var channel in await _rest.GetGuildChannels(guild.Id))
{ {
var botPermissions = _bot.PermissionsIn(channel.Id); var botPermissions = _bot.PermissionsIn(channel.Id);
var userPermissions = PermissionExtensions.PermissionsFor(guild, channel, ctx.AuthorNew.Id, senderGuildUser.Roles); var userPermissions = PermissionExtensions.PermissionsFor(guild, channel, ctx.Author.Id, senderGuildUser.Roles);
if ((userPermissions & PermissionSet.ViewChannel) == 0) if ((userPermissions & PermissionSet.ViewChannel) == 0)
{ {

View File

@ -38,7 +38,7 @@ namespace PluralKit.Bot
throw new PKError("Your system has no members! Please create at least one member before using this command."); throw new PKError("Your system has no members! Please create at least one member before using this command.");
var randInt = randGen.Next(members.Count); var randInt = randGen.Next(members.Count);
await ctx.Reply(embed: await _embeds.CreateMemberEmbed(ctx.System, members[randInt], ctx.GuildNew, ctx.LookupContextFor(ctx.System))); await ctx.Reply(embed: await _embeds.CreateMemberEmbed(ctx.System, members[randInt], ctx.Guild, ctx.LookupContextFor(ctx.System)));
} }
public async Task Group(Context ctx) public async Task Group(Context ctx)
@ -73,7 +73,7 @@ namespace PluralKit.Bot
var ms = members.ToList(); var ms = members.ToList();
var randInt = randGen.Next(ms.Count); var randInt = randGen.Next(ms.Count);
await ctx.Reply(embed: await _embeds.CreateMemberEmbed(ctx.System, ms[randInt], ctx.GuildNew, ctx.LookupContextFor(ctx.System))); await ctx.Reply(embed: await _embeds.CreateMemberEmbed(ctx.System, ms[randInt], ctx.Guild, ctx.LookupContextFor(ctx.System)));
} }
} }
} }

View File

@ -32,7 +32,7 @@ namespace PluralKit.Bot
if (await ctx.MatchClear("the server log channel")) if (await ctx.MatchClear("the server log channel"))
{ {
await _db.Execute(conn => _repo.UpsertGuild(conn, ctx.GuildNew.Id, new GuildPatch {LogChannel = null})); await _db.Execute(conn => _repo.UpsertGuild(conn, ctx.Guild.Id, new GuildPatch {LogChannel = null}));
await ctx.Reply($"{Emojis.Success} Proxy logging channel cleared."); await ctx.Reply($"{Emojis.Success} Proxy logging channel cleared.");
return; return;
} }
@ -43,10 +43,10 @@ namespace PluralKit.Bot
Channel channel = null; Channel channel = null;
var channelString = ctx.PeekArgument(); var channelString = ctx.PeekArgument();
channel = await ctx.MatchChannel(); channel = await ctx.MatchChannel();
if (channel == null || channel.GuildId != ctx.GuildNew.Id) throw Errors.ChannelNotFound(channelString); if (channel == null || channel.GuildId != ctx.Guild.Id) throw Errors.ChannelNotFound(channelString);
var patch = new GuildPatch {LogChannel = channel.Id}; var patch = new GuildPatch {LogChannel = channel.Id};
await _db.Execute(conn => _repo.UpsertGuild(conn, ctx.GuildNew.Id, patch)); await _db.Execute(conn => _repo.UpsertGuild(conn, ctx.Guild.Id, patch));
await ctx.Reply($"{Emojis.Success} Proxy logging channel set to #{channel.Name}."); await ctx.Reply($"{Emojis.Success} Proxy logging channel set to #{channel.Name}.");
} }
@ -56,20 +56,20 @@ namespace PluralKit.Bot
var affectedChannels = new List<Channel>(); var affectedChannels = new List<Channel>();
if (ctx.Match("all")) if (ctx.Match("all"))
affectedChannels = _cache.GetGuildChannels(ctx.GuildNew.Id).Where(x => x.Type == Channel.ChannelType.GuildText).ToList(); affectedChannels = _cache.GetGuildChannels(ctx.Guild.Id).Where(x => x.Type == Channel.ChannelType.GuildText).ToList();
else if (!ctx.HasNext()) throw new PKSyntaxError("You must pass one or more #channels."); else if (!ctx.HasNext()) throw new PKSyntaxError("You must pass one or more #channels.");
else while (ctx.HasNext()) else while (ctx.HasNext())
{ {
var channelString = ctx.PeekArgument(); var channelString = ctx.PeekArgument();
var channel = await ctx.MatchChannel(); var channel = await ctx.MatchChannel();
if (channel == null || channel.GuildId != ctx.GuildNew.Id) throw Errors.ChannelNotFound(channelString); if (channel == null || channel.GuildId != ctx.Guild.Id) throw Errors.ChannelNotFound(channelString);
affectedChannels.Add(channel); affectedChannels.Add(channel);
} }
ulong? logChannel = null; ulong? logChannel = null;
await using (var conn = await _db.Obtain()) await using (var conn = await _db.Obtain())
{ {
var config = await _repo.GetGuild(conn, ctx.GuildNew.Id); var config = await _repo.GetGuild(conn, ctx.Guild.Id);
logChannel = config.LogChannel; logChannel = config.LogChannel;
var blacklist = config.LogBlacklist.ToHashSet(); var blacklist = config.LogBlacklist.ToHashSet();
if (enable) if (enable)
@ -78,7 +78,7 @@ namespace PluralKit.Bot
blacklist.UnionWith(affectedChannels.Select(c => c.Id)); blacklist.UnionWith(affectedChannels.Select(c => c.Id));
var patch = new GuildPatch {LogBlacklist = blacklist.ToArray()}; var patch = new GuildPatch {LogBlacklist = blacklist.ToArray()};
await _repo.UpsertGuild(conn, ctx.GuildNew.Id, patch); await _repo.UpsertGuild(conn, ctx.Guild.Id, patch);
} }
await ctx.Reply( await ctx.Reply(
@ -90,7 +90,7 @@ namespace PluralKit.Bot
{ {
ctx.CheckGuildContext().CheckAuthorPermission(PermissionSet.ManageGuild, "Manage Server"); ctx.CheckGuildContext().CheckAuthorPermission(PermissionSet.ManageGuild, "Manage Server");
var blacklist = await _db.Execute(c => _repo.GetGuild(c, ctx.GuildNew.Id)); var blacklist = await _db.Execute(c => _repo.GetGuild(c, ctx.Guild.Id));
// Resolve all channels from the cache and order by position // Resolve all channels from the cache and order by position
var channels = blacklist.Blacklist var channels = blacklist.Blacklist
@ -106,7 +106,7 @@ namespace PluralKit.Bot
} }
await ctx.Paginate(channels.ToAsyncEnumerable(), channels.Count, 25, await ctx.Paginate(channels.ToAsyncEnumerable(), channels.Count, 25,
$"Blacklisted channels for {ctx.GuildNew.Name}", $"Blacklisted channels for {ctx.Guild.Name}",
(eb, l) => (eb, l) =>
{ {
string CategoryName(ulong? id) => string CategoryName(ulong? id) =>
@ -140,19 +140,19 @@ namespace PluralKit.Bot
var affectedChannels = new List<Channel>(); var affectedChannels = new List<Channel>();
if (ctx.Match("all")) if (ctx.Match("all"))
affectedChannels = _cache.GetGuildChannels(ctx.GuildNew.Id).Where(x => x.Type == Channel.ChannelType.GuildText).ToList(); affectedChannels = _cache.GetGuildChannels(ctx.Guild.Id).Where(x => x.Type == Channel.ChannelType.GuildText).ToList();
else if (!ctx.HasNext()) throw new PKSyntaxError("You must pass one or more #channels."); else if (!ctx.HasNext()) throw new PKSyntaxError("You must pass one or more #channels.");
else while (ctx.HasNext()) else while (ctx.HasNext())
{ {
var channelString = ctx.PeekArgument(); var channelString = ctx.PeekArgument();
var channel = await ctx.MatchChannel(); var channel = await ctx.MatchChannel();
if (channel == null || channel.GuildId != ctx.GuildNew.Id) throw Errors.ChannelNotFound(channelString); if (channel == null || channel.GuildId != ctx.Guild.Id) throw Errors.ChannelNotFound(channelString);
affectedChannels.Add(channel); affectedChannels.Add(channel);
} }
await using (var conn = await _db.Obtain()) await using (var conn = await _db.Obtain())
{ {
var guild = await _repo.GetGuild(conn, ctx.GuildNew.Id); var guild = await _repo.GetGuild(conn, ctx.Guild.Id);
var blacklist = guild.Blacklist.ToHashSet(); var blacklist = guild.Blacklist.ToHashSet();
if (shouldAdd) if (shouldAdd)
blacklist.UnionWith(affectedChannels.Select(c => c.Id)); blacklist.UnionWith(affectedChannels.Select(c => c.Id));
@ -160,7 +160,7 @@ namespace PluralKit.Bot
blacklist.ExceptWith(affectedChannels.Select(c => c.Id)); blacklist.ExceptWith(affectedChannels.Select(c => c.Id));
var patch = new GuildPatch {Blacklist = blacklist.ToArray()}; var patch = new GuildPatch {Blacklist = blacklist.ToArray()};
await _repo.UpsertGuild(conn, ctx.GuildNew.Id, patch); await _repo.UpsertGuild(conn, ctx.Guild.Id, patch);
} }
await ctx.Reply($"{Emojis.Success} Channels {(shouldAdd ? "added to" : "removed from")} the proxy blacklist."); await ctx.Reply($"{Emojis.Success} Channels {(shouldAdd ? "added to" : "removed from")} the proxy blacklist.");
@ -183,7 +183,7 @@ namespace PluralKit.Bot
.Title("Log cleanup settings") .Title("Log cleanup settings")
.Field(new("Supported bots", botList)); .Field(new("Supported bots", botList));
var guildCfg = await _db.Execute(c => _repo.GetGuild(c, ctx.GuildNew.Id)); var guildCfg = await _db.Execute(c => _repo.GetGuild(c, ctx.Guild.Id));
if (guildCfg.LogCleanupEnabled) if (guildCfg.LogCleanupEnabled)
eb.Description("Log cleanup is currently **on** for this server. To disable it, type `pk;logclean off`."); eb.Description("Log cleanup is currently **on** for this server. To disable it, type `pk;logclean off`.");
else else
@ -193,7 +193,7 @@ namespace PluralKit.Bot
} }
var patch = new GuildPatch {LogCleanupEnabled = newValue}; var patch = new GuildPatch {LogCleanupEnabled = newValue};
await _db.Execute(conn => _repo.UpsertGuild(conn, ctx.GuildNew.Id, patch)); await _db.Execute(conn => _repo.UpsertGuild(conn, ctx.Guild.Id, patch));
if (newValue) if (newValue)
await ctx.Reply($"{Emojis.Success} Log cleanup has been **enabled** for this server. Messages deleted by PluralKit will now be cleaned up from logging channels managed by the following bots:\n- **{botList}**\n\n{Emojis.Note} Make sure PluralKit has the **Manage Messages** permission in the channels in question.\n{Emojis.Note} Also, make sure to blacklist the logging channel itself from the bots in question to prevent conflicts."); await ctx.Reply($"{Emojis.Success} Log cleanup has been **enabled** for this server. Messages deleted by PluralKit will now be cleaned up from logging channels managed by the following bots:\n- **{botList}**\n\n{Emojis.Note} Make sure PluralKit has the **Manage Messages** permission in the channels in question.\n{Emojis.Note} Also, make sure to blacklist the logging channel itself from the bots in question to prevent conflicts.");

View File

@ -34,7 +34,7 @@ namespace PluralKit.Bot
var system = _db.Execute(async c => var system = _db.Execute(async c =>
{ {
var system = await _repo.CreateSystem(c, systemName); var system = await _repo.CreateSystem(c, systemName);
await _repo.AddAccount(c, system.Id, ctx.AuthorNew.Id); await _repo.AddAccount(c, system.Id, ctx.Author.Id);
return system; return system;
}); });

View File

@ -191,7 +191,7 @@ namespace PluralKit.Bot
public async Task SystemProxy(Context ctx) public async Task SystemProxy(Context ctx)
{ {
ctx.CheckSystem().CheckGuildContext(); ctx.CheckSystem().CheckGuildContext();
var gs = await _db.Execute(c => _repo.GetSystemGuild(c, ctx.GuildNew.Id, ctx.System.Id)); var gs = await _db.Execute(c => _repo.GetSystemGuild(c, ctx.Guild.Id, ctx.System.Id));
bool newValue; bool newValue;
if (ctx.Match("on", "enabled", "true", "yes")) newValue = true; if (ctx.Match("on", "enabled", "true", "yes")) newValue = true;
@ -207,12 +207,12 @@ namespace PluralKit.Bot
} }
var patch = new SystemGuildPatch {ProxyEnabled = newValue}; var patch = new SystemGuildPatch {ProxyEnabled = newValue};
await _db.Execute(conn => _repo.UpsertSystemGuild(conn, ctx.System.Id, ctx.GuildNew.Id, patch)); await _db.Execute(conn => _repo.UpsertSystemGuild(conn, ctx.System.Id, ctx.Guild.Id, patch));
if (newValue) if (newValue)
await ctx.Reply($"Message proxying in this server ({ctx.GuildNew.Name.EscapeMarkdown()}) is now **enabled** for your system."); await ctx.Reply($"Message proxying in this server ({ctx.Guild.Name.EscapeMarkdown()}) is now **enabled** for your system.");
else else
await ctx.Reply($"Message proxying in this server ({ctx.GuildNew.Name.EscapeMarkdown()}) is now **disabled** for your system."); await ctx.Reply($"Message proxying in this server ({ctx.Guild.Name.EscapeMarkdown()}) is now **disabled** for your system.");
} }
public async Task SystemTimezone(Context ctx) public async Task SystemTimezone(Context ctx)

View File

@ -49,7 +49,7 @@ namespace PluralKit.Bot
ulong id; ulong id;
if (!ctx.HasNext()) if (!ctx.HasNext())
id = ctx.AuthorNew.Id; id = ctx.Author.Id;
else if (!ctx.MatchUserRaw(out id)) else if (!ctx.MatchUserRaw(out id))
throw new PKSyntaxError("You must pass an account to link with (either ID or @mention)."); throw new PKSyntaxError("You must pass an account to link with (either ID or @mention).");

View File

@ -29,21 +29,21 @@ namespace PluralKit.Bot
try try
{ {
// DM the user a security disclaimer, and then the token in a separate message (for easy copying on mobile) // DM the user a security disclaimer, and then the token in a separate message (for easy copying on mobile)
var dm = await ctx.Cache.GetOrCreateDmChannel(ctx.RestNew, ctx.AuthorNew.Id); var dm = await ctx.Cache.GetOrCreateDmChannel(ctx.Rest, ctx.Author.Id);
await ctx.RestNew.CreateMessage(dm.Id, new MessageRequest await ctx.Rest.CreateMessage(dm.Id, new MessageRequest
{ {
Content = $"{Emojis.Warn} Please note that this grants access to modify (and delete!) all your system data, so keep it safe and secure. If it leaks or you need a new one, you can invalidate this one with `pk;token refresh`.\n\nYour token is below:" Content = $"{Emojis.Warn} Please note that this grants access to modify (and delete!) all your system data, so keep it safe and secure. If it leaks or you need a new one, you can invalidate this one with `pk;token refresh`.\n\nYour token is below:"
}); });
await ctx.RestNew.CreateMessage(dm.Id, new MessageRequest {Content = token}); await ctx.Rest.CreateMessage(dm.Id, new MessageRequest {Content = token});
// If we're not already in a DM, reply with a reminder to check // If we're not already in a DM, reply with a reminder to check
if (ctx.ChannelNew.Type != Channel.ChannelType.Dm) if (ctx.Channel.Type != Channel.ChannelType.Dm)
await ctx.Reply($"{Emojis.Success} Check your DMs!"); await ctx.Reply($"{Emojis.Success} Check your DMs!");
} }
catch (UnauthorizedException) catch (UnauthorizedException)
{ {
// Can't check for permission errors beforehand, so have to handle here :/ // Can't check for permission errors beforehand, so have to handle here :/
if (ctx.ChannelNew.Type != Channel.ChannelType.Dm) if (ctx.Channel.Type != Channel.ChannelType.Dm)
await ctx.Reply($"{Emojis.Error} Could not send token in DMs. Are your DMs closed?"); await ctx.Reply($"{Emojis.Error} Could not send token in DMs. Are your DMs closed?");
} }
} }
@ -69,8 +69,8 @@ namespace PluralKit.Bot
try { try {
// DM the user an invalidation disclaimer, and then the token in a separate message (for easy copying on mobile) // DM the user an invalidation disclaimer, and then the token in a separate message (for easy copying on mobile)
var dm = await ctx.Cache.GetOrCreateDmChannel(ctx.RestNew, ctx.AuthorNew.Id); var dm = await ctx.Cache.GetOrCreateDmChannel(ctx.Rest, ctx.Author.Id);
await ctx.RestNew.CreateMessage(dm.Id, new MessageRequest await ctx.Rest.CreateMessage(dm.Id, new MessageRequest
{ {
Content = $"{Emojis.Warn} Your previous API token has been invalidated. You will need to change it anywhere it's currently used.\n\nYour token is below:" Content = $"{Emojis.Warn} Your previous API token has been invalidated. You will need to change it anywhere it's currently used.\n\nYour token is below:"
}); });
@ -78,16 +78,16 @@ namespace PluralKit.Bot
// Make the new token after sending the first DM; this ensures if we can't DM, we also don't end up // Make the new token after sending the first DM; this ensures if we can't DM, we also don't end up
// breaking their existing token as a side effect :) // breaking their existing token as a side effect :)
var token = await MakeAndSetNewToken(ctx.System); var token = await MakeAndSetNewToken(ctx.System);
await ctx.RestNew.CreateMessage(dm.Id, new MessageRequest { Content = token }); await ctx.Rest.CreateMessage(dm.Id, new MessageRequest { Content = token });
// If we're not already in a DM, reply with a reminder to check // If we're not already in a DM, reply with a reminder to check
if (ctx.ChannelNew.Type != Channel.ChannelType.Dm) if (ctx.Channel.Type != Channel.ChannelType.Dm)
await ctx.Reply($"{Emojis.Success} Check your DMs!"); await ctx.Reply($"{Emojis.Success} Check your DMs!");
} }
catch (UnauthorizedException) catch (UnauthorizedException)
{ {
// Can't check for permission errors beforehand, so have to handle here :/ // Can't check for permission errors beforehand, so have to handle here :/
if (ctx.ChannelNew.Type != Channel.ChannelType.Dm) if (ctx.Channel.Type != Channel.ChannelType.Dm)
await ctx.Reply($"{Emojis.Error} Could not send token in DMs. Are your DMs closed?"); await ctx.Reply($"{Emojis.Error} Could not send token in DMs. Are your DMs closed?");
} }
} }

View File

@ -31,11 +31,11 @@ namespace PluralKit.Bot {
if (matchFlag && ctx.MatchFlag("y", "yes")) return true; if (matchFlag && ctx.MatchFlag("y", "yes")) return true;
else message = await ctx.Reply(msgString, mentions: mentions); else message = await ctx.Reply(msgString, mentions: mentions);
var cts = new CancellationTokenSource(); var cts = new CancellationTokenSource();
if (user == null) user = ctx.AuthorNew; if (user == null) user = ctx.Author;
if (timeout == null) timeout = Duration.FromMinutes(5); if (timeout == null) timeout = Duration.FromMinutes(5);
// "Fork" the task adding the reactions off so we don't have to wait for them to be finished to start listening for presses // "Fork" the task adding the reactions off so we don't have to wait for them to be finished to start listening for presses
await ctx.RestNew.CreateReactionsBulk(message, new[] {Emojis.Success, Emojis.Error}); await ctx.Rest.CreateReactionsBulk(message, new[] {Emojis.Success, Emojis.Error});
bool ReactionPredicate(MessageReactionAddEvent e) bool ReactionPredicate(MessageReactionAddEvent e)
{ {
@ -88,7 +88,7 @@ namespace PluralKit.Bot {
public static async Task<bool> ConfirmWithReply(this Context ctx, string expectedReply) public static async Task<bool> ConfirmWithReply(this Context ctx, string expectedReply)
{ {
bool Predicate(MessageCreateEvent e) => bool Predicate(MessageCreateEvent e) =>
e.Author.Id == ctx.AuthorNew.Id && e.ChannelId == ctx.ChannelNew.Id; e.Author.Id == ctx.Author.Id && e.ChannelId == ctx.Channel.Id;
var msg = await ctx.Services.Resolve<HandlerQueue<MessageCreateEvent>>() var msg = await ctx.Services.Resolve<HandlerQueue<MessageCreateEvent>>()
.WaitFor(Predicate, Duration.FromMinutes(1)); .WaitFor(Predicate, Duration.FromMinutes(1));
@ -121,12 +121,12 @@ namespace PluralKit.Bot {
if (pageCount <= 1) return; // If we only have one (or no) page, don't bother with the reaction/pagination logic, lol if (pageCount <= 1) return; // If we only have one (or no) page, don't bother with the reaction/pagination logic, lol
string[] botEmojis = { "\u23EA", "\u2B05", "\u27A1", "\u23E9", Emojis.Error }; string[] botEmojis = { "\u23EA", "\u2B05", "\u27A1", "\u23E9", Emojis.Error };
var _ = ctx.RestNew.CreateReactionsBulk(msg, botEmojis); // Again, "fork" var _ = ctx.Rest.CreateReactionsBulk(msg, botEmojis); // Again, "fork"
try { try {
var currentPage = 0; var currentPage = 0;
while (true) { while (true) {
var reaction = await ctx.AwaitReaction(msg, ctx.AuthorNew, timeout: Duration.FromMinutes(5)); var reaction = await ctx.AwaitReaction(msg, ctx.Author, timeout: Duration.FromMinutes(5));
// Increment/decrement page counter based on which reaction was clicked // Increment/decrement page counter based on which reaction was clicked
if (reaction.Emoji.Name == "\u23EA") currentPage = 0; // << if (reaction.Emoji.Name == "\u23EA") currentPage = 0; // <<
@ -140,18 +140,18 @@ namespace PluralKit.Bot {
// If we can, remove the user's reaction (so they can press again quickly) // If we can, remove the user's reaction (so they can press again quickly)
if (ctx.BotPermissions.HasFlag(PermissionSet.ManageMessages)) if (ctx.BotPermissions.HasFlag(PermissionSet.ManageMessages))
await ctx.RestNew.DeleteUserReaction(msg.ChannelId, msg.Id, reaction.Emoji, reaction.UserId); await ctx.Rest.DeleteUserReaction(msg.ChannelId, msg.Id, reaction.Emoji, reaction.UserId);
// Edit the embed with the new page // Edit the embed with the new page
var embed = await MakeEmbedForPage(currentPage); var embed = await MakeEmbedForPage(currentPage);
await ctx.RestNew.EditMessage(msg.ChannelId, msg.Id, new MessageEditRequest {Embed = embed}); await ctx.Rest.EditMessage(msg.ChannelId, msg.Id, new MessageEditRequest {Embed = embed});
} }
} catch (TimeoutException) { } catch (TimeoutException) {
// "escape hatch", clean up as if we hit X // "escape hatch", clean up as if we hit X
} }
if (ctx.BotPermissions.HasFlag(PermissionSet.ManageMessages)) if (ctx.BotPermissions.HasFlag(PermissionSet.ManageMessages))
await ctx.RestNew.DeleteAllReactions(msg.ChannelId, msg.Id); await ctx.Rest.DeleteAllReactions(msg.ChannelId, msg.Id);
} }
// If we get a "NotFound" error, the message has been deleted and thus not our problem // If we get a "NotFound" error, the message has been deleted and thus not our problem
catch (NotFoundException) { } catch (NotFoundException) { }
@ -189,10 +189,10 @@ namespace PluralKit.Bot {
// Add back/forward reactions and the actual indicator emojis // Add back/forward reactions and the actual indicator emojis
async Task AddEmojis() async Task AddEmojis()
{ {
await ctx.RestNew.CreateReaction(msg.ChannelId, msg.Id, new() { Name = "\u2B05" }); await ctx.Rest.CreateReaction(msg.ChannelId, msg.Id, new() { Name = "\u2B05" });
await ctx.RestNew.CreateReaction(msg.ChannelId, msg.Id, new() { Name = "\u27A1" }); await ctx.Rest.CreateReaction(msg.ChannelId, msg.Id, new() { Name = "\u27A1" });
for (int i = 0; i < items.Count; i++) for (int i = 0; i < items.Count; i++)
await ctx.RestNew.CreateReaction(msg.ChannelId, msg.Id, new() { Name = indicators[i] }); await ctx.Rest.CreateReaction(msg.ChannelId, msg.Id, new() { Name = indicators[i] });
} }
var _ = AddEmojis(); // Not concerned about awaiting var _ = AddEmojis(); // Not concerned about awaiting
@ -200,7 +200,7 @@ namespace PluralKit.Bot {
while (true) while (true)
{ {
// Wait for a reaction // Wait for a reaction
var reaction = await ctx.AwaitReaction(msg, ctx.AuthorNew); var reaction = await ctx.AwaitReaction(msg, ctx.Author);
// If it's a movement reaction, inc/dec the page index // If it's a movement reaction, inc/dec the page index
if (reaction.Emoji.Name == "\u2B05") currPage -= 1; // < if (reaction.Emoji.Name == "\u2B05") currPage -= 1; // <
@ -217,8 +217,8 @@ namespace PluralKit.Bot {
if (idx < items.Count) return items[idx]; if (idx < items.Count) return items[idx];
} }
var __ = ctx.RestNew.DeleteUserReaction(msg.ChannelId, msg.Id, reaction.Emoji, ctx.AuthorNew.Id); var __ = ctx.Rest.DeleteUserReaction(msg.ChannelId, msg.Id, reaction.Emoji, ctx.Author.Id);
await ctx.RestNew.EditMessage(msg.ChannelId, msg.Id, await ctx.Rest.EditMessage(msg.ChannelId, msg.Id,
new() new()
{ {
Content = Content =
@ -234,13 +234,13 @@ namespace PluralKit.Bot {
async Task AddEmojis() async Task AddEmojis()
{ {
for (int i = 0; i < items.Count; i++) for (int i = 0; i < items.Count; i++)
await ctx.RestNew.CreateReaction(msg.ChannelId, msg.Id, new() {Name = indicators[i]}); await ctx.Rest.CreateReaction(msg.ChannelId, msg.Id, new() {Name = indicators[i]});
} }
var _ = AddEmojis(); var _ = AddEmojis();
// Then wait for a reaction and return whichever one we found // Then wait for a reaction and return whichever one we found
var reaction = await ctx.AwaitReaction(msg, ctx.AuthorNew,rx => indicators.Contains(rx.Emoji.Name)); var reaction = await ctx.AwaitReaction(msg, ctx.Author,rx => indicators.Contains(rx.Emoji.Name));
return items[Array.IndexOf(indicators, reaction.Emoji.Name)]; return items[Array.IndexOf(indicators, reaction.Emoji.Name)];
} }
} }
@ -264,12 +264,12 @@ namespace PluralKit.Bot {
try try
{ {
await Task.WhenAll(ctx.RestNew.CreateReaction(ctx.MessageNew.ChannelId, ctx.MessageNew.Id, new() {Name = emoji}), task); await Task.WhenAll(ctx.Rest.CreateReaction(ctx.Message.ChannelId, ctx.Message.Id, new() {Name = emoji}), task);
return await task; return await task;
} }
finally finally
{ {
var _ = ctx.RestNew.DeleteOwnReaction(ctx.MessageNew.ChannelId, ctx.MessageNew.Id, new() { Name = emoji }); var _ = ctx.Rest.DeleteOwnReaction(ctx.Message.ChannelId, ctx.Message.Id, new() { Name = emoji });
} }
} }
} }