Skip to content

Commit

Permalink
Use MS SQL instead of API
Browse files Browse the repository at this point in the history
  • Loading branch information
another-one-employee committed Oct 9, 2024
1 parent 99d76fa commit a0a99fd
Show file tree
Hide file tree
Showing 13 changed files with 78 additions and 153 deletions.
Binary file added res/scripts/init_test_data.sql
Binary file not shown.
6 changes: 0 additions & 6 deletions src/TDPDNE.Telegram.Bot/Abstract/ITDPDNEWrapper.cs

This file was deleted.

17 changes: 0 additions & 17 deletions src/TDPDNE.Telegram.Bot/Configs/WrapperConfiguration.cs

This file was deleted.

13 changes: 13 additions & 0 deletions src/TDPDNE.Telegram.Bot/Extensions/BotConfigurationExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace TDPDNE.Telegram.Bot.Extensions;

using TDPDNE.Telegram.Bot.Configs;

public static class BotConfigurationExtensions
{
public static void OverrideFromEnvs(this BotConfiguration botConfiguration)
{
botConfiguration.BotToken = Environment.GetEnvironmentVariable("BotConfiguration__BotToken") ?? botConfiguration.BotToken;
botConfiguration.Support = Environment.GetEnvironmentVariable("BotConfiguration__Support") ?? botConfiguration.Support;
botConfiguration.Donations = Environment.GetEnvironmentVariable("BotConfiguration__Donations") ?? botConfiguration.Donations;
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
namespace TDPDNE.Telegram.Bot;
namespace TDPDNE.Telegram.Bot.Extensions;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

public static class Extensions
public static class ServiceProviderExtensions
{
public static T GetConfiguration<T>(this IServiceProvider serviceProvider)
where T : class
Expand Down
8 changes: 8 additions & 0 deletions src/TDPDNE.Telegram.Bot/Infrastructure/Dickpic.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace TDPDNE.Telegram.Bot.Infrastructure;

public record Dickpic
{
public Guid Id { get; init; }

public byte[] Picture { get; init; } = default!;
}
22 changes: 22 additions & 0 deletions src/TDPDNE.Telegram.Bot/Infrastructure/TDPDNEDbContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
namespace TDPDNE.Telegram.Bot.Infrastructure;

using Microsoft.EntityFrameworkCore;

public class TDPDNEDbContext : DbContext
{
public DbSet<Dickpic> Dickpics { get; set; }

public TDPDNEDbContext(DbContextOptions<TDPDNEDbContext> options) : base(options)
{
Database.EnsureCreated();
}

public async Task<Stream> GetRandomDickpicAsStream()
{
var dickpic = await Dickpics
.OrderBy(_ => Guid.NewGuid())
.FirstAsync();

return new MemoryStream(dickpic.Picture);
}
}
8 changes: 7 additions & 1 deletion src/TDPDNE.Telegram.Bot/Program.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
namespace TDPDNE.Telegram.Bot;

using global::Telegram.Bot;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using TDPDNE.Telegram.Bot.Configs;
using TDPDNE.Telegram.Bot.Extensions;
using TDPDNE.Telegram.Bot.Infrastructure;
using TDPDNE.Telegram.Bot.Services;

internal class Program
Expand All @@ -15,7 +18,7 @@ static async Task Main(string[] args)
.ConfigureServices((context, services) =>
{
services.Configure<BotConfiguration>(
context.Configuration.GetSection(BotConfiguration.Configuration));
context.Configuration.GetSection(BotConfiguration.Configuration));
services.AddHttpClient("telegram_bot_client")
.AddTypedClient<ITelegramBotClient>((httpClient, serviceProvider) =>
Expand All @@ -25,6 +28,9 @@ static async Task Main(string[] args)
return new TelegramBotClient(options, httpClient);
});
services.AddDbContext<TDPDNEDbContext>(options =>
options.UseSqlServer(context.Configuration.GetConnectionString(nameof(TDPDNEDbContext))));
services.AddScoped<UpdateHandler>();
services.AddScoped<ReceiverService>();
services.AddHostedService<PollingService>();
Expand Down
74 changes: 0 additions & 74 deletions src/TDPDNE.Telegram.Bot/Services/TDPDNEWrapper.cs

This file was deleted.

48 changes: 15 additions & 33 deletions src/TDPDNE.Telegram.Bot/Services/UpdateHandler.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
namespace TDPDNE.Telegram.Bot.Services;

using Abstract;
using Exceptions;
using global::Telegram.Bot;
using global::Telegram.Bot.Exceptions;
Expand All @@ -10,35 +9,25 @@
using Microsoft.Extensions.Logging;
using System;
using TDPDNE.Telegram.Bot.Configs;
using TDPDNE.Telegram.Bot.Extensions;
using TDPDNE.Telegram.Bot.Infrastructure;

public class UpdateHandler : IUpdateHandler
{
private readonly ITelegramBotClient _botClient;
private readonly TDPDNEDbContext _dbContext;
private readonly ILogger<UpdateHandler> _logger;
private readonly BotConfiguration _botConfiguration;

private static readonly BotConfiguration BotConfiguration;
private static readonly ITDPDNEWrapper Wrapper;

public UpdateHandler(ITelegramBotClient botClient, ILogger<UpdateHandler> logger)
public UpdateHandler(ITelegramBotClient botClient, TDPDNEDbContext dbContext, IConfiguration configuration, ILogger<UpdateHandler> logger)
{
_botClient = botClient;
_dbContext = dbContext;
_botConfiguration = configuration.GetRequiredSection(BotConfiguration.Configuration).Get<BotConfiguration>()!;
_botConfiguration.OverrideFromEnvs();
_logger = logger;
}

static UpdateHandler()
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", true)
.AddJsonFile("appsettings.Development.json", true)
.Build();

BotConfiguration = configuration.GetRequiredSection(BotConfiguration.Configuration).Get<BotConfiguration>() ??
throw new ArgumentNullException(BotConfiguration.Configuration);
OverrideBotConfigurationFromEnvironmentVariables(BotConfiguration);

Wrapper = new TDPDNEWrapper(configuration);
}

public async Task HandleUpdateAsync(ITelegramBotClient _, Update update, CancellationToken cancellationToken)
{
var handler = update switch
Expand Down Expand Up @@ -72,7 +61,7 @@ private async Task BotOnMessageReceived(Message message, CancellationToken cance
$"first name - {sentMessage.Chat.FirstName}, " +
$"last name - {sentMessage.Chat.LastName}");

static async Task<Message> UploadPicture(ITelegramBotClient botClient, Message message, CancellationToken cancellationToken)
async Task<Message> UploadPicture(ITelegramBotClient botClient, Message message, CancellationToken cancellationToken)
{
await botClient.SendChatActionAsync(
message.Chat.Id,
Expand All @@ -81,7 +70,7 @@ await botClient.SendChatActionAsync(

try
{
var content = await Wrapper.GetPicture(cancellationToken);
var content = await _dbContext.GetRandomDickpicAsStream();

return await botClient.SendPhotoAsync(
chatId: message.Chat.Id,
Expand All @@ -97,10 +86,10 @@ await botClient.SendChatActionAsync(
}
}

static async Task<Message> SendSupport(ITelegramBotClient botClient, Message message, CancellationToken cancellationToken)
async Task<Message> SendSupport(ITelegramBotClient botClient, Message message, CancellationToken cancellationToken)
{
string text = (@"*Support*:\n" +
$"{BotConfiguration.Support}")
$"{_botConfiguration.Support}")
.Replace(@"\n", Environment.NewLine);

return await botClient.SendTextMessageAsync(
Expand All @@ -110,10 +99,10 @@ static async Task<Message> SendSupport(ITelegramBotClient botClient, Message mes
cancellationToken: cancellationToken);
}

static async Task<Message> SendDonations(ITelegramBotClient botClient, Message message, CancellationToken cancellationToken)
async Task<Message> SendDonations(ITelegramBotClient botClient, Message message, CancellationToken cancellationToken)
{
string text = (@"*Donations*:\n" +
$"{BotConfiguration.Donations}")
$"{_botConfiguration.Donations}")
.Replace(@"\n", Environment.NewLine);

return await botClient.SendTextMessageAsync(
Expand All @@ -123,7 +112,7 @@ static async Task<Message> SendDonations(ITelegramBotClient botClient, Message m
cancellationToken: cancellationToken);
}

static async Task<Message> Usage(ITelegramBotClient botClient, Message message, CancellationToken cancellationToken)
async Task<Message> Usage(ITelegramBotClient botClient, Message message, CancellationToken cancellationToken)
{
const string usage = "*Usage*:\n" +
"/generate \\- _generate a new dickpic_\n" +
Expand Down Expand Up @@ -158,11 +147,4 @@ public async Task HandlePollingErrorAsync(ITelegramBotClient botClient, Exceptio
if (exception is RequestException)
await Task.Delay(TimeSpan.FromSeconds(2), cancellationToken);
}

private static void OverrideBotConfigurationFromEnvironmentVariables(BotConfiguration botConfiguration)
{
botConfiguration.BotToken = Environment.GetEnvironmentVariable("BotConfiguration__BotToken") ?? botConfiguration.BotToken;
botConfiguration.Support = Environment.GetEnvironmentVariable("BotConfiguration__Support") ?? botConfiguration.Support;
botConfiguration.Donations = Environment.GetEnvironmentVariable("BotConfiguration__Donations") ?? botConfiguration.Donations;
}
}
1 change: 1 addition & 0 deletions src/TDPDNE.Telegram.Bot/TDPDNE.Telegram.Bot.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

<ItemGroup>
<PackageReference Include="Magick.NET-Q16-AnyCPU" Version="14.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.10" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.1" />
Expand Down
15 changes: 5 additions & 10 deletions src/TDPDNE.Telegram.Bot/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
{
"BotConfiguration": {
"BotToken": "{BOT_TOKEN}",
"Support": "{SUPPORT}",
"Donations": "{DONATIONS}"
"BotToken": "#BOT_TOKEN",
"Support": "#SUPPORT",
"Donations": "#DONATIONS"
},
"WrapperConfiguration": {
"TDPDNEApiUrl": "https://api.thisdickpicdoesnotexist.com/dickPics/",
"TDPDNEImageStorageUrl": "https://www.thisdickpicdoesnotexist.com/stylegan2_fakes/",
"MagickFuzzPercentage": 10,
"AttemptsMaxCount": 10,
"MinId": 1,
"MaxId": 9194
"ConnectionStrings": {
"TDPDNEDbContext": "Server=(localdb)\\mssqllocaldb;Database=TDPDNE;Trusted_Connection=True;"
},
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
Expand Down
15 changes: 5 additions & 10 deletions src/TDPDNE.Telegram.Bot/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
{
"BotConfiguration": {
"BotToken": "{BOT_TOKEN}",
"Support": "{SUPPORT}",
"Donations": "{DONATIONS}"
"BotToken": "#BOT_TOKEN",
"Support": "#SUPPORT",
"Donations": "#DONATIONS"
},
"WrapperConfiguration": {
"TDPDNEApiUrl": "https://api.thisdickpicdoesnotexist.com/dickPics/",
"TDPDNEImageStorageUrl": "https://www.thisdickpicdoesnotexist.com/stylegan2_fakes/",
"MagickFuzzPercentage": 10,
"AttemptsMaxCount": 10,
"MinId": 1,
"MaxId": 9194
"ConnectionStrings": {
"TDPDNEDbContext": "#TDPDNE_DB_CONTEXT"
},
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
Expand Down

0 comments on commit a0a99fd

Please sign in to comment.