-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathJoinRolesInteractions.cs
87 lines (69 loc) · 2.73 KB
/
JoinRolesInteractions.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
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using DSharpPlus;
using DSharpPlus.Entities;
using DSharpPlus.EventArgs;
using Newtonsoft.Json;
namespace RoboBot
{
public class JoinRolesInteractions
{
private readonly string JoinRolesLocalPath =
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "join-roles.json");
private DiscordClient _client;
public List<JoinRoles> JoinRoles;
public JoinRolesInteractions(DiscordClient client)
{
_client = client;
SerializedJoinRoles.SetDiscordClient(_client);
JoinRolesSetupCommands.SetJoinRoleInteractions(this);
LoadJoinRoles();
client.GuildMemberAdded += ClientOnGuildMemberAdded;
}
private Task ClientOnGuildMemberAdded(DiscordClient sender, GuildMemberAddEventArgs e)
{
return Task.Run(() =>
{
JoinRoles associatedRoles = JoinRoles.FirstOrDefault(x => x.Guild == e.Guild);
if (associatedRoles == null || e.Member.Equals(_client.CurrentUser))
return;
foreach (JoinRole joinRole in associatedRoles.Roles)
{
e.Member.GrantRoleAsync(joinRole.Role).Wait();
}
GuildEventLogger.Instance
.LogInfo(e.Guild, $"{e.Member.Mention} was granted the default roles by joining the server").Wait();
});
}
public void SaveToFile()
{
List<SerializedJoinRoles> listToSerialize = new List<SerializedJoinRoles>();
foreach (JoinRoles joinRoles in JoinRoles)
{
listToSerialize.Add(new SerializedJoinRoles(joinRoles));
}
string json = JsonConvert.SerializeObject(listToSerialize, Formatting.Indented);
File.WriteAllText(JoinRolesLocalPath, json);
}
public void LoadJoinRoles()
{
JoinRoles = new List<JoinRoles>();
if (!File.Exists(JoinRolesLocalPath))
{
return;
}
string json = File.ReadAllText(JoinRolesLocalPath);
List<SerializedJoinRoles> serializedJoinRolesList =
JsonConvert.DeserializeObject<List<SerializedJoinRoles>>(json);
foreach (SerializedJoinRoles serializedJoinRoles in serializedJoinRolesList)
{
JoinRoles joinRoles = serializedJoinRoles.ToJoinRoles();
if (joinRoles != null)
JoinRoles.Add(joinRoles);
}
}
}
}