Skip to content

Commit bd2f4ea

Browse files
committed
Couple changes to DisplayName use, Track edited messages, inc displayname and nick in logs
1 parent 2815978 commit bd2f4ea

File tree

7 files changed

+86
-47
lines changed

7 files changed

+86
-47
lines changed

DiscordBot/Extensions/UserExtensions.cs

Lines changed: 11 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -17,38 +17,21 @@ public static bool HasRoleGroup(this IUser user, ulong roleId)
1717
{
1818
return user is SocketGuildUser guildUser && guildUser.Roles.Any(x => x.Id == roleId);
1919
}
20-
21-
public static bool IsNickAndNameEqual(this IUser user)
20+
21+
// Returns the users DisplayName (nickname) if it exists, otherwise returns the username
22+
public static string GetUserPreferredName(this IUser user)
2223
{
2324
var guildUser = user as SocketGuildUser;
24-
if (guildUser == null)
25-
return true;
26-
return string.Equals(guildUser.Nickname, guildUser.Username, StringComparison.CurrentCultureIgnoreCase);
27-
}
28-
29-
// Returns a simple string formatted as: "**user.Username** (aka **user.Nickname**)"
30-
// Nickname is only included if it's different from the username
31-
public static string UserNameReferenceForEmbed(this IUser user)
32-
{
33-
var reference = $"**{user.GetNickName()}**!";
34-
if (!user.IsNickAndNameEqual())
35-
reference += $" (aka **{user.Username}**)";
36-
return reference;
25+
return guildUser?.DisplayName ?? user.Username;
3726
}
3827

39-
// Returns a simple string formatted as: "user.Username (aka user.Nickname)"
40-
// Nickname is only included if it's different from the username
41-
public static string UserNameReference(this IUser user)
28+
public static string GetPreferredAndUsername(this IUser user)
4229
{
43-
var reference = $"{user.GetNickName()}!";
44-
if (!user.IsNickAndNameEqual())
45-
reference += $" (aka {user.Username})";
46-
return reference;
47-
}
48-
49-
// Returns the nickname of the user if the IUser can be cast to it exists, otherwise returns the username
50-
public static string GetNickName(this IUser user)
51-
{
52-
return (user as SocketGuildUser)?.Nickname ?? user.Username;
30+
var guildUser = user as SocketGuildUser;
31+
if (guildUser == null)
32+
return user.Username;
33+
if (guildUser.DisplayName == user.Username)
34+
return guildUser.DisplayName;
35+
return $"{guildUser.DisplayName} (aka {user.Username})";
5336
}
5437
}

DiscordBot/Modules/UserModule.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ public async Task QuoteMessage(ulong messageId, IMessageChannel channel = null)
131131
.WithFooter(footer =>
132132
{
133133
footer
134-
.WithText($"Quoted by {Context.User.UserNameReference()} • From channel {message.Channel.Name}")
134+
.WithText($"Quoted by {Context.User.GetUserPreferredName()} • From channel {message.Channel.Name}")
135135
.WithIconUrl(Context.User.GetAvatarUrl());
136136
})
137137
.WithAuthor(author =>

DiscordBot/Modules/UserSlashModule.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ public async Task ModalResponse(ulong id, ReportMessageModal modal)
170170
.WithFooter(footer =>
171171
{
172172
footer
173-
.WithText($"Reported by {Context.User.UserNameReference()} • From channel {reportedMessage.Channel.Name}")
173+
.WithText($"Reported by {Context.User.GetPreferredAndUsername()} • From channel {reportedMessage.Channel.Name}")
174174
.WithIconUrl(Context.User.GetAvatarUrl());
175175
})
176176
.WithAuthor(author =>

DiscordBot/Services/DatabaseService.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ public async Task AddNewUser(SocketGuildUser socketUser)
146146
await Query().InsertUser(user);
147147

148148
await _logging.LogAction(
149-
$"User {socketUser.UserNameReference()} successfully added to the database.",
149+
$"User {socketUser.GetPreferredAndUsername()} successfully added to the database.",
150150
true,
151151
false);
152152
}

DiscordBot/Services/LoggingService.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ private static void SetConsoleColour(LogSeverity severity)
8989
break;
9090
case LogSeverity.Verbose:
9191
case LogSeverity.Debug:
92+
default:
9293
Console.ForegroundColor = ConsoleColor.DarkGray;
9394
break;
9495
}

DiscordBot/Services/ModerationService.cs

Lines changed: 62 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,18 @@ public class ModerationService
77
{
88
private readonly ILoggingService _loggingService;
99
private readonly BotSettings _settings;
10+
11+
private static readonly int MaxMessageLength = 800;
12+
private static readonly Color DeletedMessageColor = new Color(200, 128, 128);
13+
private static readonly Color EditedMessageColor = new Color(255, 255, 128);
1014

1115
public ModerationService(DiscordSocketClient client, BotSettings settings, ILoggingService loggingService)
1216
{
1317
_settings = settings;
1418
_loggingService = loggingService;
1519

1620
client.MessageDeleted += MessageDeleted;
21+
client.MessageUpdated += MessageUpdated;
1722
}
1823

1924
private async Task MessageDeleted(Cacheable<IMessage, ulong> message, Cacheable<IMessageChannel, ulong> channel)
@@ -22,12 +27,12 @@ private async Task MessageDeleted(Cacheable<IMessage, ulong> message, Cacheable<
2227
return;
2328

2429
var content = message.Value.Content;
25-
if (content.Length > 800)
26-
content = content.Substring(0, 800);
30+
if (content.Length > MaxMessageLength)
31+
content = content[..MaxMessageLength];
2732

2833
var user = message.Value.Author;
2934
var builder = new EmbedBuilder()
30-
.WithColor(new Color(200, 128, 128))
35+
.WithColor(DeletedMessageColor)
3136
.WithTimestamp(message.Value.Timestamp)
3237
.WithFooter(footer =>
3338
{
@@ -37,14 +42,64 @@ private async Task MessageDeleted(Cacheable<IMessage, ulong> message, Cacheable<
3742
.WithAuthor(author =>
3843
{
3944
author
40-
.WithName($"{user.Username}");
45+
.WithName($"{user.GetPreferredAndUsername()} deleted a message");
4146
})
42-
.AddField("Deleted message", content);
47+
.AddField($"Deleted Message {(content.Length != message.Value.Content.Length ? "(truncated)" : "")}",
48+
content);
4349
var embed = builder.Build();
44-
50+
51+
// TimeStamp for the Footer
52+
4553
await _loggingService.LogAction(
46-
$"User {user.UserNameReference()} has " +
54+
$"User {user.GetPreferredAndUsername()} has " +
4755
$"deleted the message\n{content}\n from channel #{(await channel.GetOrDownloadAsync()).Name}", true, false);
4856
await _loggingService.LogAction(" ", false, true, embed);
4957
}
58+
59+
private async Task MessageUpdated(Cacheable<IMessage, ulong> before, SocketMessage after, ISocketMessageChannel channel)
60+
{
61+
if (after.Author.IsBot || channel.Id == _settings.BotAnnouncementChannel.Id)
62+
return;
63+
64+
bool isCached = true;
65+
string content = "";
66+
var beforeMessage = await before.GetOrDownloadAsync();
67+
if (beforeMessage == null || beforeMessage.Content == after.Content)
68+
isCached = false;
69+
else
70+
content = beforeMessage.Content;
71+
72+
bool isTruncated = false;
73+
if (content.Length > MaxMessageLength)
74+
{
75+
content = content[..MaxMessageLength];
76+
isTruncated = true;
77+
}
78+
79+
var user = after.Author;
80+
var builder = new EmbedBuilder()
81+
.WithColor(EditedMessageColor)
82+
.WithTimestamp(after.Timestamp)
83+
.WithFooter(footer =>
84+
{
85+
footer
86+
.WithText($"In channel {after.Channel.Name}");
87+
})
88+
.WithAuthor(author =>
89+
{
90+
author
91+
.WithName($"{user.GetPreferredAndUsername()} updated a message");
92+
});
93+
if (isCached)
94+
builder.AddField($"Message Content {(isTruncated ? "(truncated)" : "")}", content);
95+
builder.WithDescription($"Message: [{after.Id}]({after.GetJumpUrl()})");
96+
var embed = builder.Build();
97+
98+
// TimeStamp for the Footer
99+
100+
await _loggingService.LogAction(
101+
$"User {user.GetPreferredAndUsername()} has " +
102+
$"updated the message\n{content}\n in channel #{channel.Name}", true, false);
103+
await _loggingService.LogAction(" ", false, true, embed);
104+
}
50105
}

DiscordBot/Services/UserService.cs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -165,13 +165,13 @@ private async Task UserLeft(SocketGuild guild, SocketUser user)
165165
var timeStayed = DateTime.Now - joinDate;
166166
await _loggingService.LogAction(
167167
$"User Left - After {(timeStayed.Days > 1 ? Math.Floor((double)timeStayed.Days) + " days" : " ")}" +
168-
$" {Math.Floor((double)timeStayed.Hours).ToString(CultureInfo.InvariantCulture)} hours {user.Mention} - `{guildUser.UserNameReference()}` - ID : `{user.Id}`");
168+
$" {Math.Floor((double)timeStayed.Hours).ToString(CultureInfo.InvariantCulture)} hours {user.Mention} - `{guildUser.GetPreferredAndUsername()}` - ID : `{user.Id}`");
169169
}
170170
// If bot is to slow to get user info, we just say they left at current time.
171171
else
172172
{
173173
await _loggingService.LogAction(
174-
$"User `{guildUser.UserNameReference()}` - ID : `{user.Id}` - Left at {DateTime.Now}");
174+
$"User `{guildUser.GetPreferredAndUsername()}` - ID : `{user.Id}` - Left at {DateTime.Now}");
175175
}
176176
}
177177

@@ -336,7 +336,7 @@ public async Task<string> GenerateProfileCard(IUser user)
336336
MaxXpShown = maxXpShown,
337337
Nickname = ((IGuildUser)user).Nickname,
338338
UserId = ulong.Parse(userData.UserID),
339-
Username = user.UserNameReference(),
339+
Username = user.GetPreferredAndUsername(),
340340
XpHigh = xpHigh,
341341
XpLow = xpLow,
342342
XpPercentage = percentage,
@@ -413,14 +413,14 @@ public Embed WelcomeMessage(SocketGuildUser user)
413413
string icon = user.GetAvatarUrl();
414414
icon = string.IsNullOrEmpty(icon) ? "https://cdn.discordapp.com/embed/avatars/0.png" : icon;
415415

416-
string welcomeString = $"Welcome to Unity Developer Community {user.UserNameReferenceForEmbed()}!";
416+
string welcomeString = $"Welcome to Unity Developer Community {user.GetPreferredAndUsername()}!";
417417
var builder = new EmbedBuilder()
418418
.WithDescription(welcomeString)
419419
.WithColor(_welcomeColour)
420420
.WithAuthor(author =>
421421
{
422422
author
423-
.WithName(user.Username)
423+
.WithName(user.Nickname)
424424
.WithIconUrl(icon);
425425
});
426426

@@ -653,7 +653,7 @@ private async Task UserJoined(SocketGuildUser user)
653653
{
654654
await user.AddRoleAsync(socketTextChannel?.Guild.GetRole(_settings.MutedRoleId));
655655
await _loggingService.LogAction(
656-
$"Currently muted user rejoined - {user.Mention} - `{user.UserNameReference()}` - ID : `{user.Id}`");
656+
$"Currently muted user rejoined - {user.Mention} - `{user.GetPreferredAndUsername()}` - ID : `{user.Id}`");
657657
if (socketTextChannel != null)
658658
await socketTextChannel.SendMessageAsync(
659659
$"{user.Mention} tried to rejoin the server to avoid their mute. Mute time increased by 72 hours.");
@@ -663,7 +663,7 @@ await socketTextChannel.SendMessageAsync(
663663
}
664664

665665
await _loggingService.LogAction(
666-
$"User Joined - {user.Mention} - `{user.UserNameReference()}` - ID : `{user.Id}`");
666+
$"User Joined - {user.Mention} - `{user.GetPreferredAndUsername()}` - ID : `{user.Id}`");
667667

668668
// We check if they're already in the welcome list, if they are we don't add them again to avoid double posts
669669
if (_welcomeNoticeUsers.Count == 0 || !_welcomeNoticeUsers.Exists(u => u.id == user.Id))
@@ -768,8 +768,8 @@ private async Task UserUpdated(Cacheable<SocketGuildUser, ulong> oldUserCached,
768768
if (oldUser.Nickname != user.Nickname)
769769
{
770770
await _loggingService.LogAction(
771-
$"User {oldUser.UserNameReference()} changed his " +
772-
$"username to {user.UserNameReference()}");
771+
$"User {oldUser.GetUserPreferredName()} changed his " +
772+
$"username to {user.GetUserPreferredName()}");
773773
}
774774
}
775775

0 commit comments

Comments
 (0)