Replace crutchy method of instantiating the bot with a proper one

This commit is contained in:
jetsparrow 2021-10-16 20:13:24 +03:00
parent db78d4a3c7
commit c8f505ba03
2 changed files with 6 additions and 5 deletions

View File

@ -3,10 +3,11 @@ using System.Threading.Tasks;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using System.Threading; using System.Threading;
using Microsoft.Extensions.Hosting;
namespace JetHerald namespace JetHerald
{ {
public partial class JetHeraldBot public partial class JetHeraldBot : IHostedService
{ {
Db Db { get; set; } Db Db { get; set; }
Options.Telegram TelegramConfig { get; } Options.Telegram TelegramConfig { get; }
@ -29,13 +30,13 @@ namespace JetHerald
CancellationTokenSource HeartbeatCancellation; CancellationTokenSource HeartbeatCancellation;
Task HeartbeatTask; Task HeartbeatTask;
public async Task Init() public async Task StartAsync(CancellationToken token)
{ {
await InitTelegram(); await InitTelegram();
await InitDiscord(); await InitDiscord();
} }
public async Task Stop() public async Task StopAsync(CancellationToken token)
{ {
await DiscordBot.DisconnectAsync(); await DiscordBot.DisconnectAsync();
TelegramBot.StopReceiving(); TelegramBot.StopReceiving();
@ -103,5 +104,6 @@ namespace JetHerald
} }
catch (Exception e) { Log.LogError(e, $"Error while sending message \"{formatted}\" to {chat}"); } catch (Exception e) { Log.LogError(e, $"Error while sending message \"{formatted}\" to {chat}"); }
} }
} }
} }

View File

@ -25,6 +25,7 @@ namespace JetHerald
services.Configure<Options.Timeout>(Configuration.GetSection("Timeout")); services.Configure<Options.Timeout>(Configuration.GetSection("Timeout"));
services.AddSingleton<Db>(); services.AddSingleton<Db>();
services.AddSingleton<JetHeraldBot>(); services.AddSingleton<JetHeraldBot>();
services.AddHostedService(s => s.GetService<JetHeraldBot>());
services.AddSingleton<LeakyBucket>(); services.AddSingleton<LeakyBucket>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
@ -33,8 +34,6 @@ namespace JetHerald
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{ {
var bot = app.ApplicationServices.GetService<JetHeraldBot>();
bot.Init().GetAwaiter().GetResult();
app.UsePathBase(Configuration.GetValue<string>("PathBase")); app.UsePathBase(Configuration.GetValue<string>("PathBase"));
if (env.IsDevelopment()) if (env.IsDevelopment())
{ {