Skip to content

Commit bf73ca3

Browse files
committed
Updating repo
1 parent a20d696 commit bf73ca3

18 files changed

+211
-101
lines changed

src/DiscordNet/DiscordNet.cs

Lines changed: 61 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,47 +2,94 @@
22
using Discord.Addons.Paginator;
33
using Discord.WebSocket;
44
using DiscordNet.Controllers;
5+
using DiscordNet.Github;
56
using Microsoft.Extensions.DependencyInjection;
67
using System;
8+
using System.Linq;
9+
using System.Text.RegularExpressions;
10+
using System.Threading;
711
using System.Threading.Tasks;
812

913
namespace DiscordNet
1014
{
1115
public class DiscordNet
1216
{
13-
private DiscordSocketClient Discord;
14-
private MainHandler MainHandler;
17+
private DiscordSocketClient _client;
18+
private MainHandler _mainHandler;
19+
20+
private Regex _githubRegex = new Regex("(?<=\\s|^)##(?<number>[0-9]{1,4})(?=\\s|$)", RegexOptions.Compiled | RegexOptions.ECMAScript);
1521

1622
public async Task RunAsync()
1723
{
18-
Discord = new DiscordSocketClient(new DiscordSocketConfig()
24+
_client = new DiscordSocketClient(new DiscordSocketConfig()
1925
{
20-
LogLevel = LogSeverity.Info
26+
LogLevel = LogSeverity.Info,
2127
});
2228

23-
Discord.Log += (message) =>
29+
_client.Log += (message) =>
2430
{
2531
Console.WriteLine(message);
2632
return Task.CompletedTask;
2733
};
28-
Discord.Ready += () =>
34+
35+
_client.Ready += () =>
2936
{
3037
Console.WriteLine("Connected!");
3138
return Task.CompletedTask;
3239
};
3340

41+
_client.Disconnected += (exception) => //Kills the bot if it doesn't reconnect
42+
{
43+
Task.Run(async () =>
44+
{
45+
CancellationTokenSource cts = new CancellationTokenSource();
46+
Func<Task> ctsTask = () =>
47+
{
48+
cts.Cancel();
49+
return Task.CompletedTask;
50+
};
51+
52+
_client.Connected += ctsTask;
53+
await Task.Delay(30000, cts.Token);
54+
if (!cts.IsCancellationRequested)
55+
Environment.Exit(1);
56+
_client.Connected -= ctsTask;
57+
cts.Dispose();
58+
});
59+
return Task.CompletedTask;
60+
};
61+
62+
_client.MessageReceived += (message) =>
63+
{
64+
Task.Run(async () =>
65+
{
66+
if (message is IUserMessage userMessage)
67+
{
68+
if (userMessage.Author.IsBot)
69+
return;
70+
if (userMessage.Channel is ITextChannel tc && tc.GuildId == 81384788765712384 && userMessage.Channel.Name != "dotnet_discord-net" && userMessage.Channel.Name != "testing" && userMessage.Channel.Name != "playground")
71+
return;
72+
MatchCollection matches = _githubRegex.Matches(userMessage.Content);
73+
if (matches.Count > 0)
74+
{
75+
var urls = await GithubRest.GetIssuesUrlsAsync(matches.Take(3).Select(x => x.Groups["number"].Value));
76+
await userMessage.Channel.SendMessageAsync(string.Join("\n", urls));
77+
}
78+
}
79+
});
80+
return Task.CompletedTask;
81+
};
82+
3483
var services = new ServiceCollection();
35-
services.AddSingleton(Discord);
36-
services.AddPaginator(Discord);
84+
services.AddSingleton(_client);
85+
services.AddPaginator(_client);
3786

38-
MainHandler = new MainHandler(Discord, services.BuildServiceProvider());
39-
await MainHandler.InitializeEarlyAsync();
87+
_mainHandler = new MainHandler(_client, services.BuildServiceProvider());
88+
await _mainHandler.InitializeEarlyAsync();
4089

41-
await Discord.LoginAsync(TokenType.Bot, "...");
42-
await Discord.StartAsync();
90+
await _client.LoginAsync(TokenType.Bot, "...");
91+
await _client.StartAsync();
4392
await Task.Delay(-1);
4493
}
4594
}
46-
47-
4895
}

src/DiscordNet/DiscordNet.csproj

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,29 @@
11
<Project Sdk="Microsoft.NET.Sdk">
22

33
<PropertyGroup>
4-
<TargetFramework>netcoreapp1.1</TargetFramework>
4+
<TargetFramework>netcoreapp2.1</TargetFramework>
55
<DebugType>portable</DebugType>
66
<AssemblyName>DiscordNet</AssemblyName>
77
<OutputType>Exe</OutputType>
88
<PackageId>DiscordNet</PackageId>
99
<PackageTargetFallback>$(PackageTargetFallback);dnxcore50</PackageTargetFallback>
10-
<RuntimeFrameworkVersion>1.1.1</RuntimeFrameworkVersion>
10+
<RuntimeFrameworkVersion>2.0.5</RuntimeFrameworkVersion>
1111
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
1212
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
1313
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
1414
</PropertyGroup>
1515

1616
<ItemGroup>
17-
<PackageReference Include="Discord.Addons.Paginator" Version="1.0.23-dev" />
18-
<PackageReference Include="Discord.Net.Commands" Version="2.0.0-alpha-build-00823" />
19-
<PackageReference Include="Discord.Net.Core" Version="2.0.0-alpha-build-00823" />
20-
<PackageReference Include="Discord.Net.Rest" Version="2.0.0-alpha-build-00823" />
21-
<PackageReference Include="Discord.Net.Rpc" Version="2.0.0-alpha-build-00823" />
22-
<PackageReference Include="Discord.Net.Webhook" Version="2.0.0-alpha-build-00823" />
23-
<PackageReference Include="Discord.Net.WebSocket" Version="2.0.0-alpha-build-00823" />
24-
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="2.1.0-beta1-61220-03" />
25-
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="2.1.0-beta1-61220-03" />
26-
<PackageReference Include="Microsoft.CodeAnalysis.Scripting.Common" Version="2.1.0-beta1-61220-03" />
27-
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="1.1.1" />
17+
<PackageReference Include="Discord.Addons.Paginator" Version="1.0.27-dev" />
18+
<PackageReference Include="Discord.Net.Commands" Version="2.0.1" />
19+
<PackageReference Include="Discord.Net.Core" Version="2.0.1" />
20+
<PackageReference Include="Discord.Net.Rest" Version="2.0.1" />
21+
<PackageReference Include="Discord.Net.Webhook" Version="2.0.1" />
22+
<PackageReference Include="Discord.Net.WebSocket" Version="2.0.1" />
23+
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="2.6.1" />
24+
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="2.6.1" />
25+
<PackageReference Include="Microsoft.CodeAnalysis.Scripting.Common" Version="2.6.1" />
26+
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="2.0.0" />
2827
</ItemGroup>
2928

3029
</Project>

src/DiscordNet/Handlers/CommandHandler.cs

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
using DiscordNet.EmbedExtension;
77
using DiscordNet.Modules.Addons;
88
using Microsoft.Extensions.Caching.Memory;
9+
using Microsoft.Extensions.DependencyInjection;
910
using System;
1011
using System.Linq;
1112
using System.Reflection;
@@ -16,7 +17,7 @@ namespace DiscordNet.Handlers
1617
{
1718
public class CommandHandler
1819
{
19-
private CommandService _commands;
20+
private CommandService _commandService;
2021
private DiscordSocketClient _client;
2122
private IServiceProvider _services;
2223
private MainHandler _mainHandler;
@@ -25,12 +26,12 @@ public class CommandHandler
2526
public async Task InitializeAsync(MainHandler MainHandler, IServiceProvider services)
2627
{
2728
_mainHandler = MainHandler;
28-
_client = (DiscordSocketClient)services.GetService(typeof(DiscordSocketClient));
29-
_commands = new CommandService();
29+
_client = services.GetService<DiscordSocketClient>();
30+
_commandService = new CommandService();
3031
_services = services;
3132

32-
await _commands.AddModulesAsync(Assembly.GetEntryAssembly());
33-
_commands.Log += Log;
33+
await _commandService.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
34+
_commandService.Log += Log;
3435

3536
_client.MessageReceived += HandleCommand;
3637
_client.MessageUpdated += HandleUpdate;
@@ -66,7 +67,7 @@ private Task HandleUpdate(Cacheable<IMessage, ulong> before, SocketMessage after
6667

6768
if (reply.Item1 == null && reply.Item2 == null && reply.Item3 == null)
6869
return;
69-
var pagination = (PaginationService)_services.GetService(typeof(PaginationService));
70+
var pagination = _services.GetService<PaginationService>();
7071
var isPaginatedMessage = pagination.IsPaginatedMessage(id.Value);
7172
if (reply.Item3 != null)
7273
{
@@ -109,7 +110,7 @@ public async Task HandleCommandAsync(SocketUserMessage msg, int argPos)
109110
return;
110111
IUserMessage message;
111112
if (reply.Item3 != null)
112-
message = await ((PaginationService)_services.GetService(typeof(PaginationService))).SendPaginatedMessageAsync(msg.Channel, reply.Item3);
113+
message = await (_services.GetService<PaginationService>()).SendPaginatedMessageAsync(msg.Channel, reply.Item3);
113114
else
114115
message = await msg.Channel.SendMessageAsync(reply.Item1, embed: reply.Item2?.Build());
115116
AddCache(msg.Id, message.Id);
@@ -118,7 +119,7 @@ public async Task HandleCommandAsync(SocketUserMessage msg, int argPos)
118119
private async Task<(string, EmbedBuilder, PaginatedMessage)> BuildReply(IUserMessage msg, string message)
119120
{
120121
var context = new MyCommandContext(_client, _mainHandler, msg);
121-
var result = await _commands.ExecuteAsync(context, message, _services);
122+
var result = await _commandService.ExecuteAsync(context, message, _services);
122123
if (!result.IsSuccess && result.Error != CommandError.UnknownCommand)
123124
return (result.ErrorReason, null, null);
124125
else if (!result.IsSuccess)
@@ -169,13 +170,13 @@ public async Task<EmbedBuilder> HelpEmbedBuilderAsync(ICommandContext context, s
169170
StringBuilder sb = new StringBuilder();
170171
if (command == null)
171172
{
172-
foreach (ModuleInfo mi in _commands.Modules.OrderBy(x => x.Name))
173+
foreach (ModuleInfo mi in _commandService.Modules.OrderBy(x => x.Name))
173174
if (!mi.IsSubmodule)
174175
if (mi.Name != "Help")
175176
{
176177
bool ok = true;
177178
foreach (PreconditionAttribute precondition in mi.Preconditions)
178-
if (!(await precondition.CheckPermissions(context, null, _services)).IsSuccess)
179+
if (!(await precondition.CheckPermissionsAsync(context, null, _services)).IsSuccess)
179180
{
180181
ok = false;
181182
break;
@@ -188,7 +189,7 @@ public async Task<EmbedBuilder> HelpEmbedBuilderAsync(ICommandContext context, s
188189
{
189190
object o = cmds[i];
190191
foreach (PreconditionAttribute precondition in ((o as CommandInfo)?.Preconditions ?? (o as ModuleInfo)?.Preconditions))
191-
if (!(await precondition.CheckPermissions(context, o as CommandInfo, _services)).IsSuccess)
192+
if (!(await precondition.CheckPermissionsAsync(context, o as CommandInfo, _services)).IsSuccess)
192193
cmds.Remove(o);
193194
}
194195
if (cmds.Count != 0)
@@ -226,7 +227,7 @@ public async Task<EmbedBuilder> HelpEmbedBuilderAsync(ICommandContext context, s
226227
}
227228
else
228229
{
229-
SearchResult sr = _commands.Search(context, command);
230+
SearchResult sr = _commandService.Search(context, command);
230231
if (sr.IsSuccess)
231232
{
232233
Nullable<CommandMatch> cmd = null;

src/DiscordNet/Handlers/DocsUrlHandler.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,11 @@ namespace DiscordNet.Handlers
44
{
55
public class DocsUrlHandler
66
{
7-
public static string DocsBaseUrl { get; set; } = "https://discord.foxbot.me/docs/";
7+
public static string DocsBaseUrl { get; set; } = "https://discord.foxbot.me/latest/";
88

99
private string[] _docsUrls =
1010
{
11-
"https://discord.foxbot.me/docs/",
11+
"https://discord.foxbot.me/latest/",
1212
"http://discord.devpaulo.com.br/"
1313
};
1414

src/DiscordNet/Modules/Commands.cs

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
using System;
1111
using System.Collections.Generic;
1212
using System.Diagnostics;
13+
using System.IO;
1314
using System.Linq;
1415
using System.Net.Http;
1516
using System.Reflection;
@@ -30,7 +31,7 @@ public async Task Clean(int messages = 30)
3031
messages = 50;
3132
else if (messages < 2)
3233
messages = 2;
33-
var msgs = await Context.Channel.GetMessagesAsync(messages).Flatten();
34+
var msgs = await Context.Channel.GetMessagesAsync(messages).FlattenAsync();
3435
msgs = msgs.Where(x => x.Author.Id == Context.Client.CurrentUser.Id);
3536
foreach (IMessage msg in msgs)
3637
await msg.DeleteAsync();
@@ -223,6 +224,33 @@ public async Task SetDocsUrl([Remainder] string url)
223224
DocsUrlHandler.DocsBaseUrl = url;
224225
await ReplyAsync($"Changed base docs url to: <{url}>");
225226
}
227+
228+
[Command("botavatar")]
229+
[RequireOwner]
230+
public async Task Avatar(string url)
231+
{
232+
MemoryStream imgStream = null;
233+
try
234+
{
235+
using (var http = new HttpClient())
236+
{
237+
using (var sr = await http.GetStreamAsync(url))
238+
{
239+
imgStream = new MemoryStream();
240+
await sr.CopyToAsync(imgStream);
241+
imgStream.Position = 0;
242+
}
243+
}
244+
}
245+
catch (Exception)
246+
{
247+
await ReplyAsync("Something went wrong while downloading the image.");
248+
return;
249+
}
250+
await Context.Client.CurrentUser.ModifyAsync(x => x.Avatar = new Image(imgStream));
251+
await ReplyAsync("Avatar changed!");
252+
imgStream.Dispose();
253+
}
226254
}
227255

228256
[Name("Help")]

src/DiscordNet/Query/Cache.cs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
using DiscordNet.Query.Wrappers;
1+
using Discord.Webhook;
2+
using DiscordNet.Query.Wrappers;
23
using System;
34
using System.Collections.Concurrent;
45
using System.Collections.Generic;
@@ -144,9 +145,14 @@ private bool SearchFunction(string searchString, string objectName)
144145
return true;
145146
}
146147

148+
private void ForceReference()
149+
{
150+
new DiscordWebhookClient(null);
151+
}
152+
147153
private void Populate()
148154
{
149-
foreach (var a in Assembly.GetEntryAssembly().GetReferencedAssemblies())
155+
foreach (var a in Assembly.GetExecutingAssembly().GetReferencedAssemblies())
150156
if (a.Name.StartsWith("Discord") && !a.Name.StartsWith("Discord.Addons"))
151157
foreach (Type type in Assembly.Load(a).GetExportedTypes())
152158
LoadType(type);

src/DiscordNet/Query/Extensions/BaseDisplay.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using DiscordNet.Handlers;
22
using DiscordNet.Query.Results;
33
using DiscordNet.Query.Wrappers;
4+
using System;
45
using System.Collections.Generic;
56
using System.Linq;
67
using System.Net;
@@ -55,7 +56,7 @@ private async Task<DocsHttpResult> GetWebDocsAsync(string url, object o)
5556
url = $"{DocsUrlHandler.DocsBaseUrl}api/{SanitizeDocsUrl($"{pi.Property.DeclaringType.Namespace}.{pi.Property.DeclaringType.Name}")}.html";
5657
}
5758
}
58-
using (var httpClient = new HttpClient())
59+
using (var httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(5) })
5960
{
6061
var res = await httpClient.GetAsync(url);
6162
if (!res.IsSuccessStatusCode)

src/DiscordNet/Query/Extensions/TypeDisplay.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ private async Task<EmbedBuilder> ShowTypesAsync(EmbedBuilder eb, EmbedAuthorBuil
2424
}
2525
catch (Exception e)
2626
{
27-
Console.WriteLine(e.ToString());
27+
Console.WriteLine(e);
2828
result = new DocsHttpResult($"{DocsUrlHandler.DocsBaseUrl}api/{pageUrl}.html");
2929
}
3030
eab.Name = $"{(first.TypeInfo.IsInterface ? "Interface" : (first.TypeInfo.IsEnum ? "Enum" : "Type"))}: {first.TypeInfo.Namespace}.{first.DisplayName}";

0 commit comments

Comments
 (0)