-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
177 lines (152 loc) · 5.4 KB
/
Program.cs
File metadata and controls
177 lines (152 loc) · 5.4 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
using Discord;
using Discord.Net;
using Discord.WebSocket;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Quartz;
using Quartz.Logging;
using SQLite;
LogProvider.SetCurrentLogProvider(new ConsoleLogProvider());
var host = Host.CreateDefaultBuilder(args)
.UseSystemd()
.ConfigureServices((context, services) =>
{
services.AddHttpClient<RaiderIOClient>();
services.AddSingleton<DiscordSocketClient>();
services.AddSingleton<RaiderIOClient>();
services.AddSingleton<SQLiteConnection>(c =>
{
var db = new SQLiteConnection("mplus-data.db");
db.CreateTable<Character>();
db.CreateTable<CharacterAchievementState>();
db.CreateTable<CharacterRankingAchievementState>();
db.CreateTable<DatabaseMigration>();
db.CreateTable<MythicPlusRun>();
return db;
});
services.AddQuartz(q =>
{
q.UseSimpleTypeLoader();
q.UseInMemoryStore();
q.UseDefaultThreadPool(tp =>
{
tp.MaxConcurrency = 10;
});
q.ScheduleJob<CheckRunsJob>(trigger => trigger
.WithIdentity("Every 5 Minutes")
.WithSimpleSchedule(x => x
.WithIntervalInMinutes(5)
.RepeatForever())
.WithDescription("Checks Raider.IO for recent mythic plus runs on followed characters.")
);
});
services.AddQuartzHostedService(opt =>
{
opt.WaitForJobsToComplete = true;
});
})
.Build();
var discordClient = host.Services.GetRequiredService<DiscordSocketClient>();
var logger = host.Services.GetRequiredService<ILogger<DiscordSocketClient>>();
var config = host.Services.GetRequiredService<IConfiguration>();
var raiderIOClient = host.Services.GetRequiredService<RaiderIOClient>();
var db = host.Services.GetRequiredService<SQLiteConnection>();
await DatabaseMigrations.RunAsync(db, raiderIOClient).ConfigureAwait(false);
discordClient.Log += (LogMessage msg) =>
{
logger.LogInformation(msg.ToString());
return Task.CompletedTask;
};
await discordClient.LoginAsync(TokenType.Bot, config["Discord:Token"]).ConfigureAwait(false);
await discordClient.StartAsync().ConfigureAwait(false);
var ready = false;
discordClient.Ready += async () =>
{
var guild = discordClient.Guilds.Single();
var guildCommand = new SlashCommandBuilder();
guildCommand
.WithName("follow")
.WithDescription("Follows a specific character on Raider.IO.")
.AddOption("character", ApplicationCommandOptionType.String, "Your character name.", isRequired: true)
.AddOption("realm", ApplicationCommandOptionType.String, "Your character's server.", isRequired: true)
.AddOption("region", ApplicationCommandOptionType.String, "Your character's region.", isRequired: true);
try
{
await guild.CreateApplicationCommandAsync(guildCommand.Build()).ConfigureAwait(false);
}
catch (HttpException exception)
{
var json = JsonConvert.SerializeObject(exception.Errors, Formatting.Indented);
logger.LogError(json);
}
ready = true;
return;
};
discordClient.SlashCommandExecuted += async (SocketSlashCommand command) =>
{
switch (command.Data.Name)
{
case "follow":
var characterName = (command.Data.Options.First(x => x.Name == "character").Value as string)!;
var realm = (command.Data.Options.First(x => x.Name == "realm").Value as string)!;
var region = (command.Data.Options.First(x => x.Name == "region").Value as string)!;
var profile = await raiderIOClient.GetCharacterAsync(characterName, realm, region).ConfigureAwait(false);
if (profile.IsFailure)
{
var embed = new EmbedBuilder()
.WithColor(Color.Red)
.WithDescription($@"Error! Unable to follow character.{Environment.NewLine}{Environment.NewLine}To follow a character, the general format is `/follow character realm region`.");
await command.RespondAsync(embed: embed.Build()).ConfigureAwait(false);
}
else
{
db.InsertAll(profile.Result!.Mythic_Plus_Recent_Runs.Select(x => new MythicPlusRun { Id = x.RunId, Date = DateTimeOffset.Parse(x.Completed_At) }), "OR IGNORE");
var character = new Character
{
Name = characterName!,
Realm = realm!,
Region = region!,
};
var rowsInserted = db.Insert(character, "OR IGNORE");
if (rowsInserted == 1)
{
DatabaseMigrations.SeedAchievementState(db, character, profile.Result!);
await command.RespondAsync($"Now following {characterName} on {realm}-{region}!").ConfigureAwait(false);
}
else
{
await command.RespondAsync($"Already following {characterName} on {realm}-{region}!").ConfigureAwait(false);
}
}
break;
default:
throw new InvalidOperationException($"Unknown slash command {command.Data.Name}!");
}
};
SpinWait.SpinUntil(() => ready);
host.Run();
sealed class ConsoleLogProvider : ILogProvider
{
public Logger GetLogger(string name)
{
return (level, func, exception, parameters) =>
{
if (level >= Quartz.Logging.LogLevel.Info && func != null)
{
Console.WriteLine("[" + DateTime.Now.ToLongTimeString() + "] [" + level + "] " + func(), parameters);
}
return true;
};
}
public IDisposable OpenNestedContext(string message)
{
throw new NotImplementedException();
}
public IDisposable OpenMappedContext(string key, object value, bool destructure = false)
{
throw new NotImplementedException();
}
}