Compare commits
21
Commits
e768ee6604
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3157d215c1 | ||
|
|
1f553fa07e | ||
|
|
bf5d87094c | ||
|
|
81a49c1a5e | ||
|
|
011de9e56a | ||
|
|
e5264df7c9 | ||
|
|
230359a6ac | ||
|
|
1106209cd6 | ||
|
|
b2406557d1 | ||
|
|
77fa521e70 | ||
|
|
725216134b | ||
|
|
30acb201c6 | ||
|
|
fbe18bbb77 | ||
|
|
900d9b2c61 | ||
|
|
f5936e2bd6 | ||
|
|
5add09e264 | ||
|
|
afafe09426 | ||
|
|
e4ac2e04f7 | ||
|
|
0fb652664f | ||
|
|
9458942aeb | ||
|
|
07118e37af |
No files matched your search
@@ -0,0 +1,56 @@
|
|||||||
|
name: Create and publish a Docker image
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ "master" ]
|
||||||
|
|
||||||
|
env:
|
||||||
|
REGISTRY: gitea.yandex5.ru
|
||||||
|
IMAGE_NAME: monster/pepper_bot
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-and-push-image:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: ${{ github.server_url != 'https://github.com' }}
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Log in to the Container registry
|
||||||
|
uses: docker/login-action@65b78e6e13532edd9afa3aa52ac7964289d1a9c1
|
||||||
|
with:
|
||||||
|
registry: ${{ env.REGISTRY }}
|
||||||
|
username: ${{ vars.REGISTRY_USERNAME }}
|
||||||
|
password: ${{ secrets.REGISTRY_TOKEN }}
|
||||||
|
|
||||||
|
- name: Extract metadata (tags, labels) for Docker
|
||||||
|
id: meta
|
||||||
|
uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7
|
||||||
|
with:
|
||||||
|
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||||
|
|
||||||
|
- name: Build and push Docker image
|
||||||
|
uses: docker/build-push-action@f2a1d5e99d037542a71f64918e516c093c6f3fc4
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
push: true
|
||||||
|
tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.ref_name }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
|
||||||
|
- name: Install SSH Key
|
||||||
|
uses: shimataro/ssh-key-action@v2
|
||||||
|
with:
|
||||||
|
key: ${{ secrets.SSH_GITEA_PRIVATE_KEY }}
|
||||||
|
known_hosts: 'just-a-placeholder-so-we-dont-get-errors'
|
||||||
|
|
||||||
|
- name: Adding Known Hosts
|
||||||
|
run: ssh-keyscan -p ${{ vars.SSH_PORT }} -H ${{ vars.SSH_HOST }} >> ~/.ssh/known_hosts
|
||||||
|
|
||||||
|
- name: "Deploy to server"
|
||||||
|
run: ssh monster@${{ vars.SSH_HOST }} -p ${{ vars.SSH_PORT }} 'cd docker.services/pepper_bot && git pull && docker login ${{ env.REGISTRY }} -u ${{ vars.REGISTRY_USERNAME }} --password ${{ secrets.REGISTRY_TOKEN }} && docker compose pull && docker compose up -d && docker system prune --force'
|
||||||
|
|
||||||
|
- name: Send message to Telegram
|
||||||
|
uses: Lukasss93/telegram-action@v2
|
||||||
|
env:
|
||||||
|
TELEGRAM_TOKEN: ${{ vars.TELEGRAM_TOKEN }}
|
||||||
|
TELEGRAM_CHAT: 123622180
|
||||||
@@ -12,7 +12,7 @@ public interface ITelegramNotifier
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Уведомление о скидке в конкретный Telegram-чат (личная/персональная рассылка).
|
/// Уведомление о скидке в конкретный Telegram-чат (личная/персональная рассылка).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
Task NotifyDealToChatAsync(Deal deal, string chatId, CancellationToken cancellationToken);
|
Task NotifyDealToChatAsync(Deal deal, string chatId, string? selectionRule, CancellationToken cancellationToken);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Запустить обработку входящих сообщений Telegram и регистрацию подписок.
|
/// Запустить обработку входящих сообщений Telegram и регистрацию подписок.
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
using Microsoft.Extensions.Logging;
|
using NLog;
|
||||||
using PepperBot.Application.Interfaces;
|
using PepperBot.Application.Interfaces;
|
||||||
using PepperBot.Domain;
|
using PepperBot.Domain;
|
||||||
|
|
||||||
@@ -6,11 +6,12 @@ namespace PepperBot.Application.Services;
|
|||||||
|
|
||||||
public class DealService
|
public class DealService
|
||||||
{
|
{
|
||||||
|
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
|
||||||
|
|
||||||
private readonly IPepperClient _pepperClient;
|
private readonly IPepperClient _pepperClient;
|
||||||
private readonly IDealRepository _repository;
|
private readonly IDealRepository _repository;
|
||||||
private readonly ISubscriptionRepository _subscriptionRepository;
|
private readonly ISubscriptionRepository _subscriptionRepository;
|
||||||
private readonly ITelegramNotifier _notifier;
|
private readonly ITelegramNotifier _notifier;
|
||||||
private readonly ILogger<DealService> _logger;
|
|
||||||
private readonly IHealthMonitor _healthMonitor;
|
private readonly IHealthMonitor _healthMonitor;
|
||||||
|
|
||||||
public DealService(
|
public DealService(
|
||||||
@@ -18,14 +19,12 @@ public class DealService
|
|||||||
IDealRepository repository,
|
IDealRepository repository,
|
||||||
ISubscriptionRepository subscriptionRepository,
|
ISubscriptionRepository subscriptionRepository,
|
||||||
ITelegramNotifier notifier,
|
ITelegramNotifier notifier,
|
||||||
ILogger<DealService> logger,
|
|
||||||
IHealthMonitor healthMonitor)
|
IHealthMonitor healthMonitor)
|
||||||
{
|
{
|
||||||
_pepperClient = pepperClient;
|
_pepperClient = pepperClient;
|
||||||
_repository = repository;
|
_repository = repository;
|
||||||
_subscriptionRepository = subscriptionRepository;
|
_subscriptionRepository = subscriptionRepository;
|
||||||
_notifier = notifier;
|
_notifier = notifier;
|
||||||
_logger = logger;
|
|
||||||
_healthMonitor = healthMonitor;
|
_healthMonitor = healthMonitor;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,23 +32,28 @@ public class DealService
|
|||||||
{
|
{
|
||||||
var deals = await _pepperClient.GetLatestDealsAsync(cancellationToken);
|
var deals = await _pepperClient.GetLatestDealsAsync(cancellationToken);
|
||||||
|
|
||||||
|
Logger.Info("Начата обработка полученных скидок: всего {DealCount}", deals.Count);
|
||||||
|
|
||||||
// Хелсчек: успешный запрос, вернувший более одной скидки (пусть и не новой)
|
// Хелсчек: успешный запрос, вернувший более одной скидки (пусть и не новой)
|
||||||
if (deals.Count > 1)
|
if (deals.Count > 1)
|
||||||
{
|
{
|
||||||
_healthMonitor.ReportSuccess(DateTimeOffset.UtcNow);
|
_healthMonitor.ReportSuccess(DateTimeOffset.UtcNow);
|
||||||
|
Logger.Debug("HealthCheck: успешно получено более одной скидки ({DealCount})", deals.Count);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Загружаем активные подписки один раз на проход
|
// Загружаем активные подписки один раз на проход
|
||||||
var subscriptions = await _subscriptionRepository.GetAllActiveAsync(cancellationToken);
|
var subscriptions = await _subscriptionRepository.GetAllActiveAsync(cancellationToken);
|
||||||
|
Logger.Info("Загружено активных подписок: {SubscriptionCount}", subscriptions.Count);
|
||||||
|
|
||||||
foreach (var deal in deals)
|
foreach (var deal in deals)
|
||||||
{
|
{
|
||||||
if (await _repository.ExistsAsync(deal.Id, cancellationToken))
|
if (await _repository.ExistsAsync(deal.Id, cancellationToken))
|
||||||
{
|
{
|
||||||
|
Logger.Debug("Скидка уже есть в репозитории и будет пропущена: {DealId}", deal.Id);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
_logger.LogInformation("Новая скидка: {Title} ({Id})", deal.Title, deal.Id);
|
Logger.Info("Новая скидка: {Title} ({Id})", deal.Title, deal.Id);
|
||||||
|
|
||||||
await _repository.AddAsync(deal, cancellationToken);
|
await _repository.AddAsync(deal, cancellationToken);
|
||||||
|
|
||||||
@@ -58,6 +62,7 @@ public class DealService
|
|||||||
|
|
||||||
if (subscriptions.Count == 0)
|
if (subscriptions.Count == 0)
|
||||||
{
|
{
|
||||||
|
Logger.Debug("Активные подписки отсутствуют. Фильтрация по ключевым словам пропущена для скидки {DealId}", deal.Id);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -67,18 +72,33 @@ public class DealService
|
|||||||
{
|
{
|
||||||
if (!subscription.IsActive)
|
if (!subscription.IsActive)
|
||||||
{
|
{
|
||||||
|
Logger.Debug("Подписка {SubscriptionId} неактивна и будет пропущена", subscription.Id);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
var keywords = ParseKeywords(subscription.Keywords);
|
var keywords = ParseKeywords(subscription.Keywords);
|
||||||
if (keywords.Count == 0)
|
if (keywords.Count == 0)
|
||||||
{
|
{
|
||||||
|
Logger.Debug("У подписки {SubscriptionId} не удалось извлечь ключевые слова из строки: \"{RawKeywords}\"",
|
||||||
|
subscription.Id,
|
||||||
|
subscription.Keywords);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (IsMatch(searchableText, keywords))
|
var isMatch = IsMatch(searchableText, keywords, out var matchedKeyword);
|
||||||
|
Logger.Debug(
|
||||||
|
"Результат фильтрации скидки {DealId} по подписке {SubscriptionId}: {IsMatch}. Текст: \"{Text}\"; ключевые слова: {Keywords}",
|
||||||
|
deal.Id,
|
||||||
|
subscription.Id,
|
||||||
|
isMatch,
|
||||||
|
searchableText,
|
||||||
|
string.Join(", ", keywords));
|
||||||
|
|
||||||
|
if (isMatch)
|
||||||
{
|
{
|
||||||
await _notifier.NotifyDealToChatAsync(deal, subscription.ChatId, cancellationToken);
|
var selectionRule =
|
||||||
|
$"совпадение по ключевому слову \"{matchedKeyword}\" (подписка [{subscription.Id}]: {subscription.Keywords})";
|
||||||
|
await _notifier.NotifyDealToChatAsync(deal, subscription.ChatId, selectionRule, cancellationToken);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -93,8 +113,9 @@ public class DealService
|
|||||||
.ToList();
|
.ToList();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static bool IsMatch(string text, List<string> keywords)
|
private static bool IsMatch(string text, List<string> keywords, out string matchedKeyword)
|
||||||
{
|
{
|
||||||
|
matchedKeyword = string.Empty;
|
||||||
if (keywords.Count == 0)
|
if (keywords.Count == 0)
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
@@ -104,6 +125,7 @@ public class DealService
|
|||||||
{
|
{
|
||||||
if (text.Contains(keyword, StringComparison.OrdinalIgnoreCase))
|
if (text.Contains(keyword, StringComparison.OrdinalIgnoreCase))
|
||||||
{
|
{
|
||||||
|
matchedKeyword = keyword;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ public class Deal
|
|||||||
public DateTime CreatedAt { get; set; }
|
public DateTime CreatedAt { get; set; }
|
||||||
public long CreatedAtInMillis { get; set; }
|
public long CreatedAtInMillis { get; set; }
|
||||||
public string DealUrl { get; set; } = string.Empty;
|
public string DealUrl { get; set; } = string.Empty;
|
||||||
|
public string ImageMedium { get; set; } = string.Empty;
|
||||||
|
public string Permalink { get; set; } = string.Empty;
|
||||||
public string StoreName { get; set; } = string.Empty;
|
public string StoreName { get; set; } = string.Empty;
|
||||||
public string StorePermalink { get; set; } = string.Empty;
|
public string StorePermalink { get; set; } = string.Empty;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
using System.Net.Http.Headers;
|
using System.Net.Http.Headers;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
using Microsoft.Extensions.Logging;
|
using NLog;
|
||||||
using PepperBot.Application.Interfaces;
|
using PepperBot.Application.Interfaces;
|
||||||
using PepperBot.Domain;
|
using PepperBot.Domain;
|
||||||
|
|
||||||
@@ -9,6 +9,8 @@ namespace PepperBot.Infrastructure.Pepper;
|
|||||||
|
|
||||||
public class PepperClient : IPepperClient
|
public class PepperClient : IPepperClient
|
||||||
{
|
{
|
||||||
|
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
|
||||||
|
|
||||||
private const string Url =
|
private const string Url =
|
||||||
"https://auth.pepper.ru/v4/home/new?per_page=10&page=1&type=new&fields=id%2Ctitle%2Ccurrent_price%2Cshipping_and_handling%2Cretail_price%2Cpercent_off%2Ctop_deal%2Cimage_medium%2Ccreated_at%2Ccreated_at_in_millis%2Ccomments_count%2Clife_time_hotness%2Cuser%7Bid%2Clogin%2Cimage_medium%2Ccurrent_title%2Cdisplay_title%2Cdisplay_title_icon%7D%2Cstore%7Bpermalink%2Cname%2Cimage%7D%2Cpermalink%2Cposts_count%2Cvote_value%2Cdeal_types%2Cview_count%2Cforum%7Bforum_type%2Cname%2Cpermalink%7D%2Ctag_color_code%2C+dark_theme_tag_color_code%2Cworkflow_state%2Cdisplay_hotness_icon%2Creferral_state%2Ccoupon_code%2Cdeal_url%2Ccomment_preview%2Cis_nsfw%2Cdescription";
|
"https://auth.pepper.ru/v4/home/new?per_page=10&page=1&type=new&fields=id%2Ctitle%2Ccurrent_price%2Cshipping_and_handling%2Cretail_price%2Cpercent_off%2Ctop_deal%2Cimage_medium%2Ccreated_at%2Ccreated_at_in_millis%2Ccomments_count%2Clife_time_hotness%2Cuser%7Bid%2Clogin%2Cimage_medium%2Ccurrent_title%2Cdisplay_title%2Cdisplay_title_icon%7D%2Cstore%7Bpermalink%2Cname%2Cimage%7D%2Cpermalink%2Cposts_count%2Cvote_value%2Cdeal_types%2Cview_count%2Cforum%7Bforum_type%2Cname%2Cpermalink%7D%2Ctag_color_code%2C+dark_theme_tag_color_code%2Cworkflow_state%2Cdisplay_hotness_icon%2Creferral_state%2Ccoupon_code%2Cdeal_url%2Ccomment_preview%2Cis_nsfw%2Cdescription";
|
||||||
|
|
||||||
@@ -17,7 +19,6 @@ public class PepperClient : IPepperClient
|
|||||||
"6c266d5dc070c811e61f611ddd970a3defb493a23c50ee01f32eb9b0cfe46cd8";
|
"6c266d5dc070c811e61f611ddd970a3defb493a23c50ee01f32eb9b0cfe46cd8";
|
||||||
|
|
||||||
private readonly HttpClient _httpClient;
|
private readonly HttpClient _httpClient;
|
||||||
private readonly ILogger<PepperClient> _logger;
|
|
||||||
|
|
||||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||||
{
|
{
|
||||||
@@ -25,9 +26,8 @@ public class PepperClient : IPepperClient
|
|||||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
|
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
|
||||||
};
|
};
|
||||||
|
|
||||||
public PepperClient(ILogger<PepperClient> logger)
|
public PepperClient()
|
||||||
{
|
{
|
||||||
_logger = logger;
|
|
||||||
_httpClient = new HttpClient
|
_httpClient = new HttpClient
|
||||||
{
|
{
|
||||||
BaseAddress = new Uri("https://auth.pepper.ru")
|
BaseAddress = new Uri("https://auth.pepper.ru")
|
||||||
@@ -45,7 +45,10 @@ public class PepperClient : IPepperClient
|
|||||||
public async Task<IReadOnlyList<Deal>> GetLatestDealsAsync(CancellationToken cancellationToken)
|
public async Task<IReadOnlyList<Deal>> GetLatestDealsAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
using var request = new HttpRequestMessage(HttpMethod.Get, Url);
|
using var request = new HttpRequestMessage(HttpMethod.Get, Url);
|
||||||
|
Logger.Debug("Отправка запроса за последними скидками Pepper: {Url}", Url);
|
||||||
|
|
||||||
using var response = await _httpClient.SendAsync(request, cancellationToken);
|
using var response = await _httpClient.SendAsync(request, cancellationToken);
|
||||||
|
Logger.Debug("Получен ответ от Pepper: {StatusCode}", (int)response.StatusCode);
|
||||||
|
|
||||||
response.EnsureSuccessStatusCode();
|
response.EnsureSuccessStatusCode();
|
||||||
|
|
||||||
@@ -54,11 +57,16 @@ public class PepperClient : IPepperClient
|
|||||||
|
|
||||||
if (dto?.Deals is null)
|
if (dto?.Deals is null)
|
||||||
{
|
{
|
||||||
_logger.LogWarning("Не удалось распарсить ответ Pepper");
|
Logger.Warn("Не удалось распарсить ответ Pepper");
|
||||||
return Array.Empty<Deal>();
|
return Array.Empty<Deal>();
|
||||||
}
|
}
|
||||||
|
|
||||||
return dto.Deals.Select(MapToDeal).ToArray();
|
Logger.Info("Успешно распарсен ответ Pepper: всего сделок в ответе {DealCount}", dto.Deals.Count);
|
||||||
|
|
||||||
|
var mappedDeals = dto.Deals.Select(MapToDeal).ToArray();
|
||||||
|
Logger.Debug("После маппинга в доменную модель осталось сделок: {MappedCount}", mappedDeals.Length);
|
||||||
|
|
||||||
|
return mappedDeals;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Deal MapToDeal(PepperDeal dto)
|
private static Deal MapToDeal(PepperDeal dto)
|
||||||
@@ -73,6 +81,8 @@ public class PepperClient : IPepperClient
|
|||||||
CreatedAt = dto.CreatedAt ?? DateTimeOffset.FromUnixTimeMilliseconds(dto.CreatedAtInMillis).UtcDateTime,
|
CreatedAt = dto.CreatedAt ?? DateTimeOffset.FromUnixTimeMilliseconds(dto.CreatedAtInMillis).UtcDateTime,
|
||||||
CreatedAtInMillis = dto.CreatedAtInMillis,
|
CreatedAtInMillis = dto.CreatedAtInMillis,
|
||||||
DealUrl = dto.DealUrl ?? string.Empty,
|
DealUrl = dto.DealUrl ?? string.Empty,
|
||||||
|
ImageMedium = dto.ImageMedium ?? string.Empty,
|
||||||
|
Permalink = dto.Permalink ?? string.Empty,
|
||||||
StoreName = dto.Store?.Name ?? string.Empty,
|
StoreName = dto.Store?.Name ?? string.Empty,
|
||||||
StorePermalink = dto.Store?.Permalink ?? string.Empty
|
StorePermalink = dto.Store?.Permalink ?? string.Empty
|
||||||
};
|
};
|
||||||
@@ -110,6 +120,12 @@ public class PepperClient : IPepperClient
|
|||||||
[JsonPropertyName("deal_url")]
|
[JsonPropertyName("deal_url")]
|
||||||
public string? DealUrl { get; set; }
|
public string? DealUrl { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("image_medium")]
|
||||||
|
public string? ImageMedium { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("permalink")]
|
||||||
|
public string? Permalink { get; set; }
|
||||||
|
|
||||||
[JsonPropertyName("store")]
|
[JsonPropertyName("store")]
|
||||||
public PepperStore? Store { get; set; }
|
public PepperStore? Store { get; set; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using Microsoft.Extensions.Logging;
|
using NLog;
|
||||||
using PepperBot.Application.Interfaces;
|
using PepperBot.Application.Interfaces;
|
||||||
using PepperBot.Domain;
|
using PepperBot.Domain;
|
||||||
using Telegram.Bot;
|
using Telegram.Bot;
|
||||||
@@ -14,9 +14,10 @@ namespace PepperBot.Infrastructure.Telegram;
|
|||||||
|
|
||||||
public class TelegramNotifier : ITelegramNotifier
|
public class TelegramNotifier : ITelegramNotifier
|
||||||
{
|
{
|
||||||
|
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
|
||||||
|
|
||||||
private readonly ITelegramBotClient _botClient;
|
private readonly ITelegramBotClient _botClient;
|
||||||
private readonly ISubscriptionRepository _subscriptionRepository;
|
private readonly ISubscriptionRepository _subscriptionRepository;
|
||||||
private readonly ILogger<TelegramNotifier> _logger;
|
|
||||||
private readonly string _broadcastChatId;
|
private readonly string _broadcastChatId;
|
||||||
private bool _started;
|
private bool _started;
|
||||||
|
|
||||||
@@ -30,17 +31,15 @@ public class TelegramNotifier : ITelegramNotifier
|
|||||||
|
|
||||||
public TelegramNotifier(
|
public TelegramNotifier(
|
||||||
ITelegramBotClient botClient,
|
ITelegramBotClient botClient,
|
||||||
ISubscriptionRepository subscriptionRepository,
|
ISubscriptionRepository subscriptionRepository)
|
||||||
ILogger<TelegramNotifier> logger)
|
|
||||||
{
|
{
|
||||||
_botClient = botClient;
|
_botClient = botClient;
|
||||||
_subscriptionRepository = subscriptionRepository;
|
_subscriptionRepository = subscriptionRepository;
|
||||||
_logger = logger;
|
|
||||||
_broadcastChatId = Environment.GetEnvironmentVariable("TELEGRAM_CHAT_ID") ?? string.Empty;
|
_broadcastChatId = Environment.GetEnvironmentVariable("TELEGRAM_CHAT_ID") ?? string.Empty;
|
||||||
|
|
||||||
if (string.IsNullOrWhiteSpace(_broadcastChatId))
|
if (string.IsNullOrWhiteSpace(_broadcastChatId))
|
||||||
{
|
{
|
||||||
_logger.LogInformation("TELEGRAM_CHAT_ID не задан. Общая рассылка по скидкам будет отключена.");
|
Logger.Info("TELEGRAM_CHAT_ID не задан. Общая рассылка по скидкам будет отключена.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -51,17 +50,17 @@ public class TelegramNotifier : ITelegramNotifier
|
|||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
return SendDealAsync(deal, _broadcastChatId, cancellationToken);
|
return SendDealAsync(deal, _broadcastChatId, selectionRule: null, cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task NotifyDealToChatAsync(Deal deal, string chatId, CancellationToken cancellationToken)
|
public Task NotifyDealToChatAsync(Deal deal, string chatId, string? selectionRule, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrWhiteSpace(chatId))
|
if (string.IsNullOrWhiteSpace(chatId))
|
||||||
{
|
{
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
return SendDealAsync(deal, chatId, cancellationToken);
|
return SendDealAsync(deal, chatId, selectionRule, cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task StartAsync(CancellationToken cancellationToken)
|
public Task StartAsync(CancellationToken cancellationToken)
|
||||||
@@ -83,7 +82,7 @@ public class TelegramNotifier : ITelegramNotifier
|
|||||||
cancellationToken);
|
cancellationToken);
|
||||||
|
|
||||||
_started = true;
|
_started = true;
|
||||||
_logger.LogInformation("Запущена обработка входящих сообщений Telegram.");
|
Logger.Info("Запущена обработка входящих сообщений Telegram.");
|
||||||
|
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
@@ -93,10 +92,8 @@ public class TelegramNotifier : ITelegramNotifier
|
|||||||
if (update.Type == UpdateType.CallbackQuery)
|
if (update.Type == UpdateType.CallbackQuery)
|
||||||
{
|
{
|
||||||
await HandleCallbackQueryAsync(botClient, update.CallbackQuery!, cancellationToken);
|
await HandleCallbackQueryAsync(botClient, update.CallbackQuery!, cancellationToken);
|
||||||
{
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
if (update.Type != UpdateType.Message)
|
if (update.Type != UpdateType.Message)
|
||||||
{
|
{
|
||||||
@@ -198,7 +195,7 @@ public class TelegramNotifier : ITelegramNotifier
|
|||||||
text: confirmation.ToString(),
|
text: confirmation.ToString(),
|
||||||
cancellationToken: cancellationToken);
|
cancellationToken: cancellationToken);
|
||||||
|
|
||||||
_logger.LogInformation(
|
Logger.Info(
|
||||||
"Для чата {ChatId} добавлены правила подписки по ключевым словам: {Keywords}",
|
"Для чата {ChatId} добавлены правила подписки по ключевым словам: {Keywords}",
|
||||||
chatId,
|
chatId,
|
||||||
string.Join(", ", keywords));
|
string.Join(", ", keywords));
|
||||||
@@ -253,15 +250,21 @@ public class TelegramNotifier : ITelegramNotifier
|
|||||||
_ => exception.ToString()
|
_ => exception.ToString()
|
||||||
};
|
};
|
||||||
|
|
||||||
_logger.LogError("Ошибка Telegram-бота: {Error}", errorMessage);
|
Logger.Error("Ошибка Telegram-бота: {Error}", errorMessage);
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task SendDealAsync(Deal deal, string chatId, CancellationToken cancellationToken)
|
private async Task SendDealAsync(Deal deal, string chatId, string? selectionRule, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var textBuilder = new StringBuilder();
|
var textBuilder = new StringBuilder();
|
||||||
textBuilder.AppendLine($"🔥 {deal.Title}");
|
textBuilder.AppendLine($"🔥 {deal.Title}");
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(selectionRule))
|
||||||
|
{
|
||||||
|
textBuilder.AppendLine($"Правило отбора: {selectionRule}");
|
||||||
|
textBuilder.AppendLine();
|
||||||
|
}
|
||||||
|
|
||||||
if (deal.CurrentPrice is not null)
|
if (deal.CurrentPrice is not null)
|
||||||
{
|
{
|
||||||
textBuilder.AppendLine($"Цена: {deal.CurrentPrice:0.##} ₽");
|
textBuilder.AppendLine($"Цена: {deal.CurrentPrice:0.##} ₽");
|
||||||
@@ -280,8 +283,44 @@ public class TelegramNotifier : ITelegramNotifier
|
|||||||
textBuilder.AppendLine();
|
textBuilder.AppendLine();
|
||||||
textBuilder.AppendLine($"Магазин: {deal.StoreName}");
|
textBuilder.AppendLine($"Магазин: {deal.StoreName}");
|
||||||
textBuilder.AppendLine();
|
textBuilder.AppendLine();
|
||||||
textBuilder.AppendLine($"Открыть на Pepper.ru: {deal.DealUrl}");
|
textBuilder.AppendLine($"Товар в магазине: {deal.DealUrl}");
|
||||||
|
|
||||||
|
if (!string.IsNullOrEmpty(deal.Permalink))
|
||||||
|
{
|
||||||
|
textBuilder.AppendLine($"Открыть на pepper: https://www.pepper.ru/deals/{deal.Permalink}");
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var text = textBuilder.ToString();
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(deal.ImageMedium)
|
||||||
|
&& Uri.TryCreate(deal.ImageMedium, UriKind.Absolute, out var imageUri))
|
||||||
|
{
|
||||||
|
await _botClient.SendPhoto(
|
||||||
|
chatId: chatId,
|
||||||
|
photo: InputFile.FromUri(imageUri),
|
||||||
|
caption: text,
|
||||||
|
cancellationToken: cancellationToken);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await _botClient.SendMessage(
|
||||||
|
chatId: chatId,
|
||||||
|
text: text,
|
||||||
|
cancellationToken: cancellationToken);
|
||||||
|
}
|
||||||
|
catch (ApiRequestException ex)
|
||||||
|
{
|
||||||
|
Logger.Warn(
|
||||||
|
ex,
|
||||||
|
"Не удалось отправить сообщение в Telegram (чат {ChatId}): [{Code}] {Message}",
|
||||||
|
chatId,
|
||||||
|
ex.ErrorCode,
|
||||||
|
ex.Message);
|
||||||
|
|
||||||
|
// Фолбэк: если фото не отправилось (например, Telegram не смог скачать URL),
|
||||||
|
// пробуем хотя бы текст.
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await _botClient.SendMessage(
|
await _botClient.SendMessage(
|
||||||
@@ -289,14 +328,15 @@ public class TelegramNotifier : ITelegramNotifier
|
|||||||
text: textBuilder.ToString(),
|
text: textBuilder.ToString(),
|
||||||
cancellationToken: cancellationToken);
|
cancellationToken: cancellationToken);
|
||||||
}
|
}
|
||||||
catch (ApiRequestException ex)
|
catch (ApiRequestException fallbackEx)
|
||||||
{
|
{
|
||||||
_logger.LogWarning(
|
Logger.Warn(
|
||||||
ex,
|
fallbackEx,
|
||||||
"Не удалось отправить сообщение в Telegram (чат {ChatId}): [{Code}] {Message}",
|
"Не удалось отправить фолбэк-текст в Telegram (чат {ChatId}): [{Code}] {Message}",
|
||||||
chatId,
|
chatId,
|
||||||
ex.ErrorCode,
|
fallbackEx.ErrorCode,
|
||||||
ex.Message);
|
fallbackEx.Message);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,8 +14,15 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.3" />
|
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.3" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.3" />
|
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.3" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="10.0.3" />
|
<PackageReference Include="NLog" Version="6.1.1" />
|
||||||
|
<PackageReference Include="NLog.Web.AspNetCore" Version="6.1.2" />
|
||||||
<PackageReference Include="Telegram.Bot" Version="22.9.5.3" />
|
<PackageReference Include="Telegram.Bot" Version="22.9.5.3" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<None Update="nlog.config">
|
||||||
|
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||||
|
</None>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Hosting;
|
||||||
using Microsoft.Extensions.Logging;
|
using NLog;
|
||||||
using PepperBot.Application.Interfaces;
|
using PepperBot.Application.Interfaces;
|
||||||
using PepperBot.Application.Services;
|
using PepperBot.Application.Services;
|
||||||
|
|
||||||
@@ -7,24 +7,23 @@ namespace PepperBot;
|
|||||||
|
|
||||||
public class BotWorker : BackgroundService
|
public class BotWorker : BackgroundService
|
||||||
{
|
{
|
||||||
|
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
|
||||||
|
|
||||||
private readonly DealService _dealService;
|
private readonly DealService _dealService;
|
||||||
private readonly IDealRepository _repository;
|
private readonly IDealRepository _repository;
|
||||||
private readonly ISubscriptionRepository _subscriptionRepository;
|
private readonly ISubscriptionRepository _subscriptionRepository;
|
||||||
private readonly ITelegramNotifier _telegramNotifier;
|
private readonly ITelegramNotifier _telegramNotifier;
|
||||||
private readonly ILogger<BotWorker> _logger;
|
|
||||||
|
|
||||||
public BotWorker(
|
public BotWorker(
|
||||||
DealService dealService,
|
DealService dealService,
|
||||||
IDealRepository repository,
|
IDealRepository repository,
|
||||||
ISubscriptionRepository subscriptionRepository,
|
ISubscriptionRepository subscriptionRepository,
|
||||||
ITelegramNotifier telegramNotifier,
|
ITelegramNotifier telegramNotifier)
|
||||||
ILogger<BotWorker> logger)
|
|
||||||
{
|
{
|
||||||
_dealService = dealService;
|
_dealService = dealService;
|
||||||
_repository = repository;
|
_repository = repository;
|
||||||
_subscriptionRepository = subscriptionRepository;
|
_subscriptionRepository = subscriptionRepository;
|
||||||
_telegramNotifier = telegramNotifier;
|
_telegramNotifier = telegramNotifier;
|
||||||
_logger = logger;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||||
@@ -35,7 +34,7 @@ public class BotWorker : BackgroundService
|
|||||||
// Вся работа с Telegram вынесена в TelegramNotifier
|
// Вся работа с Telegram вынесена в TelegramNotifier
|
||||||
await _telegramNotifier.StartAsync(stoppingToken);
|
await _telegramNotifier.StartAsync(stoppingToken);
|
||||||
|
|
||||||
_logger.LogInformation("PepperBot запущен. Опрос скидок каждые 30 секунд.");
|
Logger.Info("PepperBot запущен. Опрос скидок каждые 30 секунд.");
|
||||||
|
|
||||||
while (!stoppingToken.IsCancellationRequested)
|
while (!stoppingToken.IsCancellationRequested)
|
||||||
{
|
{
|
||||||
@@ -45,7 +44,7 @@ public class BotWorker : BackgroundService
|
|||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_logger.LogError(ex, "Ошибка при обработке скидок");
|
Logger.Error(ex, "Ошибка при обработке скидок");
|
||||||
}
|
}
|
||||||
|
|
||||||
await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
|
await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
|
||||||
|
|||||||
+19
-5
@@ -10,14 +10,17 @@ using PepperBot.Infrastructure.Health;
|
|||||||
using PepperBot.Infrastructure.Pepper;
|
using PepperBot.Infrastructure.Pepper;
|
||||||
using PepperBot.Infrastructure.Telegram;
|
using PepperBot.Infrastructure.Telegram;
|
||||||
using Telegram.Bot;
|
using Telegram.Bot;
|
||||||
|
using NLog;
|
||||||
|
using NLog.Web;
|
||||||
|
|
||||||
|
var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
builder.Services.AddLogging(logging =>
|
builder.Logging.ClearProviders();
|
||||||
{
|
builder.Host.UseNLog();
|
||||||
logging.ClearProviders();
|
|
||||||
logging.AddConsole();
|
|
||||||
});
|
|
||||||
|
|
||||||
builder.Services.AddSingleton<IDealRepository, SqliteDealRepository>();
|
builder.Services.AddSingleton<IDealRepository, SqliteDealRepository>();
|
||||||
builder.Services.AddSingleton<ISubscriptionRepository, SqliteSubscriptionRepository>();
|
builder.Services.AddSingleton<ISubscriptionRepository, SqliteSubscriptionRepository>();
|
||||||
@@ -54,4 +57,15 @@ app.MapGet("/health", (IHealthMonitor healthMonitor) =>
|
|||||||
return Results.StatusCode(StatusCodes.Status503ServiceUnavailable);
|
return Results.StatusCode(StatusCodes.Status503ServiceUnavailable);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
logger.Info("Запуск PepperBot приложения");
|
||||||
await app.RunAsync();
|
await app.RunAsync();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.Error(ex, "Приложение остановлено из-за необработанного исключения");
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
global::NLog.LogManager.Shutdown();
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8" ?>
|
||||||
|
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
autoReload="true"
|
||||||
|
throwConfigExceptions="true">
|
||||||
|
|
||||||
|
<targets>
|
||||||
|
<target xsi:type="Console" name="console" layout="${longdate}|${level:uppercase=true}|${logger}|${message} ${exception:format=ToString}" />
|
||||||
|
</targets>
|
||||||
|
|
||||||
|
<rules>
|
||||||
|
<!-- Глушим инфраструктурные логи ASP.NET Core (Kestrel, маршрутизация, результаты HTTP и хостинг) -->
|
||||||
|
<logger name="Microsoft.AspNetCore.Hosting.Diagnostics" minlevel="Trace" maxlevel="Fatal" final="true" />
|
||||||
|
<logger name="Microsoft.AspNetCore.Server.Kestrel.*" minlevel="Trace" maxlevel="Fatal" final="true" />
|
||||||
|
<logger name="Microsoft.AspNetCore.Routing.*" minlevel="Trace" maxlevel="Fatal" final="true" />
|
||||||
|
<logger name="Microsoft.AspNetCore.Http.Result.*" minlevel="Trace" maxlevel="Fatal" final="true" />
|
||||||
|
|
||||||
|
<!-- Более подробные логи для парсинга и фильтров -->
|
||||||
|
<logger name="PepperBot.Infrastructure.Pepper.PepperClient" minlevel="Debug" writeTo="console" />
|
||||||
|
<logger name="PepperBot.Application.Services.DealService" minlevel="Debug" writeTo="console" />
|
||||||
|
<!-- Общий уровень для остальных логгеров -->
|
||||||
|
<logger name="*" minlevel="Debug" writeTo="console" />
|
||||||
|
</rules>
|
||||||
|
|
||||||
|
</nlog>
|
||||||
|
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
## PepperBot — Telegram‑бот для отслеживания скидок с Pepper.ru
|
||||||
|
|
||||||
|
PepperBot периодически опрашивает Pepper.ru, ищет новые скидки и отправляет их в Telegram:
|
||||||
|
- в **общий чат**, указанный в `TELEGRAM_CHAT_ID`;
|
||||||
|
- в **личные подписки пользователей** по ключевым словам.
|
||||||
|
|
||||||
|
Бот умеет управлять подписками прямо из Telegram через меню и кнопки.
|
||||||
|
|
||||||
|
### Возможности
|
||||||
|
|
||||||
|
- **Отправка новых скидок в Telegram**
|
||||||
|
- Формирование читаемого сообщения по скидке (цена, старая цена, процент скидки, магазин, ссылка).
|
||||||
|
- Отправка в общий канал/группу (`TELEGRAM_CHAT_ID`).
|
||||||
|
- **Персональные подписки по ключевым словам**
|
||||||
|
- Для каждой скидки ищутся совпадения по названию и магазину.
|
||||||
|
- Если совпало с ключевым словом подписки — скидка уходит в соответствующий чат.
|
||||||
|
- **Управление подписками через меню в Telegram**
|
||||||
|
- Команда `/menu` открывает меню с кнопками:
|
||||||
|
- `Добавить подписку`
|
||||||
|
- `Удалить подписку`
|
||||||
|
- `Список подписок`
|
||||||
|
- Добавление подписок по кейвордам.
|
||||||
|
- Удаление через inline‑кнопки.
|
||||||
|
- Просмотр всех активных подписок.
|
||||||
|
- **Health‑endpoint**
|
||||||
|
- `GET /health` — используется для проверки работоспособности (например, оркестратором).
|
||||||
|
|
||||||
|
### Архитектура (вкратце)
|
||||||
|
|
||||||
|
- `PepperBot` — единственный проект (консольное ASP.NET Core приложение).
|
||||||
|
- **Слои:**
|
||||||
|
- `Application` — интерфейсы и доменные сервисы (`DealService`, `ISubscriptionRepository`, `ITelegramNotifier` и т.п.).
|
||||||
|
- `Domain` — простые модели (`Deal`, `Subscription` и др.).
|
||||||
|
- `Infrastructure`
|
||||||
|
- `Data` — хранение в SQLite (`SqliteDealRepository`, `SqliteSubscriptionRepository`, файл БД `data/pepper_bot.db`).
|
||||||
|
- `Pepper` — клиент Pepper (`IPepperClient` / `PepperClient`).
|
||||||
|
- `Telegram` — вся работа с Telegram через библиотеку `Telegram.Bot` (`TelegramNotifier`).
|
||||||
|
- `Presentation`
|
||||||
|
- `BotWorker` — фоновой воркер, который:
|
||||||
|
- инициализирует репозитории;
|
||||||
|
- запускает работу `TelegramNotifier` (приём сообщений);
|
||||||
|
- каждые 30 секунд опрашивает Pepper и рассылает новые скидки.
|
||||||
|
|
||||||
|
### Зависимости
|
||||||
|
|
||||||
|
- .NET `10.0` (Target Framework: `net10.0`).
|
||||||
|
- ASP.NET Core (через `Microsoft.AspNetCore.App`).
|
||||||
|
- `Microsoft.Data.Sqlite` — для локальной БД.
|
||||||
|
- `Telegram.Bot` — работа с Telegram Bot API.
|
||||||
|
|
||||||
|
### Переменные окружения
|
||||||
|
|
||||||
|
- **`TELEGRAM_BOT_TOKEN`** — токен Telegram‑бота.
|
||||||
|
- **`TELEGRAM_CHAT_ID`** — ID чата/канала/группы для общей рассылки (можно оставить пустым, если общий канал не нужен).
|
||||||
|
- **`ASPNETCORE_URLS`** — адрес, на котором слушается HTTP (по умолчанию в `docker-compose.yml` `http://0.0.0.0:8080`).
|
||||||
|
|
||||||
|
### Запуск локально (без Docker)
|
||||||
|
|
||||||
|
1. Установите .NET SDK 10.0.
|
||||||
|
2. В корне репозитория задайте переменные окружения (пример для PowerShell):
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$env:TELEGRAM_BOT_TOKEN = "ваш_токен_бота"
|
||||||
|
$env:TELEGRAM_CHAT_ID = "ид_чата_для_общей_рассылки" # можно не задавать
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Запустите приложение:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cd PepperBot
|
||||||
|
dotnet run
|
||||||
|
```
|
||||||
|
|
||||||
|
Приложение поднимет HTTP‑сервер (endpoint `/health`) и запустит фонового воркера с Telegram‑ботом.
|
||||||
|
|
||||||
|
### Запуск через Docker
|
||||||
|
|
||||||
|
В корне репозитория уже есть `Dockerfile` и `docker-compose.yml`.
|
||||||
|
|
||||||
|
#### Быстрый старт
|
||||||
|
|
||||||
|
1. Задайте переменные окружения в системе или в `.env` рядом с `docker-compose.yml`:
|
||||||
|
|
||||||
|
```env
|
||||||
|
TELEGRAM_BOT_TOKEN=ваш_токен_бота
|
||||||
|
TELEGRAM_CHAT_ID=ид_чата_для_общей_рассылки
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Запустите контейнер:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose up -d --build
|
||||||
|
```
|
||||||
|
|
||||||
|
Что делает `docker-compose.yml`:
|
||||||
|
- собирает образ по `Dockerfile`;
|
||||||
|
- пробрасывает переменные окружения внутрь контейнера;
|
||||||
|
- монтирует `./data` на `/app/data` (там хранится SQLite‑база);
|
||||||
|
- прокидывает порт `9001` на `8080` контейнера (health‑endpoint будет доступен по `http://localhost:9001/health`).
|
||||||
|
|
||||||
|
### Как пользоваться ботом в Telegram
|
||||||
|
|
||||||
|
1. Создайте бота через `@BotFather` и пропишите его токен в `TELEGRAM_BOT_TOKEN`.
|
||||||
|
2. Запустите приложение (локально или в Docker).
|
||||||
|
3. Откройте диалог с ботом в Telegram.
|
||||||
|
|
||||||
|
#### Меню управления подписками
|
||||||
|
|
||||||
|
- Отправьте `/menu` — появится клавиатура:
|
||||||
|
- **Добавить подписку**
|
||||||
|
- Бот попросит отправить одно или несколько ключевых слов.
|
||||||
|
- Пример: `PLA ABS`, или `PLA, ABS, PETG`.
|
||||||
|
- Каждое слово станет отдельной подпиской.
|
||||||
|
- **Список подписок**
|
||||||
|
- Бот выведет все активные подписки в формате `[Id] keyword`.
|
||||||
|
- **Удалить подписку**
|
||||||
|
- Бот покажет inline‑кнопки по существующим подпискам.
|
||||||
|
- Нажмите на кнопку с нужным ключом — подписка будет деактивирована.
|
||||||
|
|
||||||
|
#### Как приходят уведомления
|
||||||
|
|
||||||
|
- Раз в 30 секунд бот опрашивает Pepper.ru.
|
||||||
|
- Для каждой новой скидки:
|
||||||
|
- отправляет сообщение в общий чат (`TELEGRAM_CHAT_ID`), если задан;
|
||||||
|
- подбирает все подписки, у которых ключ входит в `Title` или `StoreName` скидки (без учёта регистра);
|
||||||
|
- отправляет сообщение в соответствующие личные/групповые чаты.
|
||||||
|
|
||||||
|
### Полезное для разработки
|
||||||
|
|
||||||
|
- Сборка:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd PepperBot
|
||||||
|
dotnet build
|
||||||
|
```
|
||||||
|
|
||||||
|
- Запуск:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd PepperBot
|
||||||
|
dotnet run
|
||||||
|
```
|
||||||
|
|
||||||
|
- БД `data/pepper_bot.db` создаётся автоматически при первом запуске.
|
||||||
|
|
||||||
@@ -4,6 +4,7 @@ services:
|
|||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
|
image: gitea.yandex5.ru/monster/pepper_bot:master
|
||||||
container_name: pepper-bot
|
container_name: pepper-bot
|
||||||
environment:
|
environment:
|
||||||
- TELEGRAM_BOT_TOKEN=${TELEGRAM_BOT_TOKEN}
|
- TELEGRAM_BOT_TOKEN=${TELEGRAM_BOT_TOKEN}
|
||||||
@@ -14,4 +15,9 @@ services:
|
|||||||
ports:
|
ports:
|
||||||
- "9001:8080"
|
- "9001:8080"
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
logging:
|
||||||
|
driver: json-file
|
||||||
|
options:
|
||||||
|
max-size: "10m"
|
||||||
|
max-file: "3"
|
||||||
|
|
||||||
Reference in new issue
Block a user