-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathDiscordChatClient.cs
More file actions
230 lines (195 loc) · 7.7 KB
/
Copy pathDiscordChatClient.cs
File metadata and controls
230 lines (195 loc) · 7.7 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DevChatter.Bot.Core.Data.Model;
using DevChatter.Bot.Core.Events.Args;
using DevChatter.Bot.Core.Systems.Chat;
using DevChatter.Bot.Core.Util;
using DevChatter.Bot.Infra.Discord.Extensions;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
namespace DevChatter.Bot.Infra.Discord
{
public class DiscordChatClient : IChatClient
{
private readonly DiscordClientSettings _settings;
private readonly DiscordSocketClient _discordClient;
private TaskCompletionSource<bool> _connectionCompletionTask = new TaskCompletionSource<bool>();
private TaskCompletionSource<bool> _disconnectionCompletionTask = new TaskCompletionSource<bool>();
private SocketGuild _guild;
private readonly List<ulong> _guildChannels = new List<ulong>();
private ISocketMessageChannel _textChannel;
private bool _isReady;
public DiscordChatClient(DiscordClientSettings settings)
{
_settings = settings;
_discordClient = new DiscordSocketClient();
_discordClient.MessageReceived += DiscordClientMessageReceived;
_discordClient.GuildAvailable += DiscordClientGuildAvailable;
_discordClient.GuildUnavailable += DiscordClientGuildUnavailable;
_discordClient.ChannelCreated += DiscordClientChannelCreated;
_discordClient.ChannelDestroyed += DiscordClientChannelDestroyed;
_discordClient.UserJoined += DiscordClientUserJoined;
_discordClient.UserLeft += DiscordClientUserLeft;
}
private async Task DiscordClientGuildAvailable(SocketGuild guild)
{
_guild = guild;
_guildChannels.AddRange(_guild.Channels.Select(channel => channel.Id));
_textChannel = _guild.Channels.FirstOrDefault(channel => channel.Id == _settings.DiscordTextChannelId) as ISocketMessageChannel;
_isReady = true;
}
private async Task DiscordClientGuildUnavailable(SocketGuild guild)
{
_guild = null;
_guildChannels.Clear();
_isReady = false;
}
private async Task DiscordClientChannelCreated(SocketChannel newChannel)
{
_guildChannels.Add(newChannel.Id);
}
private async Task DiscordClientChannelDestroyed(SocketChannel oldChannel)
{
_guildChannels.Remove(oldChannel.Id);
}
private async Task DiscordClientMessageReceived(SocketMessage arg)
{
var message = arg as SocketUserMessage;
if (message == null)
{
return;
}
int commandStartIndex = 0;
if (message.HasCharPrefix(_settings.CommandPrefix, ref commandStartIndex))
{
if (_guildChannels.Contains(message.Channel.Id))
{
if (arg.Author is IGuildUser guildUser)
{
GuildCommandReceived(guildUser, commandStartIndex, arg.Content);
}
}
else
{
DirectCommandReceieved(arg.Author, commandStartIndex, arg.Content);
}
}
}
private void GuildCommandReceived(IGuildUser user, int commandStartIndex, string message)
{
var commandInfo = CommandParser.Parse(message, commandStartIndex);
if(string.IsNullOrWhiteSpace(commandInfo.commandWord))
{
return;
}
RaiseOnCommandReceived(user, commandInfo.commandWord, commandInfo.arguments);
}
private void DirectCommandReceieved(IUser user, int commandStartIndex, string message)
{
var commandInfo = CommandParser.Parse(message, commandStartIndex);
if(string.IsNullOrWhiteSpace(commandInfo.commandWord))
{
return;
}
// TODO: Do we want to handle direct message commands?
}
public async Task Connect()
{
_discordClient.Connected += DiscordClientConnected;
await _discordClient.LoginAsync(TokenType.Bot, _settings.DiscordToken).ConfigureAwait(false);
await _discordClient.StartAsync().ConfigureAwait(false);
await _connectionCompletionTask.Task;
}
private async Task DiscordClientConnected()
{
_discordClient.Connected -= DiscordClientConnected;
_connectionCompletionTask?.SetResult(true);
_disconnectionCompletionTask = new TaskCompletionSource<bool>();
}
public async Task Disconnect()
{
_discordClient.Disconnected += DiscordClientDisconnected;
await _discordClient.LogoutAsync().ConfigureAwait(false);
await _discordClient.StopAsync().ConfigureAwait(false);
await _disconnectionCompletionTask.Task;
}
private async Task DiscordClientDisconnected(Exception arg)
{
_discordClient.Disconnected -= DiscordClientDisconnected;
_disconnectionCompletionTask.SetResult(true);
_connectionCompletionTask = new TaskCompletionSource<bool>();
}
private async Task DiscordClientUserJoined(SocketGuildUser arg)
{
RaiseOnUserNoticed(arg);
}
private async Task DiscordClientUserLeft(SocketGuildUser arg)
{
RaiseOnUserLeft(arg);
}
/// <summary>
/// If not connected to a guild
/// </summary>
public IList<ChatUser> GetAllChatters()
{
if (!_isReady)
{
return new List<ChatUser>();
}
var chatUsers = _guild.Users.Select(user => user.ToChatUser(_settings)).ToList();
return chatUsers;
}
public void SendMessage(string message)
{
if (!_isReady)
{
return;
}
_textChannel?.SendMessageAsync($"`{message}`").Wait();
}
public void SendDirectMessage(string username, string message)
{
if (!_isReady)
{
return;
}
var discordUser = _guild.Users.FirstOrDefault(u => u.Username == username);
discordUser?.SendMessageAsync(message);
}
private void RaiseOnCommandReceived(IGuildUser user, string commandWord, List<string> arguments)
{
var eventArgs = new CommandReceivedEventArgs
{
CommandWord = commandWord,
Arguments = arguments ?? new List<string>(),
ChatUser = user.ToChatUser(_settings)
};
OnCommandReceived?.Invoke(this, eventArgs);
}
private void RaiseOnUserNoticed(SocketGuildUser user)
{
var eventArgs = new UserStatusEventArgs
{
DisplayName = user.Username,
Role = user.ToUserRole(_settings)
};
OnUserNoticed?.Invoke(this, eventArgs);
}
private void RaiseOnUserLeft(SocketGuildUser user)
{
var eventArgs = new UserStatusEventArgs
{
DisplayName = user.Username,
Role = user.ToUserRole(_settings)
};
OnUserLeft?.Invoke(this, eventArgs);
}
public event EventHandler<CommandReceivedEventArgs> OnCommandReceived;
public event EventHandler<NewSubscriberEventArgs> OnNewSubscriber;
public event EventHandler<UserStatusEventArgs> OnUserNoticed;
public event EventHandler<UserStatusEventArgs> OnUserLeft;
}
}