-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDiscordNet.cs
101 lines (88 loc) · 3.73 KB
/
DiscordNet.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
using Discord;
using Discord.WebSocket;
using DiscordNet.Github;
using Microsoft.Extensions.DependencyInjection;
using Paginator;
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace DiscordNet
{
public class DiscordNet
{
private DiscordSocketClient _client;
private MainController _mainController;
private Regex _githubRegex = new Regex("(?<=\\s|^)##(?<number>[0-9]{1,4})(?=\\s|$)", RegexOptions.Compiled | RegexOptions.ECMAScript);
public async Task RunAsync()
{
string discordToken = await File.ReadAllTextAsync("Tokens/Discord.txt");
string githubToken = await File.ReadAllTextAsync("Tokens/Github.txt");
var githubRest = new GithubRest(githubToken);
_client = new DiscordSocketClient(new DiscordSocketConfig()
{
LogLevel = LogSeverity.Info,
});
_client.Log += (message) =>
{
Console.WriteLine(message);
return Task.CompletedTask;
};
_client.Ready += () =>
{
Console.WriteLine("Connected!");
return Task.CompletedTask;
};
_client.Disconnected += (exception) => //Kills the bot if it doesn't reconnect
{
Task.Run(async () =>
{
CancellationTokenSource cts = new CancellationTokenSource();
Task ctsTask()
{
cts.Cancel();
return Task.CompletedTask;
}
_client.Connected += ctsTask;
try { await Task.Delay(30000, cts.Token); } catch { }
if (!cts.IsCancellationRequested)
Environment.Exit(1);
_client.Connected -= ctsTask;
cts.Dispose();
});
return Task.CompletedTask;
};
_client.MessageReceived += (message) =>
{
Task.Run(async () =>
{
if (message is IUserMessage userMessage)
{
if (userMessage.Author.IsBot)
return;
if (userMessage.Channel is ITextChannel tc && tc.GuildId == 81384788765712384 && userMessage.Channel.Name != "dotnet_discord-net" && userMessage.Channel.Name != "testing" && userMessage.Channel.Name != "playground")
return;
MatchCollection matches = _githubRegex.Matches(userMessage.Content);
if (matches.Count > 0)
{
var urls = await githubRest.GetIssuesUrlsAsync(matches.Take(3).Select(x => x.Groups["number"].Value));
await userMessage.Channel.SendMessageAsync(string.Join("\n", urls));
}
}
});
return Task.CompletedTask;
};
var services = new ServiceCollection();
services.AddSingleton(_client);
services.AddSingleton(new PaginatorService(_client));
services.AddSingleton(githubRest);
_mainController = new MainController(_client, services.BuildServiceProvider());
await _mainController.InitializeEarlyAsync();
await _client.LoginAsync(TokenType.Bot, discordToken);
await _client.StartAsync();
await Task.Delay(-1);
}
}
}