-
-
Notifications
You must be signed in to change notification settings - Fork 299
/
Utilities.cs
348 lines (295 loc) · 12.5 KB
/
Utilities.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
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using DSharpPlus.Entities;
using DSharpPlus.Net;
using Microsoft.Extensions.Logging;
namespace DSharpPlus;
/// <summary>
/// Various Discord-related utilities.
/// </summary>
public static partial class Utilities
{
/// <summary>
/// Gets the version of the library
/// </summary>
private static string VersionHeader { get; set; }
private static Dictionary<DiscordPermissions, string> PermissionStrings { get; set; }
internal static UTF8Encoding UTF8 { get; } = new UTF8Encoding(false);
static Utilities()
{
PermissionStrings = [];
Type t = typeof(DiscordPermissions);
TypeInfo ti = t.GetTypeInfo();
IEnumerable<DiscordPermissions> vals = Enum.GetValues(t).Cast<DiscordPermissions>();
foreach (DiscordPermissions xv in vals)
{
string xsv = xv.ToString();
MemberInfo? xmv = ti.DeclaredMembers.FirstOrDefault(xm => xm.Name == xsv);
PermissionStringAttribute? xav = xmv.GetCustomAttribute<PermissionStringAttribute>();
PermissionStrings[xv] = xav.String;
}
Assembly a = typeof(DiscordClient).GetTypeInfo().Assembly;
string vs = "";
AssemblyInformationalVersionAttribute? iv = a.GetCustomAttribute<AssemblyInformationalVersionAttribute>();
if (iv != null)
{
vs = iv.InformationalVersion;
}
else
{
Version? v = a.GetName().Version;
vs = v.ToString(3);
}
VersionHeader = $"DiscordBot (https://github.com/DSharpPlus/DSharpPlus, v{vs})";
}
internal static string GetApiBaseUri()
=> Endpoints.BASE_URI;
internal static Uri GetApiUriFor(string path)
=> new($"{GetApiBaseUri()}{path}");
internal static Uri GetApiUriFor(string path, string queryString)
=> new($"{GetApiBaseUri()}{path}{queryString}");
internal static QueryUriBuilder GetApiUriBuilderFor(string path)
=> new($"{GetApiBaseUri()}{path}");
internal static string GetFormattedToken(BaseDiscordClient client) => GetFormattedToken(client.Configuration);
internal static string GetFormattedToken(DiscordConfiguration config)
{
return config.TokenType switch
{
TokenType.Bearer => $"Bearer {config.Token}",
TokenType.Bot => $"Bot {config.Token}",
_ => throw new ArgumentException("Invalid token type specified.", nameof(config)),
};
}
internal static string GetUserAgent()
=> VersionHeader;
internal static bool ContainsUserMentions(string message)
{
Regex regex = UserMentionRegex();
return regex.IsMatch(message);
}
internal static bool ContainsNicknameMentions(string message)
{
Regex regex = NicknameMentionRegex();
return regex.IsMatch(message);
}
internal static bool ContainsChannelMentions(string message)
{
Regex regex = ChannelMentionRegex();
return regex.IsMatch(message);
}
internal static bool ContainsRoleMentions(string message)
{
Regex regex = RoleMentionRegex();
return regex.IsMatch(message);
}
internal static bool ContainsEmojis(string message)
{
Regex regex = EmojiMentionRegex();
return regex.IsMatch(message);
}
internal static IEnumerable<ulong> GetUserMentions(DiscordMessage message)
{
Regex regex = UserMentionRegex();
MatchCollection matches = regex.Matches(message.Content);
foreach (Match match in matches.Cast<Match>())
{
yield return ulong.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
}
}
internal static IEnumerable<ulong> GetRoleMentions(DiscordMessage message)
{
Regex regex = RoleMentionRegex();
MatchCollection matches = regex.Matches(message.Content);
foreach (Match match in matches.Cast<Match>())
{
yield return ulong.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
}
}
internal static IEnumerable<ulong> GetChannelMentions(DiscordMessage message)
{
Regex regex = ChannelMentionRegex();
MatchCollection matches = regex.Matches(message.Content);
foreach (Match match in matches.Cast<Match>())
{
yield return ulong.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
}
}
internal static IEnumerable<ulong> GetEmojis(DiscordMessage message)
{
Regex regex = EmojiMentionRegex();
MatchCollection matches = regex.Matches(message.Content);
foreach (Match match in matches.Cast<Match>())
{
yield return ulong.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture);
}
}
internal static bool IsValidSlashCommandName(string name)
{
Regex regex = SlashCommandNameRegex();
return regex.IsMatch(name);
}
internal static bool HasMessageIntents(DiscordIntents intents)
=> (intents.HasIntent(DiscordIntents.GuildMessages) && intents.HasIntent(DiscordIntents.MessageContents)) || intents.HasIntent(DiscordIntents.DirectMessages);
internal static bool HasReactionIntents(DiscordIntents intents)
=> intents.HasIntent(DiscordIntents.GuildMessageReactions) || intents.HasIntent(DiscordIntents.DirectMessageReactions);
internal static bool HasTypingIntents(DiscordIntents intents)
=> intents.HasIntent(DiscordIntents.GuildMessageTyping) || intents.HasIntent(DiscordIntents.DirectMessageTyping);
internal static bool IsTextableChannel(DiscordChannel channel)
=> channel.Type switch
{
DiscordChannelType.Text => true,
DiscordChannelType.Voice => true,
DiscordChannelType.Group => true,
DiscordChannelType.Private => true,
DiscordChannelType.PublicThread => true,
DiscordChannelType.PrivateThread => true,
DiscordChannelType.NewsThread => true,
DiscordChannelType.News => true,
DiscordChannelType.Stage => true,
_ => false,
};
// https://discord.com/developers/docs/topics/gateway#sharding-sharding-formula
/// <summary>
/// Gets a shard id from a guild id and total shard count.
/// </summary>
/// <param name="guildId">The guild id the shard is on.</param>
/// <param name="shardCount">The total amount of shards.</param>
/// <returns>The shard id.</returns>
public static int GetShardId(ulong guildId, int shardCount)
=> (int)((guildId >> 22) % (ulong)shardCount);
/// <summary>
/// Helper method to create a <see cref="DateTimeOffset"/> from Unix time seconds for targets that do not support this natively.
/// </summary>
/// <param name="unixTime">Unix time seconds to convert.</param>
/// <param name="shouldThrow">Whether the method should throw on failure. Defaults to true.</param>
/// <returns>Calculated <see cref="DateTimeOffset"/>.</returns>
public static DateTimeOffset GetDateTimeOffset(long unixTime, bool shouldThrow = true)
{
try
{
return DateTimeOffset.FromUnixTimeSeconds(unixTime);
}
catch (Exception)
{
if (shouldThrow)
{
throw;
}
return DateTimeOffset.MinValue;
}
}
/// <summary>
/// Helper method to create a <see cref="DateTimeOffset"/> from Unix time milliseconds for targets that do not support this natively.
/// </summary>
/// <param name="unixTime">Unix time milliseconds to convert.</param>
/// <param name="shouldThrow">Whether the method should throw on failure. Defaults to true.</param>
/// <returns>Calculated <see cref="DateTimeOffset"/>.</returns>
public static DateTimeOffset GetDateTimeOffsetFromMilliseconds(long unixTime, bool shouldThrow = true)
{
try
{
return DateTimeOffset.FromUnixTimeMilliseconds(unixTime);
}
catch (Exception)
{
if (shouldThrow)
{
throw;
}
return DateTimeOffset.MinValue;
}
}
/// <summary>
/// Helper method to calculate Unix time seconds from a <see cref="DateTimeOffset"/> for targets that do not support this natively.
/// </summary>
/// <param name="dto"><see cref="DateTimeOffset"/> to calculate Unix time for.</param>
/// <returns>Calculated Unix time.</returns>
public static long GetUnixTime(DateTimeOffset dto)
=> dto.ToUnixTimeMilliseconds();
/// <summary>
/// Computes a timestamp from a given snowflake.
/// </summary>
/// <param name="snowflake">Snowflake to compute a timestamp from.</param>
/// <returns>Computed timestamp.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static DateTimeOffset GetSnowflakeTime(this ulong snowflake)
=> DiscordClient.discordEpoch.AddMilliseconds(snowflake >> 22);
/// <summary>
/// Converts this <see cref="DiscordPermissions"/> into human-readable format.
/// </summary>
/// <param name="perm">Permissions enumeration to convert.</param>
/// <returns>Human-readable permissions.</returns>
public static string ToPermissionString(this DiscordPermissions perm)
{
if (perm == DiscordPermissions.None)
{
return PermissionStrings[perm];
}
perm &= PermissionMethods.FULL_PERMS;
IEnumerable<string> strs = PermissionStrings
.Where(xkvp => xkvp.Key != DiscordPermissions.None && (perm & xkvp.Key) == xkvp.Key)
.Select(xkvp => xkvp.Value);
return string.Join(", ", strs.OrderBy(xs => xs));
}
/// <summary>
/// Checks whether this string contains given characters.
/// </summary>
/// <param name="str">String to check.</param>
/// <param name="characters">Characters to check for.</param>
/// <returns>Whether the string contained these characters.</returns>
public static bool Contains(this string str, params char[] characters)
{
foreach (char xc in str)
{
if (characters.Contains(xc))
{
return true;
}
}
return false;
}
internal static void LogTaskFault(this Task task, ILogger logger, LogLevel level, EventId eventId, string message)
{
ArgumentNullException.ThrowIfNull(task);
if (logger == null)
{
return;
}
task.ContinueWith(t => logger.Log(level, eventId, t.Exception, "{Message}", message), TaskContinuationOptions.OnlyOnFaulted);
}
internal static void Deconstruct<TKey, TValue>(this KeyValuePair<TKey, TValue> kvp, out TKey key, out TValue value)
{
key = kvp.Key;
value = kvp.Value;
}
/// <summary>
/// Creates a snowflake from a given <see cref="DateTimeOffset"/>. This can be used to provide "timestamps" for methods
/// like <see cref="DiscordChannel.GetMessagesAfterAsync"/>.
/// </summary>
/// <param name="dateTimeOffset">DateTimeOffset to create a snowflake from.</param>
/// <returns>Returns a snowflake representing the given date and time.</returns>
public static ulong CreateSnowflake(DateTimeOffset dateTimeOffset)
{
long diff = dateTimeOffset.ToUnixTimeMilliseconds() - DiscordClient.discordEpoch.ToUnixTimeMilliseconds();
return (ulong)diff << 22;
}
[GeneratedRegex("<@(\\d+)>", RegexOptions.ECMAScript)]
private static partial Regex UserMentionRegex();
[GeneratedRegex("<@!(\\d+)>", RegexOptions.ECMAScript)]
private static partial Regex NicknameMentionRegex();
[GeneratedRegex("<#(\\d+)>", RegexOptions.ECMAScript)]
private static partial Regex ChannelMentionRegex();
[GeneratedRegex("<@&(\\d+)>", RegexOptions.ECMAScript)]
private static partial Regex RoleMentionRegex();
[GeneratedRegex("<a?:(.*):(\\d+)>", RegexOptions.ECMAScript)]
private static partial Regex EmojiMentionRegex();
[GeneratedRegex("^[\\w-]{1,32}$")]
private static partial Regex SlashCommandNameRegex();
}