-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathServerSpecificFeatures.cs
More file actions
325 lines (284 loc) · 15.5 KB
/
ServerSpecificFeatures.cs
File metadata and controls
325 lines (284 loc) · 15.5 KB
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
namespace MechanicalMilkshake;
public partial class ServerSpecificFeatures
{
public partial class EventChecks
{
public static bool ShutBotsAllowed;
public static async Task MessageCreateChecks(MessageCreatedEventArgs e)
{
// ignore dms
if (e.Channel.IsPrivate) return;
#region dev/home server
if (e.Guild.Id == 799644062973427743)
{
#region &caption -> #captions
if (e.Message.Author.Id == 1031968180974927903 &&
(await e.Message.Channel.GetMessagesBeforeAsync(e.Message.Id, 1).ToListAsync())[0].Content
.Contains("caption"))
{
var chan = await Program.Discord.GetChannelAsync(1048242806486999092);
if (e.Message.Flags?.HasFlag(DiscordMessageFlags.IsComponentsV2) ?? false)
{
var mediaGalleryComponent = e.Message.Components.First() as DiscordMediaGalleryComponent;
var mediaUrl = mediaGalleryComponent.Items.First().Media.Url;
await chan.SendMessageAsync($"{mediaUrl} ({e.Message.JumpLink})");
}
else if (string.IsNullOrWhiteSpace(e.Message.Content))
await chan.SendMessageAsync($"{e.Message.Attachments[0].Url} ({e.Message.JumpLink})");
else if (e.Message.Content.Contains("http"))
await chan.SendMessageAsync(e.Message.Content);
}
#endregion &caption -> #captions
}
#endregion dev/home server
#region Patch Tuesday announcements
#if DEBUG
if (e.Guild.Id == 799644062973427743) // my testing server
{
await PatchTuesdayAnnouncementCheck(e, 455432936339144705, 1409289579139305573);
}
#else
if (e.Guild.Id == 438781053675634713) // not my testing server
{
await PatchTuesdayAnnouncementCheck(e, 696333378990899301, 1251028070488477716);
}
#endif
#endregion Patch Tuesday announcements
#region shut
// Redis "shutCooldowns" hash:
// Key user ID
// Value whether user has attempted to use the command during cooldown
// Value is used so that on user's first attempt during cooldown, we can respond to indicate the cooldown;
// but on subsequent attempts we should not respond to avoid ratelimits as that would defeat the purpose of the cooldown
if (e.Guild.Id == 1203128266559328286 || e.Guild.Id == Program.HomeServer.Id)
{
if (e.Message.Content == "shutok" && e.Message.Author.Id == 455432936339144705)
{
await e.Message.RespondAsync("ok");
ShutBotsAllowed = true;
}
if (e.Message.Content == "shutstop" && e.Message.Author.Id == 455432936339144705)
{
await e.Message.RespondAsync("ok");
ShutBotsAllowed = false;
}
if (e.Message.Content is not null && (e.Message.Content.Equals("shut", StringComparison.OrdinalIgnoreCase) || e.Message.Content.Equals("open", StringComparison.OrdinalIgnoreCase)
|| e.Message.Content.Equals("**shut**", StringComparison.OrdinalIgnoreCase) || e.Message.Content.Equals("**open**", StringComparison.OrdinalIgnoreCase)))
{
if (e.Message.Author.IsBot)
if (!ShutBotsAllowed || e.Message.Author.Id == Program.Discord.CurrentApplication.Id || e.Channel.Id != 1285684652543185047) return; // testing uwubot? use 1285760935310655568 for channel id
var userId = e.Message.Author.Id;
var userShutCooldownSerialized = await Program.Db.HashGetAsync("shutCooldowns", userId.ToString());
KeyValuePair<DateTime, bool> userShutCooldown = new();
if (userShutCooldownSerialized.HasValue)
{
try
{
userShutCooldown = JsonConvert.DeserializeObject<KeyValuePair<DateTime, bool>>(userShutCooldownSerialized);
}
catch (Exception ex)
{
Program.Discord.Logger.LogWarning("Failed to read shut cooldown from db for user {user}! {exType}: {exMessage}\n{exStackTrace}", userId, ex.GetType(), ex.Message, ex.StackTrace);
}
var userCooldownTime = userShutCooldown.Key;
if (userCooldownTime > DateTime.Now && !userShutCooldown.Value) // user on cooldown & has not attempted
{
var cooldownRemainingTime = Math.Round((userCooldownTime - DateTime.Now).TotalSeconds);
if (cooldownRemainingTime == 0) cooldownRemainingTime = 1;
await e.Message.RespondAsync($"You're going too fast! Try again in {cooldownRemainingTime} second{(cooldownRemainingTime > 1 ? "s" : "")}.");
userShutCooldown = new(userShutCooldown.Key, true);
}
else if (userCooldownTime < DateTime.Now)
{
userShutCooldown = new KeyValuePair<DateTime, bool>(DateTime.Now.AddSeconds(5), false);
if (e.Message.Content.Equals("shut", StringComparison.OrdinalIgnoreCase)
|| e.Message.Content.Equals("**shut**", StringComparison.OrdinalIgnoreCase))
await e.Message.RespondAsync("open");
else if (e.Message.Content.Equals("open", StringComparison.OrdinalIgnoreCase)
|| e.Message.Content.Equals("**open**", StringComparison.OrdinalIgnoreCase))
await e.Message.RespondAsync("shut");
}
}
else
{
if (e.Message.Content.Equals("shut", StringComparison.OrdinalIgnoreCase)
|| e.Message.Content.Equals("**shut**", StringComparison.OrdinalIgnoreCase))
await e.Message.RespondAsync("open");
else if (e.Message.Content.Equals("open", StringComparison.OrdinalIgnoreCase)
|| e.Message.Content.Equals("**open**", StringComparison.OrdinalIgnoreCase))
await e.Message.RespondAsync("shut");
if (e.Message.Author.Id != 1264728368847523850) // testing uwubot? use 1285760461047861298
userShutCooldown = new(DateTime.Now.AddSeconds(5), false);
}
if (userShutCooldown.Key == DateTime.MinValue && userShutCooldown.Value == false)
await Program.Db.HashSetAsync("shutCooldowns", userId.ToString(), JsonConvert.SerializeObject(userShutCooldown));
}
}
#endregion shut
}
private static async Task PatchTuesdayAnnouncementCheck(MessageCreatedEventArgs e, ulong authorId, ulong channelId)
{
// Patch Tuesday automatic message generation
var insiderRedditUrlPattern = new Regex(@"https:\/\/.*reddit.com\/r\/Windows[0-9]{1,}.*cumulative_updates.*");
// Filter to messages by passed author & channel IDs, and that match the pattern
if (e.Message.Author.Id != authorId || e.Channel.Id != channelId || !insiderRedditUrlPattern.IsMatch(e.Message.Content))
return;
// List of roles to ping with message
var usersToPing = new List<ulong>
{
228574821590499329,
455432936339144705
};
// Get message before current message; if authors do not match or message is not a Cumulative Updates post, ignore
var previousMessage = (await e.Message.Channel.GetMessagesBeforeAsync(e.Message.Id, 1).ToListAsync())[0];
if (previousMessage.Author.Id != e.Message.Author.Id || !insiderRedditUrlPattern.IsMatch(previousMessage.Content))
return;
// Get URLs from both messages
var thisUrl = insiderRedditUrlPattern.Match(e.Message.Content).Value;
var previousUrl = insiderRedditUrlPattern.Match(previousMessage.Content).Value;
// Figure out which URL is Windows 10 and which is Windows 11
var windows10Url = thisUrl.Contains("Windows10") ? thisUrl : previousUrl;
var windows11Url = thisUrl.Contains("Windows11") ? thisUrl : previousUrl;
// Assemble message
var msg = "";
foreach (var user in usersToPing)
msg += $"<@{user}> ";
msg += $"```\nIt's <@&445773142233710594>! Update discussion threads & changelist links are here: {windows10Url} (Windows 10 Extended Security Updates) and {windows11Url} (Windows 11)\n```";
// Send message
await e.Message.Channel.SendMessageAsync(msg);
}
#region regex
[GeneratedRegex("(.*)?<@!?([0-9]+)>(.*)")]
private static partial Regex MentionPattern();
[GeneratedRegex(@"https.*windows-(\d+).*?build[s]?-(?:(\d+(?:-\d+)?)(?:-and-(\d+-\d+)?)*)(?:.+?(?:(canary|dev|beta|release-preview)(?:-and-(canary|dev|beta|release-preview))*)?-channel[s]?.*)?\/")]
private static partial Regex InsiderUrlPattern();
#endregion regex
}
public class Commands
{
public class MessageCommands
{
// Per-server commands go here. Use the [TargetServer(serverId)] attribute to restrict a command to a specific guild.
[Command("poop")]
[Description("immaturity is key")]
[TextAlias("shit", "defecate")]
[CommandChecks.AllowedServers(799644062973427743, 1203128266559328286)]
[AllowedProcessors(typeof(TextCommandProcessor))]
public async Task Poop(CommandContext ctx, [RemainingText] string much = "")
{
if (ctx.Channel.IsPrivate)
{
await ctx.RespondAsync("sorry, no can do.");
return;
}
try
{
DiscordChannel chan;
DiscordMessage msg;
#if DEBUG
chan = await Program.Discord.GetChannelAsync(893654247709741088);
msg = await chan.GetMessageAsync(1282187612844589168);
#else
chan = await Program.Discord.GetChannelAsync(892978015309557870);
msg = much == "MUCH" ? await chan.GetMessageAsync(1294869494648279071) : await chan.GetMessageAsync(1085253151155830895);
#endif
var phrases = msg.Content.Split("\n");
await ctx.Channel.SendMessageAsync(phrases[Program.Random.Next(0, phrases.Length)]
.Replace("{user}", ctx.Member!.DisplayName));
}
catch
{
await ctx.RespondAsync("sorry, no can do.");
}
}
}
public class RoleCommands
{
[Command("rolename")]
[Description("Change the name of someone's role.")]
[AllowedProcessors(typeof(SlashCommandProcessor))]
public static async Task RoleName(SlashCommandContext ctx,
[Parameter("name"), Description("The new name.")] string name,
[Parameter("user"), Description("The user whose role name to change.")] DiscordUser user = default)
{
await ctx.DeferResponseAsync();
if (ctx.Guild.Id != 984903591816990730)
{
await ctx.FollowupAsync(new DiscordFollowupMessageBuilder()
.WithContent("This command is not available in this server."));
return;
}
if (user == default) user = ctx.User;
DiscordMember member;
try
{
member = await ctx.Guild.GetMemberAsync(user.Id);
}
catch
{
await ctx.FollowupAsync(new DiscordFollowupMessageBuilder().WithContent("I couldn't find that user!"));
return;
}
List<DiscordRole> roles = new();
if (member.Roles.Any())
{
roles.AddRange(member.Roles.OrderBy(role => role.Position).Reverse());
}
else
{
var response = ctx.User == user ? "You don't have any roles." : "That user doesn't have any roles.";
await ctx.FollowupAsync(new DiscordFollowupMessageBuilder().WithContent(response));
return;
}
if (roles.Count == 1 && roles.First().Id is 984903591833796659 or 984903591816990739 or 984936907874136094)
{
var response = ctx.User == user
? "You don't have a role that can be renamed!"
: "That user doesn't have a role that can be renamed!";
await ctx.FollowupAsync(new DiscordFollowupMessageBuilder().WithContent(response));
return;
}
var roleToModify = roles.FirstOrDefault(role =>
role.Id is not (984903591833796659 or 984903591816990739 or 984936907874136094));
if (roleToModify == default)
{
var response = ctx.User == user
? "You don't have a role that can be renamed!"
: "That user doesn't have a role that can be renamed!";
await ctx.FollowupAsync(new DiscordFollowupMessageBuilder()
.WithContent(response));
return;
}
try
{
await roleToModify.ModifyAsync(role => role.Name = name);
}
catch (UnauthorizedException)
{
await ctx.FollowupAsync(
new DiscordFollowupMessageBuilder().WithContent("I don't have permission to rename that role!"));
return;
}
var finalResponse = ctx.User == user
? $"Your role has been renamed to **{name}**."
: $"{member.Mention}'s role has been renamed to **{name}**.";
await ctx.FollowupAsync(new DiscordFollowupMessageBuilder().WithContent(finalResponse));
}
}
}
public class CommandChecks
{
public class AllowedServersAttribute(params ulong[] allowedServers) : ContextCheckAttribute
{
public ulong[] AllowedServers { get; } = allowedServers;
}
public class AllowedServersContextCheck : IContextCheck
{
#nullable enable
public ValueTask<string?> ExecuteCheckAsync(AllowedServersAttribute attribute, CommandContext ctx) =>
ValueTask.FromResult(!ctx.Channel.IsPrivate && ctx.Guild is not null && attribute.AllowedServers.Contains(ctx.Guild.Id)
? null
: "This command is not available in this server.");
}
}
}