Skip to content

Commit

Permalink
Merge pull request #41 from xforman2/40-create-message-handler-for-di…
Browse files Browse the repository at this point in the history
…scord-bot

feat: added discord message handler
  • Loading branch information
mf-16 authored Sep 5, 2024
2 parents 5729f39 + 63d9140 commit 3f1a479
Show file tree
Hide file tree
Showing 6 changed files with 97 additions and 12 deletions.
15 changes: 8 additions & 7 deletions Backend/Seeding/DbSeeder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,25 @@ public DbSeeder(HouseScoutContext context)
_context = context;
}

public void Seed()
public async Task Seed()
{
if (!_context.Estates.Any())
{
var estateFaker = new Faker<Estate>()
.RuleFor(e => e.ApiType, f => f.PickRandom<ApiType>())
.RuleFor(e => e.ApiId, f => f.Random.Guid().ToString())
.RuleFor(e => e.Address, f => f.Address.FullAddress())
.RuleFor(e => e.Price, f => f.Random.Decimal(100000, 1000000))
.RuleFor(e => e.Price, f => f.Random.Decimal(10000, 100000))
.RuleFor(e => e.Link, f => f.Internet.Url())
.RuleFor(e => e.Surface, f => f.Random.Double(50, 500))
.RuleFor(e => e.Surface, f => f.Random.Double(10, 100))
.RuleFor(e => e.EstateType, f => f.PickRandom<EstateType>())
.RuleFor(e => e.OfferType, f => f.PickRandom<OfferType>());
.RuleFor(e => e.OfferType, f => f.PickRandom<OfferType>())
.RuleFor(e => e.New, f => true);

var estates = estateFaker.Generate(500);
var estates = estateFaker.Generate(200);

_context.Estates.AddRange(estates);
_context.SaveChanges();
await _context.Estates.AddRangeAsync(estates);
await _context.SaveChangesAsync();
}
}
}
3 changes: 2 additions & 1 deletion DiscordBot/Filters/DataFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ int surfaceMax
{
return _context
.Estates.Where(e =>
e.Price >= priceMin
e.New
&& e.Price >= priceMin
&& e.Price <= priceMax
&& e.Surface >= surfaceMin
&& e.Surface <= surfaceMax
Expand Down
5 changes: 4 additions & 1 deletion DiscordBot/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Discord.Interactions;
using Discord.WebSocket;
using DiscordBot.Filters;
using DiscordBot.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
Expand Down Expand Up @@ -55,6 +56,7 @@ static async Task Main(string[] args)

var rabbitMqService = host.Services.GetRequiredService<RabbitMQService>();
rabbitMqService.StartListening();

await Task.Delay(-1); // Keep the bot running
}

Expand Down Expand Up @@ -87,7 +89,8 @@ private static IHostBuilder CreateHostBuilder() =>
)
.AddSingleton<CommandService>()
.AddScoped<DataFilter>()
.AddSingleton<RabbitMQService>();
.AddSingleton<RabbitMQService>()
.AddSingleton<IMessageHandler, DiscordMessageHandler>();
}
);

Expand Down
79 changes: 79 additions & 0 deletions DiscordBot/Services/DiscordMessageHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
using System.Text;
using Discord.WebSocket;
using DiscordBot.Filters;
using Microsoft.EntityFrameworkCore;
using SharedDependencies.Model;
using SharedDependencies.Services;

namespace DiscordBot.Services
{
public class DiscordMessageHandler : IMessageHandler
{
private readonly DiscordSocketClient _client;
private readonly HouseScoutContext _context;
private readonly DataFilter _dataFilter;

public DiscordMessageHandler(
DiscordSocketClient client,
HouseScoutContext context,
DataFilter dataFilter
)
{
_client = client;
_context = context;
_dataFilter = dataFilter;
}

public async Task HandleMessageAsync()
{
var users = await _context.Users.AsNoTracking().ToListAsync();
foreach (var dbUser in users)
{
var user = await _client.GetUserAsync((ulong)dbUser.UserId);
if (user != null)
{
var dmChannel = await user.CreateDMChannelAsync();
var estateData = _dataFilter.SurfacePriceFilter(
dbUser.MinPrice,
dbUser.MaxPrice,
dbUser.MinSurface,
dbUser.MaxSurface
);

var messages = PrepareMessages(estateData);

foreach (var message in messages)
{
await dmChannel.SendMessageAsync(message);
}
}
}
}

private List<string> PrepareMessages(List<Estate> estateData)
{
var messages = new List<string>();
var currentMessage = new StringBuilder();

foreach (var estate in estateData)
{
string estateInfo = $"{estate.Address} - {estate.Price:C} - {estate.Link}\n";

if (currentMessage.Length + estateInfo.Length > 2000)
{
messages.Add(currentMessage.ToString());
currentMessage.Clear();
}

currentMessage.Append(estateInfo);
}

if (currentMessage.Length > 0)
{
messages.Add(currentMessage.ToString());
}

return messages;
}
}
}
2 changes: 1 addition & 1 deletion SharedDependencies/Services/IMessageHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ namespace SharedDependencies.Services;

public interface IMessageHandler
{
void HandleMessage();
Task HandleMessageAsync();
}
5 changes: 3 additions & 2 deletions SharedDependencies/Services/RabbitMQService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,16 @@ public void PublishMessage(string message)
public void StartListening()
{
var consumer = new EventingBasicConsumer(_channel);
consumer.Received += (ch, ea) =>
consumer.Received += async (ch, ea) =>
{
if (_messageHandler != null)
{
_messageHandler.HandleMessage();
await _messageHandler.HandleMessageAsync();
}

_channel.BasicAck(ea.DeliveryTag, false);
};
_channel.BasicConsume(_queueName, false, consumer);
}

public void Dispose()
Expand Down

0 comments on commit 3f1a479

Please sign in to comment.