Skip to content
This repository was archived by the owner on Feb 5, 2024. It is now read-only.

Commit 76dc0a4

Browse files
improve code readability
1 parent 6355121 commit 76dc0a4

File tree

11 files changed

+104
-128
lines changed

11 files changed

+104
-128
lines changed

DSharpPlusDocs.cs

Lines changed: 0 additions & 66 deletions
This file was deleted.

Handlers/CommandHandler.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ public class CommandHandler
4343
private DiscordClient _client;
4444
private MainHandler _mainHandler;
4545
private IServiceProvider _services;
46-
private readonly MemoryCache cache = new(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(3) });
46+
private readonly MemoryCache _cache = new(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(3) });
4747

4848
public Task InitializeAsync(MainHandler mainHandler)
4949
{
@@ -187,9 +187,9 @@ private Task HandleUpdate(DiscordClient client, MessageUpdateEventArgs e)
187187
}
188188
}
189189

190-
public void AddCache(ulong userMessageId, ulong ourMessageId) => cache.Set(userMessageId, ourMessageId, new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10) });
190+
public void AddCache(ulong userMessageId, ulong ourMessageId) => _cache.Set(userMessageId, ourMessageId, new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10) });
191191

192-
public ulong? GetOurMessageIdFromCache(ulong messageId) => cache.TryGetValue(messageId, out ulong id) ? id : null;
192+
public ulong? GetOurMessageIdFromCache(ulong messageId) => _cache.TryGetValue(messageId, out ulong id) ? id : null;
193193

194194
/*public async Task<DiscordEmbed> HelpEmbedBuilderAsync(CommandContext context, string command = null)
195195
{

Modules/Commands.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ public async Task GuidesAsync(CommandContext ctx, [RemainingText] string guide =
8686
string html;
8787
using (HttpClient httpClient = new())
8888
{
89-
HttpResponseMessage res = await httpClient.GetAsync("https://raw.githubusercontent.com/NaamloosDT/DSharpPlus/master/docs/articles/toc.yml");
89+
HttpResponseMessage res = await httpClient.GetAsync("https://raw.githubusercontent.com/DSharpPlus/DSharpPlus/master/docs/articles/toc.yml");
9090
if (!res.IsSuccessStatusCode)
9191
{
9292
throw new Exception($"An error occurred: {res.ReasonPhrase}");
@@ -154,9 +154,9 @@ public async Task GuidesAsync(CommandContext ctx, [RemainingText] string guide =
154154
foreach (string category in guides.Keys)
155155
{
156156
authorName = $"Guide: {category}";
157-
if (guides.ContainsKey(category))
157+
if (guides.TryGetValue(category, out string guide1))
158158
{
159-
authorUrl = guides[category];
159+
authorUrl = guide1;
160160
}
161161

162162
bool add = false;
@@ -225,8 +225,8 @@ public async Task InfoAsync(CommandContext ctx)
225225
eb.AddField(
226226
"Info",
227227
$"- Library: DSharpPlus ({ctx.Client.VersionString})\n" +
228-
$"- Runtime: {RuntimeInformation.FrameworkDescription} {RuntimeInformation.ProcessArchitecture}\n" +
229-
//$"- Source: https://github.com/SubZero0/DiscordNet-Docs\n" +
228+
$"- Runtime: {RuntimeInformation.FrameworkDescription} {RuntimeInformation.ProcessArchitecture}\n" +
229+
//$"- Source: https://github.com/SubZero0/DiscordNet-Docs\n" +
230230
$"- Uptime: {DateTime.Now - Process.GetCurrentProcess().StartTime:dd\\.hh\\:mm\\:ss}",
231231
false);
232232
eb.AddField(

Paginator/PaginationService.cs

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ public async Task<DiscordMessage> SendPaginatedMessageAsync(DiscordChannel chann
6969

7070
if (paginated.Options.Timeout != TimeSpan.Zero)
7171
{
72-
_ = Task.Delay(paginated.Options.Timeout).ContinueWith(async _t =>
72+
_ = Task.Delay(paginated.Options.Timeout).ContinueWith(async _ =>
7373
{
7474
if (!_messages.ContainsKey(message.Id))
7575
{
@@ -120,7 +120,7 @@ public async Task EditMessageToPaginatedMessageAsync(DiscordMessage message, Pag
120120

121121
if (paginated.Options.Timeout != TimeSpan.Zero)
122122
{
123-
_ = Task.Delay(paginated.Options.Timeout).ContinueWith(async _t =>
123+
_ = Task.Delay(paginated.Options.Timeout).ContinueWith(async _ =>
124124
{
125125
if (!_messages.ContainsKey(message.Id))
126126
{
@@ -168,6 +168,7 @@ internal async Task OnReactionAddedAsync(DiscordClient client, MessageReactionAd
168168
_ = message.DeleteReactionAsync(e.Emoji, e.User);
169169
return;
170170
}
171+
171172
if (e.Emoji.Equals(page.Options.EmoteFirst))
172173
{
173174
if (page.CurrentPage != 1)
@@ -212,18 +213,22 @@ internal async Task OnReactionAddedAsync(DiscordClient client, MessageReactionAd
212213
await message.DeleteAllReactionsAsync();
213214
}
214215
}
216+
215217
_ = message.DeleteReactionAsync(e.Emoji, e.User);
216218
}
217219
}
218220
}
219221

220222
public class PaginatedMessage
221223
{
222-
public PaginatedMessage(IEnumerable<string> pages, string title = "", int embedColor = 0, DiscordUser user = null, AppearanceOptions options = null)
224+
public PaginatedMessage(IEnumerable<string> pages, string title = "", int embedColor = 0,
225+
DiscordUser user = null, AppearanceOptions options = null)
223226
: this(pages.Select(x => new Page { Description = x }), title, embedColor, user, options)
224227
{
225228
}
226-
public PaginatedMessage(IEnumerable<Page> pages, string title = "", int embedColor = 0, DiscordUser user = null, AppearanceOptions options = null)
229+
230+
public PaginatedMessage(IEnumerable<Page> pages, string title = "", int embedColor = 0, DiscordUser user = null,
231+
AppearanceOptions options = null)
227232
{
228233
List<DiscordEmbed> embeds = new();
229234
int i = 1;
@@ -249,6 +254,7 @@ public PaginatedMessage(IEnumerable<Page> pages, string title = "", int embedCol
249254

250255
embeds.Add(builder);
251256
}
257+
252258
Pages = embeds;
253259
Title = title;
254260
EmbedColor = embedColor;

Program.cs

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,46 @@
2121
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2222
// SOFTWARE.
2323

24+
using System;
25+
using System.Threading.Tasks;
26+
using DSharpPlus;
27+
using DSharpPlusDocs.Controllers;
28+
using Microsoft.Extensions.Logging;
29+
2430
namespace DSharpPlusDocs
2531
{
26-
public class Program
32+
public class Program : IDisposable
2733
{
28-
public static void Main() => new DSharpPlusDocs().RunAsync().GetAwaiter().GetResult();
34+
private static DiscordClient _client;
35+
private static MainHandler _mainHandler;
36+
37+
public static async Task Main()
38+
{
39+
_client = new DiscordClient(new DiscordConfiguration
40+
{
41+
MinimumLogLevel = LogLevel.Debug,
42+
MessageCacheSize = 1024,
43+
TokenType = TokenType.Bot,
44+
Token = Environment.GetEnvironmentVariable("DISCORD_TOKEN")
45+
});
46+
47+
_client.Ready += (client, eventArgs) =>
48+
{
49+
Console.WriteLine("Connected!");
50+
return Task.CompletedTask;
51+
};
52+
53+
_mainHandler = new MainHandler(_client);
54+
await _mainHandler.InitializeEarlyAsync();
55+
56+
await _client.ConnectAsync();
57+
await Task.Delay(-1);
58+
}
59+
60+
public void Dispose()
61+
{
62+
_client.Dispose();
63+
GC.SuppressFinalize(this);
64+
}
2965
}
3066
}

Query/Cache.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,7 @@ private void LoadInterface(Type _interface, TypeInfoWrapper parent)
276276

277277
foreach (PropertyInfo pi in _interface.GetRuntimeProperties())
278278
{
279-
if (!allTypes[parent].Properties.Contains(pi) && !allTypes[parent].Properties.Any(x => x.Name == pi.Name))
279+
if (!allTypes[parent].Properties.Contains(pi) && allTypes[parent].Properties.All(x => x.Name != pi.Name))
280280
{
281281
allTypes[parent].Properties.Add(pi);
282282
}

Query/Extensions/BaseDisplay.cs

Lines changed: 39 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -114,15 +114,14 @@ private static string GetDocsUrlPath(object o)
114114
{
115115
bool useParent = !IsInherited(o);
116116
Regex rgx = new("\\W+");
117-
return o is TypeInfoWrapper type
118-
? rgx.Replace($"{type.TypeInfo.Namespace}_{type.TypeInfo.Name}", "_")
119-
: o is MethodInfoWrapper method
120-
? rgx.Replace($"{(useParent ? method.Parent.TypeInfo.Namespace : method.Method.DeclaringType.Namespace)}_{(useParent ? method.Parent.TypeInfo.Name : method.Method.DeclaringType.Name)}_{method.Method.Name}", "_")
121-
: o is PropertyInfoWrapper property
122-
? rgx.Replace($"{(useParent ? property.Parent.TypeInfo.Namespace : property.Property.DeclaringType.Namespace)}_{(useParent ? property.Parent.TypeInfo.Name : property.Property.DeclaringType.Name)}_{property.Property.Name}", "_")
123-
: o is EventInfoWrapper eve
124-
? rgx.Replace($"{eve.Parent.TypeInfo.Namespace}_{eve.Parent.TypeInfo.Name}_{eve.Event.Name}".Replace('.', '_'), "_")
125-
: rgx.Replace($"{o.GetType().Namespace}_{o.GetType().Name}".Replace('.', '_'), "_");
117+
return o switch
118+
{
119+
TypeInfoWrapper type => rgx.Replace($"{type.TypeInfo.Namespace}_{type.TypeInfo.Name}", "_"),
120+
MethodInfoWrapper method => rgx.Replace($"{(useParent ? method.Parent.TypeInfo.Namespace : method.Method.DeclaringType.Namespace)}_{(useParent ? method.Parent.TypeInfo.Name : method.Method.DeclaringType.Name)}_{method.Method.Name}", "_"),
121+
PropertyInfoWrapper property => rgx.Replace($"{(useParent ? property.Parent.TypeInfo.Namespace : property.Property.DeclaringType.Namespace)}_{(useParent ? property.Parent.TypeInfo.Name : property.Property.DeclaringType.Name)}_{property.Property.Name}", "_"),
122+
EventInfoWrapper eve => rgx.Replace($"{eve.Parent.TypeInfo.Namespace}_{eve.Parent.TypeInfo.Name}_{eve.Event.Name}".Replace('.', '_'), "_"),
123+
_ => rgx.Replace($"{o.GetType().Namespace}_{o.GetType().Name}".Replace('.', '_'), "_")
124+
};
126125
}
127126

128127
//Generic types will return like Type`1 and the docs change to Type-1
@@ -151,13 +150,13 @@ public static string GetPath(object o, bool withInheritanceMarkup = true)
151150

152151
return $"{type}: {typeWrapper.DisplayName} in {typeWrapper.TypeInfo.Namespace}";
153152
}
154-
return o is MethodInfoWrapper method
155-
? $"Method: {method.Method.Name} in {method.Parent.TypeInfo.Namespace}.{method.Parent.DisplayName}{(global::DSharpPlusDocs.Query.ResultDisplay.IsInherited(method) && withInheritanceMarkup ? " (i)" : "")}"
156-
: o is PropertyInfoWrapper property
157-
? $"Property: {property.Property.Name} in {property.Parent.TypeInfo.Namespace}.{property.Parent.DisplayName}{(global::DSharpPlusDocs.Query.ResultDisplay.IsInherited(property) && withInheritanceMarkup ? " (i)" : "")}"
158-
: o is EventInfoWrapper eve
159-
? $"Event: {eve.Event.Name} in {eve.Parent.TypeInfo.Namespace}.{eve.Parent.DisplayName}"
160-
: o.GetType().ToString();
153+
return o switch
154+
{
155+
MethodInfoWrapper method => $"Method: {method.Method.Name} in {method.Parent.TypeInfo.Namespace}.{method.Parent.DisplayName}{(global::DSharpPlusDocs.Query.ResultDisplay.IsInherited(method) && withInheritanceMarkup ? " (i)" : "")}",
156+
PropertyInfoWrapper property => $"Property: {property.Property.Name} in {property.Parent.TypeInfo.Namespace}.{property.Parent.DisplayName}{(global::DSharpPlusDocs.Query.ResultDisplay.IsInherited(property) && withInheritanceMarkup ? " (i)" : "")}",
157+
EventInfoWrapper eve => $"Event: {eve.Event.Name} in {eve.Parent.TypeInfo.Namespace}.{eve.Parent.DisplayName}",
158+
_ => o.GetType().ToString()
159+
};
161160
}
162161

163162
public static string GetSimplePath(object o)
@@ -176,28 +175,32 @@ public static string GetSimplePath(object o)
176175

177176
return $"{type}:{typeWrapper.DisplayName}";
178177
}
179-
return o is MethodInfoWrapper method
180-
? $"Method:{method.Method.Name}"
181-
: o is PropertyInfoWrapper property
182-
? $"Property:{property.Property.Name}"
183-
: o is EventInfoWrapper eve ? $"Event:{eve.Event.Name}" : o.GetType().ToString();
178+
return o switch
179+
{
180+
MethodInfoWrapper method => $"Method:{method.Method.Name}",
181+
PropertyInfoWrapper property => $"Property:{property.Property.Name}",
182+
EventInfoWrapper eve => $"Event:{eve.Event.Name}",
183+
_ => o.GetType().ToString()
184+
};
184185
}
185186

186-
public static string GetNamespace(object o) => o is TypeInfoWrapper typeWrapper
187-
? typeWrapper.TypeInfo.Namespace
188-
: o is MethodInfoWrapper method
189-
? $"{method.Parent.TypeInfo.Namespace}.{method.Parent.DisplayName}"
190-
: o is PropertyInfoWrapper property
191-
? $"{property.Parent.TypeInfo.Namespace}.{property.Parent.DisplayName}"
192-
: o is EventInfoWrapper eve ? $"{eve.Parent.TypeInfo.Namespace}.{eve.Parent.DisplayName}" : o.GetType().Namespace;
193-
194-
public static string GetParent(object o) => o is TypeInfoWrapper typeWrapper
195-
? typeWrapper.DisplayName
196-
: o is MethodInfoWrapper method
197-
? method.Parent.DisplayName
198-
: o is PropertyInfoWrapper property
199-
? property.Parent.DisplayName
200-
: o is EventInfoWrapper eve ? eve.Parent.DisplayName : o.GetType().Name;
187+
public static string GetNamespace(object o) => o switch
188+
{
189+
TypeInfoWrapper typeWrapper => typeWrapper.TypeInfo.Namespace,
190+
MethodInfoWrapper method => $"{method.Parent.TypeInfo.Namespace}.{method.Parent.DisplayName}",
191+
PropertyInfoWrapper property => $"{property.Parent.TypeInfo.Namespace}.{property.Parent.DisplayName}",
192+
EventInfoWrapper eve => $"{eve.Parent.TypeInfo.Namespace}.{eve.Parent.DisplayName}",
193+
_ => o.GetType().Namespace
194+
};
195+
196+
public static string GetParent(object o) => o switch
197+
{
198+
TypeInfoWrapper typeWrapper => typeWrapper.DisplayName,
199+
MethodInfoWrapper method => method.Parent.DisplayName,
200+
PropertyInfoWrapper property => property.Parent.DisplayName,
201+
EventInfoWrapper eve => eve.Parent.DisplayName,
202+
_ => o.GetType().Name
203+
};
201204

202205
private static string StripTags(string source)
203206
{

Query/Extensions/EventDisplay.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,15 +59,15 @@ private async Task<DiscordEmbedBuilder> ShowEventsAsync(DiscordEmbedBuilder eb,
5959

6060
if (result.Summary != null)
6161
{
62-
eb.AddField("Summary:", result.Summary, false);
62+
eb.AddField("Summary:", result.Summary);
6363
}
6464

6565
if (result.Example != null)
6666
{
67-
eb.AddField("Example:", result.Example, false);
67+
eb.AddField("Example:", result.Example);
6868
}
6969

70-
eb.AddField("Arguments:", BuildEvent(first), false);
70+
eb.AddField("Arguments:", BuildEvent(first));
7171
return eb;
7272
}
7373

Query/Extensions/MethodDisplay.cs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,6 @@ private string MethodToDocs(MethodInfoWrapper mi, bool removeDiscord = false) //
8484

8585
Regex rgx = new("[^a-zA-Z0-9_][^a-zA-Z]*");
8686
string parameters = "";
87-
string parameters_orig = "";
8887
foreach (ParameterInfo pi in mi.Method.GetParameters())
8988
{
9089
string format = rgx.Replace(pi.ParameterType.ToString(), "_").Replace("System_Action", "Action").Replace("System_Collections_Generic_IEnumerable", "IEnumerable");
@@ -94,7 +93,6 @@ private string MethodToDocs(MethodInfoWrapper mi, bool removeDiscord = false) //
9493
}
9594

9695
parameters += $"{format}_";
97-
parameters_orig += $"{pi.ParameterType}_";
9896
}
9997
string final = $"#{mi.Parent.TypeInfo.Namespace.Replace('.', '_')}_{mi.Parent.TypeInfo.Name}_{mi.Method.Name}_{parameters}";
10098
return final.Length > 68 && !removeDiscord ? MethodToDocs(mi, true) : final;
@@ -103,9 +101,8 @@ private string MethodToDocs(MethodInfoWrapper mi, bool removeDiscord = false) //
103101
private static string BuildMethod(MethodInfoWrapper methodWrapper)
104102
{
105103
MethodInfo mi = methodWrapper.Method;
106-
IEnumerable<string> parameters = null;
107104
ParameterInfo[] parametersInfo = mi.GetParameters();
108-
parameters = mi.IsDefined(typeof(ExtensionAttribute)) && parametersInfo.First().ParameterType.IsAssignableFrom(methodWrapper.Parent.TypeInfo.AsType())
105+
IEnumerable<string> parameters = mi.IsDefined(typeof(ExtensionAttribute)) && parametersInfo.First().ParameterType.IsAssignableFrom(methodWrapper.Parent.TypeInfo.AsType())
109106
? parametersInfo.Skip(1).Select(x => $"{BuildPreParameter(x)}{Utils.BuildType(x.ParameterType)} {x.Name}{GetParameterDefaultValue(x)}")
110107
: parametersInfo.Select(x => $"{BuildPreParameter(x)}{Utils.BuildType(x.ParameterType)} {x.Name}{GetParameterDefaultValue(x)}");
111108
return $"{Utils.BuildType(mi.ReturnType)} {mi.Name}({string.Join(", ", parameters)})";

0 commit comments

Comments
 (0)