forked from RPCS3/discord-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathForcedNicknames.cs
270 lines (251 loc) · 12.4 KB
/
ForcedNicknames.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CompatBot.Commands.Attributes;
using CompatBot.Database;
using CompatBot.EventHandlers;
using CompatBot.Utils;
using CompatBot.Utils.Extensions;
using DSharpPlus;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using Microsoft.EntityFrameworkCore;
namespace CompatBot.Commands;
[Group("rename")]
[Description("Manage users who has forced nickname.")]
internal sealed class ForcedNicknames : BaseCommandModuleCustom
{
[GroupCommand]
[Description("Enforces specific nickname for particular user.")]
public async Task Rename(CommandContext ctx,
[Description("Discord user to add to forced nickname list.")] DiscordUser discordUser,
[Description("Nickname which should be displayed."), RemainingText] string expectedNickname)
{
if (!await new RequiresBotModRole().ExecuteCheckAsync(ctx, false).ConfigureAwait(false))
return;
try
{
if (expectedNickname.Length is < 2 or > 32)
{
await ctx.ReactWithAsync(Config.Reactions.Failure, "Nickname must be between 2 and 32 characters long", true).ConfigureAwait(false);
return;
}
if ((!expectedNickname.All(c => char.IsLetterOrDigit(c)
|| char.IsWhiteSpace(c)
|| char.IsPunctuation(c))
|| expectedNickname.Any(c => c is ':' or '#' or '@' or '`')
) && !discordUser.IsBotSafeCheck())
{
await ctx.ReactWithAsync(Config.Reactions.Failure, "Nickname must follow Rule 7", true).ConfigureAwait(false);
return;
}
List<DiscordGuild> guilds;
if (ctx.Guild == null)
{
guilds = ctx.Client.Guilds?.Values.ToList() ?? [];
if (guilds.Count > 1)
await ctx.Channel.SendMessageAsync($"{discordUser.Mention} will be renamed in all {guilds.Count} servers").ConfigureAwait(false);
}
else
guilds = [ctx.Guild];
int changed = 0, noPermissions = 0, failed = 0;
await using var db = new BotDb();
foreach (var guild in guilds)
{
if (!discordUser.IsBotSafeCheck())
{
var enforceRules = db.ForcedNicknames.FirstOrDefault(mem => mem.UserId == discordUser.Id && mem.GuildId == guild.Id);
if (enforceRules is null)
{
enforceRules = new() {UserId = discordUser.Id, GuildId = guild.Id, Nickname = expectedNickname};
await db.ForcedNicknames.AddAsync(enforceRules).ConfigureAwait(false);
}
else
{
if (enforceRules.Nickname == expectedNickname)
continue;
enforceRules.Nickname = expectedNickname;
}
}
if (!(ctx.Guild?.Permissions?.HasFlag(Permissions.ChangeNickname) ?? true))
{
noPermissions++;
continue;
}
if (await ctx.Client.GetMemberAsync(guild, discordUser).ConfigureAwait(false) is DiscordMember discordMember)
try
{
await discordMember.ModifyAsync(x => x.Nickname = expectedNickname).ConfigureAwait(false);
changed++;
}
catch (Exception ex)
{
Config.Log.Warn(ex, "Failed to change nickname");
failed++;
}
}
await db.SaveChangesAsync().ConfigureAwait(false);
if (guilds.Count > 1)
{
if (changed > 0)
await ctx.ReactWithAsync(Config.Reactions.Success, $"Forced nickname for {discordUser.Mention} in {changed} server{(changed == 1 ? "" : "s")}", true).ConfigureAwait(false);
else
await ctx.ReactWithAsync(Config.Reactions.Failure, $"Failed to force nickname for {discordUser.Mention} in any server").ConfigureAwait(false);
}
else
{
if (changed > 0)
await ctx.ReactWithAsync(Config.Reactions.Success, $"Forced nickname for {discordUser.Mention}", true).ConfigureAwait(false);
else if (failed > 0)
await ctx.ReactWithAsync(Config.Reactions.Failure, $"Failed to force nickname for {discordUser.Mention}").ConfigureAwait(false);
else if (noPermissions > 0)
await ctx.ReactWithAsync(Config.Reactions.Failure, $"No permissions to force nickname for {discordUser.Mention}").ConfigureAwait(false);
}
}
catch (Exception e)
{
Config.Log.Error(e);
await ctx.ReactWithAsync(Config.Reactions.Failure, "Failed to change nickname, check bot's permissions").ConfigureAwait(false);
}
}
[Command("clear"), Aliases("remove"), RequiresBotModRole]
[Description("Removes nickname restriction from particular user.")]
public async Task Remove(CommandContext ctx, [Description("Discord user to remove from forced nickname list.")] DiscordUser discordUser)
{
try
{
if (discordUser.IsBotSafeCheck())
{
var mem = await ctx.Client.GetMemberAsync(ctx.Guild.Id, discordUser).ConfigureAwait(false);
if (mem is not null)
{
await mem.ModifyAsync(m => m.Nickname = new(discordUser.Username)).ConfigureAwait(false);
await ctx.ReactWithAsync(Config.Reactions.Success).ConfigureAwait(false);
}
return;
}
await using var db = new BotDb();
var enforcedRules = ctx.Guild == null
? await db.ForcedNicknames.Where(mem => mem.UserId == discordUser.Id).ToListAsync().ConfigureAwait(false)
: await db.ForcedNicknames.Where(mem => mem.UserId == discordUser.Id && mem.GuildId == ctx.Guild.Id).ToListAsync().ConfigureAwait(false);
if (enforcedRules.Count == 0)
return;
db.ForcedNicknames.RemoveRange(enforcedRules);
await db.SaveChangesAsync().ConfigureAwait(false);
await ctx.ReactWithAsync(Config.Reactions.Success).ConfigureAwait(false);
}
catch (Exception e)
{
Config.Log.Error(e);
await ctx.ReactWithAsync(Config.Reactions.Failure, "Failed to reset user nickname").ConfigureAwait(false);
}
}
[Command("cleanup"), Aliases("clean", "fix"), RequiresBotModRole]
[Description("Removes zalgo from specified user nickname")]
public async Task Cleanup(CommandContext ctx, [Description("Discord user to clean up")] DiscordUser discordUser)
{
if (await ctx.Client.GetMemberAsync(discordUser).ConfigureAwait(false) is not DiscordMember member)
{
await ctx.ReactWithAsync(Config.Reactions.Failure, $"Failed to resolve guild member for user {discordUser.Username}#{discordUser.Discriminator}").ConfigureAwait(false);
return;
}
var name = member.DisplayName;
var newName = UsernameZalgoMonitor.StripZalgo(name, discordUser.Username, discordUser.Id);
if (name == newName)
await ctx.Channel.SendMessageAsync("Failed to remove any extra symbols").ConfigureAwait(false);
else
{
try
{
await member.ModifyAsync(m => m.Nickname = new(newName)).ConfigureAwait(false);
await ctx.ReactWithAsync(Config.Reactions.Success, $"Renamed user to {newName}", true).ConfigureAwait(false);
}
catch (Exception)
{
Config.Log.Warn($"Failed to rename user {discordUser.Username}#{discordUser.Discriminator}");
await ctx.ReactWithAsync(Config.Reactions.Failure, $"Failed to rename user to {newName}").ConfigureAwait(false);
}
}
}
[Command("dump")]
[Description("Prints hexadecimal binary representation of an UTF-8 encoded user name for diagnostic purposes")]
public async Task Dump(CommandContext ctx, [Description("Discord user to dump")] DiscordUser discordUser)
{
var name = discordUser.Username;
var nameBytes = StringUtils.Utf8.GetBytes(name);
var hex = BitConverter.ToString(nameBytes).Replace('-', ' ');
var result = $"User ID: {discordUser.Id}\nUsername: {hex}";
var member = await ctx.Client.GetMemberAsync(ctx.Guild, discordUser).ConfigureAwait(false);
if (member is { Nickname: { Length: > 0 } nickname })
{
nameBytes = StringUtils.Utf8.GetBytes(nickname);
hex = BitConverter.ToString(nameBytes).Replace('-', ' ');
result += "\nNickname: " + hex;
}
await ctx.Channel.SendMessageAsync(result).ConfigureAwait(false);
}
[Command("generate"), Aliases("gen", "suggest")]
[Description("Generates random name for specified user")]
public async Task Generate(CommandContext ctx, [Description("Discord user to dump")] DiscordUser discordUser)
{
var newName = UsernameZalgoMonitor.GenerateRandomName(discordUser.Id);
await ctx.Channel.SendMessageAsync(newName).ConfigureAwait(false);
}
[Command("autorename"), Aliases("auto"), RequiresBotModRole]
[Description("Sets automatically generated nickname without enforcing it")]
public async Task Autorename(CommandContext ctx, [Description("Discord user to rename")] DiscordUser discordUser)
{
var newName = UsernameZalgoMonitor.GenerateRandomName(discordUser.Id);
try
{
if (await ctx.Client.GetMemberAsync(discordUser).ConfigureAwait(false) is { } member)
{
await member.ModifyAsync(m => m.Nickname = new(newName)).ConfigureAwait(false);
await ctx.ReactWithAsync(Config.Reactions.Success, $"Renamed user to {newName}", true).ConfigureAwait(false);
}
else
await ctx.ReactWithAsync(Config.Reactions.Failure, $"Couldn't resolve guild member for user {discordUser.Username}#{discordUser.Discriminator}").ConfigureAwait(false);
}
catch (Exception e)
{
Config.Log.Warn(e, $"Failed to rename user {discordUser.Username}#{discordUser.Discriminator}");
await ctx.ReactWithAsync(Config.Reactions.Failure, $"Failed to rename user to {newName}").ConfigureAwait(false);
}
}
[Command("list"), RequiresBotModRole]
[Description("Lists all users who has restricted nickname.")]
public async Task List(CommandContext ctx)
{
await using var db = new BotDb();
var selectExpr = db.ForcedNicknames.AsNoTracking();
if (ctx.Guild != null)
selectExpr = selectExpr.Where(mem => mem.GuildId == ctx.Guild.Id);
var forcedNicknames = (
from m in selectExpr.AsEnumerable()
orderby m.UserId, m.Nickname
let result = new {m.UserId, m.Nickname}
select result
).ToList();
if (forcedNicknames.Count == 0)
{
await ctx.Channel.SendMessageAsync("No users with forced nicknames").ConfigureAwait(false);
return;
}
var table = new AsciiTable(
new AsciiColumn("ID", !ctx.Channel.IsPrivate || !await ctx.User.IsWhitelistedAsync(ctx.Client).ConfigureAwait(false)),
new AsciiColumn("Username"),
new AsciiColumn("Forced nickname")
);
var previousUser = 0ul;
foreach (var forcedNickname in forcedNicknames.Distinct())
{
var sameUser = forcedNickname.UserId == previousUser;
var username = sameUser ? "" : await ctx.GetUserNameAsync(forcedNickname.UserId).ConfigureAwait(false);
table.Add( sameUser ? "" : forcedNickname.UserId.ToString(), username, forcedNickname.Nickname);
previousUser = forcedNickname.UserId;
}
await ctx.SendAutosplitMessageAsync(table.ToString()).ConfigureAwait(false);
}
}