-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTelegramBotBuilder.cs
More file actions
241 lines (187 loc) · 7.88 KB
/
TelegramBotBuilder.cs
File metadata and controls
241 lines (187 loc) · 7.88 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
231
232
233
234
235
236
237
238
239
240
241
using System.Configuration;
using Botticelli.Bot.Data;
using Botticelli.Bot.Data.Repositories;
using Botticelli.Bot.Data.Settings;
using Botticelli.Bot.Utils;
using Botticelli.Bot.Utils.TextUtils;
using Botticelli.Client.Analytics;
using Botticelli.Client.Analytics.Settings;
using Botticelli.Controls.Parsers;
using Botticelli.Framework.Builders;
using Botticelli.Framework.Extensions;
using Botticelli.Framework.Options;
using Botticelli.Framework.Security;
using Botticelli.Framework.Services;
using Botticelli.Framework.Telegram.Decorators;
using Botticelli.Framework.Telegram.Handlers;
using Botticelli.Framework.Telegram.HostedService;
using Botticelli.Framework.Telegram.Http;
using Botticelli.Framework.Telegram.Layout;
using Botticelli.Framework.Telegram.Options;
using Botticelli.Framework.Telegram.Utils;
using Botticelli.Interfaces;
using Botticelli.Shared.Utils;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Telegram.Bot.Types.ReplyMarkups;
namespace Botticelli.Framework.Telegram.Builders;
/// <summary>
/// <inheritdoc />
/// </summary>
/// <typeparam name="TBot"></typeparam>
public abstract class TelegramBotBuilder<TBot>(bool isStandalone)
: TelegramBotBuilder<TBot, TelegramBotBuilder<TBot>>(isStandalone)
where TBot : TelegramBot
{
}
/// <summary>
/// Builder for a non-standalone Telegram bot
/// </summary>
/// <typeparam name="TBot"></typeparam>
/// <typeparam name="TBotBuilder"></typeparam>
public class TelegramBotBuilder<TBot, TBotBuilder> : BotBuilder<TBot, TBotBuilder>
where TBot : TelegramBot
where TBotBuilder : BotBuilder<TBot, TBotBuilder>
{
private readonly bool _isStandalone;
private readonly List<Action<IServiceProvider>> _subHandlers = [];
private string? _botToken;
private TelegramClientDecoratorBuilder _builder = null!;
public TelegramBotBuilder() : this(false)
{
}
public TelegramBotBuilder(bool isStandalone)
{
_isStandalone = isStandalone;
}
protected TelegramBotSettings? BotSettings { get; set; }
protected BotData.Entities.Bot.BotData? BotData { get; set; }
public static TBotBuilderNew? Instance<TBotBuilderNew>(IServiceCollection services,
ServerSettingsBuilder<ServerSettings> serverSettingsBuilder,
BotSettingsBuilder<TelegramBotSettings> settingsBuilder,
DataAccessSettingsBuilder<DataAccessSettings> dataAccessSettingsBuilder,
AnalyticsClientSettingsBuilder<AnalyticsClientSettings> analyticsClientSettingsBuilder,
bool isStandalone)
where TBotBuilderNew : BotBuilder<TBot, TBotBuilder>
{
var botBuilder = Activator.CreateInstance(typeof(TBotBuilderNew), [isStandalone]) as TBotBuilderNew;
(botBuilder as TelegramBotBuilder<TelegramBot, TelegramBotBuilder<TelegramBot>>)
.AddBotSettings(settingsBuilder)
.AddServerSettings(serverSettingsBuilder)
.AddAnalyticsSettings(analyticsClientSettingsBuilder)
.AddBotDataAccessSettings(dataAccessSettingsBuilder)
.AddServices(services);
return botBuilder;
}
public TelegramBotBuilder<TBot, TBotBuilder> AddSubHandler<T>()
where T : class, IBotUpdateSubHandler
{
Services.NotNull();
Services.AddSingleton<T>();
_subHandlers.Add(sp =>
{
var botHandler = sp.GetRequiredService<IBotUpdateHandler>();
var subHandler = sp.GetRequiredService<T>();
botHandler.AddSubHandler(subHandler);
});
return this;
}
public TelegramBotBuilder<TBot, TBotBuilder> AddToken(string botToken)
{
_botToken = botToken;
return this;
}
public TelegramBotBuilder<TBot, TBotBuilder> AddClient(TelegramClientDecoratorBuilder builder)
{
_builder = builder;
return this;
}
protected override TBot? InnerBuild(IServiceProvider serviceProvider)
{
ApplyMigrations(serviceProvider);
foreach (var sh in _subHandlers) sh.Invoke(serviceProvider);
if (Activator.CreateInstance(typeof(TBot),
_builder.Build(),
serviceProvider.GetRequiredService<IBotUpdateHandler>(),
serviceProvider.GetRequiredService<ILogger<TBot>>(),
serviceProvider.GetRequiredService<ITextTransformer>(),
serviceProvider.GetRequiredService<IBotDataAccess>(),
serviceProvider.GetService<MetricsProcessor>()) is not TBot bot)
throw new InvalidDataException($"{nameof(bot)} shouldn't be null!");
AddEvents(bot);
return bot;
}
public TelegramBotBuilder<TBot, TBotBuilder> Prepare()
{
if (!_isStandalone)
{
Services.AddSingleton(ServerSettingsBuilder!.Build());
Services.AddHttpClient<BotStatusService>()
.AddServerCertificates(BotSettings);
Services.AddHostedService<BotStatusService>();
Services.AddHttpClient<BotKeepAliveService>()
.AddServerCertificates(BotSettings);
Services.AddHostedService<BotKeepAliveService>();
Services.AddHostedService<TelegramBotHostedService>();
}
var botId = BotDataUtils.GetBotId();
if (botId == null) throw new InvalidDataException($"{nameof(botId)} shouldn't be null!");
#region Metrics
if (!_isStandalone)
{
var metricsPublisher = new MetricsPublisher(AnalyticsClientSettingsBuilder!.Build());
var metricsProcessor = new MetricsProcessor(metricsPublisher);
Services.AddSingleton(metricsPublisher);
Services.AddSingleton(metricsProcessor);
}
#endregion
#region Data
Services.AddDbContext<BotInfoContext>(o =>
o.UseSqlite($"Data source={BotDataAccessSettingsBuilder!.Build().ConnectionString}"), ServiceLifetime.Singleton);
Services.AddSingleton<IBotDataAccess, BotDataAccess>();
#endregion
#region TextTransformer
Services.AddTransient<ITextTransformer, TelegramTextTransformer>();
#endregion
if (BotSettings?.UseThrottling is true)
_builder.AddThrottler(new OutcomeThrottlingDelegatingHandler());
if (!string.IsNullOrWhiteSpace(_botToken)) _builder.AddToken(_botToken);
var client = _builder.Build();
client.NotNull();
client!.Timeout = TimeSpan.FromMilliseconds(BotSettings?.Timeout ?? 10000);
Services.AddSingleton<ILayoutSupplier<ReplyMarkup>, ReplyTelegramLayoutSupplier>()
.AddBotticelliFramework()
.AddSingleton<IBotUpdateHandler, BotUpdateHandler>()
.AddSingleton(client);
if (_isStandalone)
{
Services.AddHttpClient<BotStandaloneService>()
.AddServerCertificates(BotSettings);
if (BotData == null) throw new ConfigurationErrorsException("BotData is null!");
Services.AddHostedService<BotStandaloneService>()
.AddSingleton(BotData);
Services.AddSingleton<IBot>(sp => this .Build(sp)!);
}
return this;
}
private void AddEvents(TBot bot)
{
bot.MessageSent += MessageSent;
bot.MessageReceived += MessageReceived;
bot.MessageRemoved += MessageRemoved;
bot.ContactShared += SharedContact;
bot.NewChatMembers += NewChatMembers;
}
protected TelegramBotBuilder<TBot, TBotBuilder> AddBotSettings<TBotSettings>(
BotSettingsBuilder<TBotSettings> settingsBuilder)
where TBotSettings : BotSettings, new()
{
BotSettings = settingsBuilder.Build() as TelegramBotSettings ?? throw new InvalidOperationException();
return this;
}
private static void ApplyMigrations(IServiceProvider sp)
{
sp.GetRequiredService<BotInfoContext>().Database.Migrate();
}
}