Compare commits
12
Commits
e5a14dc8b1
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a4e5bdc4b5 | ||
|
|
18c7cc65fe | ||
|
|
fa06b887ed | ||
|
|
ae4fc1aef7 | ||
|
|
9a4051980f | ||
|
|
c3129fc19d | ||
|
|
93058db0a9 | ||
|
|
198c9a3e2c | ||
|
|
100f84f4af | ||
|
|
63900b25b9 | ||
|
|
4c08ebd68b | ||
|
|
c79a4d4f6d |
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/telegram2vk_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/${{ github.event.repository.name }} && 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
|
||||||
+8
-2
@@ -1,4 +1,4 @@
|
|||||||
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
|
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
|
|
||||||
COPY ./src ./src
|
COPY ./src ./src
|
||||||
@@ -6,10 +6,16 @@ COPY ./src ./src
|
|||||||
RUN dotnet restore "src/Telegram2VkBot/Telegram2VkBot.csproj"
|
RUN dotnet restore "src/Telegram2VkBot/Telegram2VkBot.csproj"
|
||||||
RUN dotnet publish "src/Telegram2VkBot/Telegram2VkBot.csproj" -c Release -o /app/publish --no-restore
|
RUN dotnet publish "src/Telegram2VkBot/Telegram2VkBot.csproj" -c Release -o /app/publish --no-restore
|
||||||
|
|
||||||
FROM mcr.microsoft.com/dotnet/runtime:8.0 AS runtime
|
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS runtime
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends curl \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
COPY --from=build /app/publish .
|
COPY --from=build /app/publish .
|
||||||
|
|
||||||
|
ENV ASPNETCORE_URLS=http://+:8080
|
||||||
|
EXPOSE 8080
|
||||||
|
|
||||||
ENTRYPOINT ["dotnet", "Telegram2VkBot.dll"]
|
ENTRYPOINT ["dotnet", "Telegram2VkBot.dll"]
|
||||||
|
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
# Telegram → VK: репост из канала в сообщество
|
||||||
|
|
||||||
|
Сервис на **ASP.NET Core** слушает посты в **Telegram-канале** (long polling), публикует их на **стене сообщества ВКонтакте** и при редактировании поста в Telegram обновляет соответствующий пост ВК. Соответствие «сообщение Telegram ↔ пост ВК» хранится в **SQLite**.
|
||||||
|
|
||||||
|
Поддерживаются:
|
||||||
|
|
||||||
|
- текст и подписи к фото;
|
||||||
|
- несколько фото в одном посте ВК (альбомы из Telegram собираются в один пост);
|
||||||
|
- правки поста в Telegram → `wall.edit` в ВК.
|
||||||
|
|
||||||
|
## Требования
|
||||||
|
|
||||||
|
- [.NET 10 SDK](https://dotnet.microsoft.com/download) — для локального запуска без Docker;
|
||||||
|
- Docker и Compose с поддержкой **Compose file 3.8+** (для `healthcheck.start_period`) — для контейнера.
|
||||||
|
|
||||||
|
## Быстрый старт (Docker)
|
||||||
|
|
||||||
|
1. Склонируйте репозиторий и перейдите в каталог проекта.
|
||||||
|
|
||||||
|
2. Создайте файл `.env` рядом с `docker-compose.yml`. Переменные конфигурации должны соответствовать [соглашению ASP.NET Core](https://learn.microsoft.com/aspnet/core/fundamentals/configuration/#environment-variables): секция и свойство разделяются **двойным подчёркиванием** `__`.
|
||||||
|
|
||||||
|
Пример:
|
||||||
|
|
||||||
|
```env
|
||||||
|
TELEGRAM__BotToken=123456:ABC...
|
||||||
|
TELEGRAM__ChannelId=-1001234567890
|
||||||
|
VK__AccessToken=vk1.a...
|
||||||
|
VK__GroupId=123456789
|
||||||
|
VK__ApiVersion=5.199
|
||||||
|
```
|
||||||
|
|
||||||
|
- **TELEGRAM__ChannelId** — ID канала (для каналов часто вида `-100…`).
|
||||||
|
- **VK__GroupId** — числовой ID сообщества **без** минуса (в API владелец стены задаётся как отрицательный ID группы).
|
||||||
|
|
||||||
|
3. Добавьте бота в канал как администратора (чтобы приходили обновления о постах).
|
||||||
|
|
||||||
|
4. Токен ВК должен позволять публикацию от имени сообщества (`wall`, загрузка фото и т.д. — по вашей настройке приложения).
|
||||||
|
|
||||||
|
5. Запуск:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose build
|
||||||
|
docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
База по умолчанию: том `./data` → `/data/mapping.sqlite` в контейнере (см. `DB__Path` в `docker-compose.yml`).
|
||||||
|
|
||||||
|
## Локальный запуск (без Docker)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd src/Telegram2VkBot
|
||||||
|
dotnet run
|
||||||
|
```
|
||||||
|
|
||||||
|
Перед запуском задайте те же переменные окружения или отредактируйте `appsettings.json` (секции `TELEGRAM`, `VK`, `DB`). Путь к SQLite по умолчанию: `data/mapping.sqlite` относительно рабочей директории.
|
||||||
|
|
||||||
|
HTTP-сервер слушает адрес из `ASPNETCORE_URLS` (в Docker: `http://+:8080`).
|
||||||
|
|
||||||
|
## Проверка работоспособности
|
||||||
|
|
||||||
|
- `GET /health` — общий health; в теге `telegram` проверяется доступность Telegram Bot API.
|
||||||
|
- `GET /` — перенаправление на `/health`.
|
||||||
|
|
||||||
|
## Структура репозитория
|
||||||
|
|
||||||
|
| Путь | Назначение |
|
||||||
|
|------|------------|
|
||||||
|
| `src/Telegram2VkBot/` | приложение: `ForwardWorker` (polling), `VkApiClient`, `MappingRepository`, health check |
|
||||||
|
| `Dockerfile` | multi-stage сборка .NET 10, runtime + `curl` для healthcheck |
|
||||||
|
| `docker-compose.yml` | сервис, порт `8080`, том `data`, healthcheck |
|
||||||
+18
-3
@@ -1,10 +1,12 @@
|
|||||||
version: '3'
|
version: '3.8'
|
||||||
services:
|
services:
|
||||||
telegram2vk:
|
telegram2vk:
|
||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
restart: unless-stopped
|
image: gitea.yandex5.ru/monster/telegram2vk_bot:master
|
||||||
|
container_name: telegram2vk
|
||||||
|
restart: always
|
||||||
env_file: .env
|
env_file: .env
|
||||||
environment:
|
environment:
|
||||||
# Имена ключей должны совпадать с свойствами Options (BotToken, ChannelId, ...),
|
# Имена ключей должны совпадать с свойствами Options (BotToken, ChannelId, ...),
|
||||||
@@ -15,6 +17,19 @@ services:
|
|||||||
#VK__GroupId: ${VK_GROUP_ID}
|
#VK__GroupId: ${VK_GROUP_ID}
|
||||||
#VK__ApiVersion: ${VK_API_VERSION:-5.199}
|
#VK__ApiVersion: ${VK_API_VERSION:-5.199}
|
||||||
DB__Path: /data/mapping.sqlite
|
DB__Path: /data/mapping.sqlite
|
||||||
|
ASPNETCORE_URLS: http://+:8080
|
||||||
|
ports:
|
||||||
|
- "8082:8080"
|
||||||
volumes:
|
volumes:
|
||||||
- ./data:/data
|
- ./data:/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/health >/dev/null || exit 1"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 12s
|
||||||
|
retries: 3
|
||||||
|
start_period: 45s
|
||||||
|
logging:
|
||||||
|
driver: json-file
|
||||||
|
options:
|
||||||
|
max-size: "10m"
|
||||||
|
max-file: "3"
|
||||||
@@ -4,6 +4,9 @@ public sealed class TelegramOptions
|
|||||||
{
|
{
|
||||||
public required string BotToken { get; init; }
|
public required string BotToken { get; init; }
|
||||||
public required long ChannelId { get; init; }
|
public required long ChannelId { get; init; }
|
||||||
|
public bool AddReactionAfterRepost { get; init; } = true;
|
||||||
|
public string RepostReactionEmoji { get; init; } = "🤖";
|
||||||
|
public bool RepostReactionIsBig { get; init; } = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class VkOptions
|
public sealed class VkOptions
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
using Telegram.Bot;
|
using Telegram.Bot;
|
||||||
using Telegram.Bot.Types;
|
using Telegram.Bot.Types;
|
||||||
using Telegram.Bot.Types.Enums;
|
using Telegram.Bot.Types.Enums;
|
||||||
@@ -8,28 +11,41 @@ namespace Telegram2VkBot;
|
|||||||
|
|
||||||
public sealed class ForwardWorker : BackgroundService
|
public sealed class ForwardWorker : BackgroundService
|
||||||
{
|
{
|
||||||
|
private static readonly TimeSpan AlbumDebounce = TimeSpan.FromMilliseconds(950);
|
||||||
|
public const string TelegramBotApiHttpClientName = "TelegramBotApi";
|
||||||
|
|
||||||
private readonly TelegramOptions _telegram;
|
private readonly TelegramOptions _telegram;
|
||||||
private readonly VkOptions _vk;
|
private readonly VkOptions _vk;
|
||||||
private readonly VkApiClient _vkApi;
|
private readonly VkApiClient _vkApi;
|
||||||
private readonly MappingRepository _repo;
|
private readonly MappingRepository _repo;
|
||||||
|
private readonly IHttpClientFactory _httpFactory;
|
||||||
private readonly ILogger<ForwardWorker> _logger;
|
private readonly ILogger<ForwardWorker> _logger;
|
||||||
|
private readonly SemaphoreSlim _updateGate = new(1, 1);
|
||||||
|
private readonly ConcurrentDictionary<(long ChatId, string MediaGroupId), AlbumBuffer> _albumBuffers = new();
|
||||||
|
|
||||||
|
private CancellationToken _appStopping;
|
||||||
|
private TelegramBotClient _bot;
|
||||||
|
|
||||||
public ForwardWorker(
|
public ForwardWorker(
|
||||||
IOptions<TelegramOptions> telegram,
|
IOptions<TelegramOptions> telegram,
|
||||||
IOptions<VkOptions> vk,
|
IOptions<VkOptions> vk,
|
||||||
VkApiClient vkApi,
|
VkApiClient vkApi,
|
||||||
MappingRepository repo,
|
MappingRepository repo,
|
||||||
|
IHttpClientFactory httpFactory,
|
||||||
ILogger<ForwardWorker> logger)
|
ILogger<ForwardWorker> logger)
|
||||||
{
|
{
|
||||||
_telegram = telegram.Value;
|
_telegram = telegram.Value;
|
||||||
_vk = vk.Value;
|
_vk = vk.Value;
|
||||||
_vkApi = vkApi;
|
_vkApi = vkApi;
|
||||||
_repo = repo;
|
_repo = repo;
|
||||||
|
_httpFactory = httpFactory;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||||
{
|
{
|
||||||
|
_appStopping = stoppingToken;
|
||||||
|
|
||||||
if (string.IsNullOrWhiteSpace(_telegram.BotToken))
|
if (string.IsNullOrWhiteSpace(_telegram.BotToken))
|
||||||
throw new ArgumentException("TELEGRAM__BotToken (или TELEGRAM:BotToken) пуст — проверьте .env / переменные окружения.");
|
throw new ArgumentException("TELEGRAM__BotToken (или TELEGRAM:BotToken) пуст — проверьте .env / переменные окружения.");
|
||||||
if (_telegram.ChannelId == 0)
|
if (_telegram.ChannelId == 0)
|
||||||
@@ -42,7 +58,7 @@ public sealed class ForwardWorker : BackgroundService
|
|||||||
_logger.LogInformation("Init database");
|
_logger.LogInformation("Init database");
|
||||||
await _repo.InitializeAsync(stoppingToken);
|
await _repo.InitializeAsync(stoppingToken);
|
||||||
|
|
||||||
var bot = new TelegramBotClient(_telegram.BotToken);
|
_bot = new TelegramBotClient(_telegram.BotToken);
|
||||||
var receiverOptions = new ReceiverOptions
|
var receiverOptions = new ReceiverOptions
|
||||||
{
|
{
|
||||||
AllowedUpdates = new[]
|
AllowedUpdates = new[]
|
||||||
@@ -54,29 +70,39 @@ public sealed class ForwardWorker : BackgroundService
|
|||||||
|
|
||||||
_logger.LogInformation("Start Telegram polling for channel {ChannelId}", _telegram.ChannelId);
|
_logger.LogInformation("Start Telegram polling for channel {ChannelId}", _telegram.ChannelId);
|
||||||
|
|
||||||
using var semaphore = new SemaphoreSlim(1, 1);
|
_bot.StartReceiving(
|
||||||
|
|
||||||
bot.StartReceiving(
|
|
||||||
async (client, update, ct) =>
|
async (client, update, ct) =>
|
||||||
{
|
{
|
||||||
await semaphore.WaitAsync(ct);
|
await _updateGate.WaitAsync(ct);
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await HandleUpdateAsync(update, bot, ct);
|
await HandleUpdateAsync(update, _bot, ct);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
semaphore.Release();
|
_updateGate.Release();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
HandleErrorAsync,
|
HandleErrorAsync,
|
||||||
receiverOptions,
|
receiverOptions,
|
||||||
stoppingToken);
|
stoppingToken);
|
||||||
|
|
||||||
// StartReceiving не блокирует, поэтому держим сервис живым.
|
|
||||||
await Task.Delay(Timeout.InfiniteTimeSpan, stoppingToken);
|
await Task.Delay(Timeout.InfiniteTimeSpan, stoppingToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public override void Dispose()
|
||||||
|
{
|
||||||
|
_updateGate.Dispose();
|
||||||
|
foreach (var kv in _albumBuffers)
|
||||||
|
{
|
||||||
|
kv.Value.DebounceCts?.Cancel();
|
||||||
|
kv.Value.DebounceCts?.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
_albumBuffers.Clear();
|
||||||
|
base.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
private async Task HandleUpdateAsync(Update update, TelegramBotClient bot, CancellationToken ct)
|
private async Task HandleUpdateAsync(Update update, TelegramBotClient bot, CancellationToken ct)
|
||||||
{
|
{
|
||||||
if (update.EditedChannelPost is { } edited && edited.Chat.Id == _telegram.ChannelId)
|
if (update.EditedChannelPost is { } edited && edited.Chat.Id == _telegram.ChannelId)
|
||||||
@@ -93,14 +119,102 @@ public sealed class ForwardWorker : BackgroundService
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async Task HandleChannelPostAsync(TelegramBotClient bot, Message message, CancellationToken ct)
|
private async Task HandleChannelPostAsync(TelegramBotClient bot, Message message, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (message.MediaGroupId is { } groupId)
|
||||||
|
{
|
||||||
|
EnqueueAlbumPartAndScheduleFlush(bot, message, groupId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await PostSingleChannelMessageAsync(bot, message, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void EnqueueAlbumPartAndScheduleFlush(TelegramBotClient bot, Message message, string mediaGroupId)
|
||||||
|
{
|
||||||
|
var key = (message.Chat.Id, mediaGroupId);
|
||||||
|
var buffer = _albumBuffers.GetOrAdd(key, _ => new AlbumBuffer());
|
||||||
|
|
||||||
|
lock (buffer.Sync)
|
||||||
|
{
|
||||||
|
if (buffer.Messages.TrueForAll(m => m.MessageId != message.MessageId))
|
||||||
|
buffer.Messages.Add(message);
|
||||||
|
|
||||||
|
buffer.DebounceCts?.Cancel();
|
||||||
|
buffer.DebounceCts?.Dispose();
|
||||||
|
buffer.DebounceCts = CancellationTokenSource.CreateLinkedTokenSource(_appStopping);
|
||||||
|
var debounceToken = buffer.DebounceCts.Token;
|
||||||
|
|
||||||
|
_logger.LogDebug(
|
||||||
|
"Альбом media_group_id={MediaGroupId}: частей в буфере={Count}",
|
||||||
|
mediaGroupId,
|
||||||
|
buffer.Messages.Count);
|
||||||
|
|
||||||
|
_ = FlushAlbumAfterDebounceAsync(bot, key, debounceToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task FlushAlbumAfterDebounceAsync(
|
||||||
|
TelegramBotClient bot,
|
||||||
|
(long ChatId, string MediaGroupId) key,
|
||||||
|
CancellationToken debounceToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await Task.Delay(AlbumDebounce, debounceToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await _updateGate.WaitAsync(debounceToken).ConfigureAwait(false);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await FlushAlbumBufferCoreAsync(bot, key, debounceToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_updateGate.Release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task FlushAlbumBufferCoreAsync(
|
||||||
|
TelegramBotClient bot,
|
||||||
|
(long ChatId, string MediaGroupId) key,
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (!_albumBuffers.TryRemove(key, out var buffer))
|
||||||
|
return;
|
||||||
|
|
||||||
|
buffer.DebounceCts?.Dispose();
|
||||||
|
buffer.DebounceCts = null;
|
||||||
|
|
||||||
|
List<Message> batch;
|
||||||
|
lock (buffer.Sync)
|
||||||
|
{
|
||||||
|
batch = buffer.Messages.OrderBy(m => m.MessageId).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (batch.Count == 0)
|
||||||
|
return;
|
||||||
|
|
||||||
|
_logger.LogInformation(
|
||||||
|
"Альбом media_group_id={MediaGroupId}: публикация одного поста ВК по {Count} частям Telegram (message ids: {Ids})",
|
||||||
|
key.MediaGroupId,
|
||||||
|
batch.Count,
|
||||||
|
string.Join(",", batch.Select(m => m.MessageId)));
|
||||||
|
|
||||||
|
await PostChannelMessagesAsSingleVkPostAsync(bot, batch, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task PostSingleChannelMessageAsync(TelegramBotClient bot, Message message, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var ownerId = -Math.Abs(_vk.GroupId);
|
var ownerId = -Math.Abs(_vk.GroupId);
|
||||||
var telegramMessageId = message.MessageId;
|
var telegramMessageId = message.MessageId;
|
||||||
|
|
||||||
var text = ExtractTelegramText(message);
|
var text = ExtractTelegramText(message);
|
||||||
var attachments = await ExtractPhotoAttachmentIfAnyAsync(bot, message, ct);
|
var attachments = await ExtractPhotoAttachmentsFromMessagesAsync(bot, new[] { message }, ct);
|
||||||
|
|
||||||
// Если это не текст и не фото, просто пропускаем (сложно маппить видео/документы в VK без доп. логики).
|
|
||||||
if (string.IsNullOrWhiteSpace(text) && string.IsNullOrWhiteSpace(attachments))
|
if (string.IsNullOrWhiteSpace(text) && string.IsNullOrWhiteSpace(attachments))
|
||||||
{
|
{
|
||||||
_logger.LogInformation("Skip message {MessageId}: no text/photo", telegramMessageId);
|
_logger.LogInformation("Skip message {MessageId}: no text/photo", telegramMessageId);
|
||||||
@@ -117,15 +231,80 @@ public sealed class ForwardWorker : BackgroundService
|
|||||||
|
|
||||||
var postId = await _vkApi.WallPostAsync(ownerId, text ?? string.Empty, attachments, ct);
|
var postId = await _vkApi.WallPostAsync(ownerId, text ?? string.Empty, attachments, ct);
|
||||||
await _repo.UpsertAsync(
|
await _repo.UpsertAsync(
|
||||||
telegramChatId: _telegram.ChannelId,
|
_telegram.ChannelId,
|
||||||
telegramMessageId: telegramMessageId,
|
telegramMessageId,
|
||||||
vkOwnerId: ownerId,
|
ownerId,
|
||||||
vkPostId: postId,
|
postId,
|
||||||
vkMessage: text,
|
text,
|
||||||
vkAttachments: attachments,
|
attachments,
|
||||||
ct);
|
ct);
|
||||||
|
|
||||||
_logger.LogInformation("Posted new VK post {PostId} for Telegram {MessageId}", postId, telegramMessageId);
|
_logger.LogInformation("Posted new VK post {PostId} for Telegram {MessageId}", postId, telegramMessageId);
|
||||||
|
await TryAddTelegramReactionAfterRepostAsync(message.Chat.Id, telegramMessageId, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task PostChannelMessagesAsSingleVkPostAsync(TelegramBotClient bot, IReadOnlyList<Message> batch, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var ownerId = -Math.Abs(_vk.GroupId);
|
||||||
|
var text = ExtractTelegramTextFromAlbum(batch);
|
||||||
|
var attachments = await ExtractPhotoAttachmentsFromMessagesAsync(bot, batch, ct);
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(text) && string.IsNullOrWhiteSpace(attachments))
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Skip album: no text/photo after merge (ids {Ids})", string.Join(",", batch.Select(m => m.MessageId)));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogInformation(
|
||||||
|
"VK wall.post (альбом): owner_id={OwnerId}, частей={Count}, textLen={TextLen}, textPreview={TextPreview}, attachments={Attachments}",
|
||||||
|
ownerId,
|
||||||
|
batch.Count,
|
||||||
|
(text ?? string.Empty).Length,
|
||||||
|
TruncateForLog(text, 200),
|
||||||
|
attachments ?? "(none)");
|
||||||
|
|
||||||
|
var postId = await _vkApi.WallPostAsync(ownerId, text ?? string.Empty, attachments, ct);
|
||||||
|
|
||||||
|
foreach (var msg in batch)
|
||||||
|
{
|
||||||
|
await _repo.UpsertAsync(
|
||||||
|
_telegram.ChannelId,
|
||||||
|
msg.MessageId,
|
||||||
|
ownerId,
|
||||||
|
postId,
|
||||||
|
text,
|
||||||
|
attachments,
|
||||||
|
ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogInformation(
|
||||||
|
"Posted single VK post {PostId} for Telegram album media_group_id={Group} (message ids {Ids})",
|
||||||
|
postId,
|
||||||
|
batch[0].MediaGroupId,
|
||||||
|
string.Join(",", batch.Select(m => m.MessageId)));
|
||||||
|
|
||||||
|
// Реакция на «оригинальный пост» альбома: первую (самую раннюю) часть.
|
||||||
|
await TryAddTelegramReactionAfterRepostAsync(batch[0].Chat.Id, batch[0].MessageId, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task TryAddTelegramReactionAfterRepostAsync(long chatId, int messageId, CancellationToken ct)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_logger.LogWarning($"Начинаю простановку реакции.");
|
||||||
|
await _bot.SetMessageReaction(chatId, messageId, [new ReactionTypeEmoji() { Emoji = "🦄" }], cancellationToken: ct);
|
||||||
|
_logger.LogWarning($"Реация успешно проставлена.");
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException ex) when (ct.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
_logger.LogWarning($"Ошибка проставноки реакции: {ex.Message}{ex.StackTrace}");
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogWarning($"Ошибка проставноки реакции: {ex.Message}{ex.StackTrace}");
|
||||||
|
// intentionally no logging (do not spam logs for tg calls)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task HandleChannelPostEditAsync(TelegramBotClient bot, Message editedMessage, CancellationToken ct)
|
private async Task HandleChannelPostEditAsync(TelegramBotClient bot, Message editedMessage, CancellationToken ct)
|
||||||
@@ -137,8 +316,15 @@ public sealed class ForwardWorker : BackgroundService
|
|||||||
|
|
||||||
var extractedText = ExtractTelegramText(editedMessage);
|
var extractedText = ExtractTelegramText(editedMessage);
|
||||||
|
|
||||||
// Если фото в апдейте отсутствует, то оставляем старые вложения, чтобы не "стереть" медиа на стороне VK.
|
var extractedAttachments = await ExtractPhotoAttachmentsFromMessagesAsync(bot, new[] { editedMessage }, ct);
|
||||||
string? extractedAttachments = await ExtractPhotoAttachmentIfAnyAsync(bot, editedMessage, ct);
|
|
||||||
|
// У апдейта альбома в Telegram приходит одно сообщение с одной фото; не затираем все вложения ВК одним файлом.
|
||||||
|
if (editedMessage.MediaGroupId is not null && existing is { VkAttachments: { } prevAtt })
|
||||||
|
{
|
||||||
|
if (CountAttachmentTokens(prevAtt) > CountAttachmentTokens(extractedAttachments))
|
||||||
|
extractedAttachments = prevAtt;
|
||||||
|
}
|
||||||
|
|
||||||
var attachmentsToSend = !string.IsNullOrWhiteSpace(extractedAttachments)
|
var attachmentsToSend = !string.IsNullOrWhiteSpace(extractedAttachments)
|
||||||
? extractedAttachments
|
? extractedAttachments
|
||||||
: existing?.VkAttachments;
|
: existing?.VkAttachments;
|
||||||
@@ -181,11 +367,69 @@ public sealed class ForwardWorker : BackgroundService
|
|||||||
attachmentsToSend ?? "(none)");
|
attachmentsToSend ?? "(none)");
|
||||||
|
|
||||||
await _vkApi.WallEditAsync(existing.Value.VkOwnerId, existing.Value.VkPostId, messageToSendFinal, attachmentsToSend, ct);
|
await _vkApi.WallEditAsync(existing.Value.VkOwnerId, existing.Value.VkPostId, messageToSendFinal, attachmentsToSend, ct);
|
||||||
await _repo.UpsertAsync(_telegram.ChannelId, telegramMessageId, existing.Value.VkOwnerId, existing.Value.VkPostId, messageToSendFinal, attachmentsToSend, ct);
|
|
||||||
|
var idsToTouch = await _repo.GetTelegramMessageIdsForVkPostAsync(_telegram.ChannelId, existing.Value.VkPostId, ct);
|
||||||
|
if (idsToTouch.Count == 0)
|
||||||
|
idsToTouch = new[] { telegramMessageId };
|
||||||
|
|
||||||
|
foreach (var mid in idsToTouch)
|
||||||
|
{
|
||||||
|
await _repo.UpsertAsync(
|
||||||
|
_telegram.ChannelId,
|
||||||
|
mid,
|
||||||
|
existing.Value.VkOwnerId,
|
||||||
|
existing.Value.VkPostId,
|
||||||
|
messageToSendFinal,
|
||||||
|
attachmentsToSend,
|
||||||
|
ct);
|
||||||
|
}
|
||||||
|
|
||||||
_logger.LogInformation("Edited VK post {PostId} for Telegram {MessageId}", existing.Value.VkPostId, telegramMessageId);
|
_logger.LogInformation("Edited VK post {PostId} for Telegram {MessageId}", existing.Value.VkPostId, telegramMessageId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static int CountAttachmentTokens(string? vkAttachmentsCsv)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(vkAttachmentsCsv))
|
||||||
|
return 0;
|
||||||
|
return vkAttachmentsCsv.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Length;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? ExtractTelegramTextFromAlbum(IReadOnlyList<Message> messages)
|
||||||
|
{
|
||||||
|
foreach (var message in messages.OrderBy(m => m.MessageId))
|
||||||
|
{
|
||||||
|
var t = ExtractTelegramText(message);
|
||||||
|
if (!string.IsNullOrWhiteSpace(t))
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<string?> ExtractPhotoAttachmentsFromMessagesAsync(
|
||||||
|
TelegramBotClient bot,
|
||||||
|
IReadOnlyList<Message> messages,
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
var ordered = messages.OrderBy(m => m.MessageId).ToList();
|
||||||
|
var parts = new List<string>();
|
||||||
|
|
||||||
|
foreach (var message in ordered)
|
||||||
|
{
|
||||||
|
if (message.Photo is not { Length: > 0 })
|
||||||
|
continue;
|
||||||
|
|
||||||
|
var best = message.Photo[^1];
|
||||||
|
await using var ms = new MemoryStream();
|
||||||
|
await bot.GetInfoAndDownloadFile(best.FileId, ms, ct).ConfigureAwait(false);
|
||||||
|
var att = await _vkApi.UploadPhotoAndGetAttachmentAsync(ms.ToArray(), ct).ConfigureAwait(false);
|
||||||
|
if (!string.IsNullOrWhiteSpace(att))
|
||||||
|
parts.Add(att);
|
||||||
|
}
|
||||||
|
|
||||||
|
return parts.Count == 0 ? null : string.Join(",", parts);
|
||||||
|
}
|
||||||
|
|
||||||
private static string? ExtractTelegramText(Message message)
|
private static string? ExtractTelegramText(Message message)
|
||||||
{
|
{
|
||||||
if (!string.IsNullOrWhiteSpace(message.Text))
|
if (!string.IsNullOrWhiteSpace(message.Text))
|
||||||
@@ -195,28 +439,12 @@ public sealed class ForwardWorker : BackgroundService
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<string?> ExtractPhotoAttachmentIfAnyAsync(TelegramBotClient bot, Message message, CancellationToken ct)
|
|
||||||
{
|
|
||||||
if (message.Photo == null || message.Photo.Length == 0)
|
|
||||||
return null;
|
|
||||||
|
|
||||||
// Telegram предоставляет несколько размеров одного фото. Берем самый большой.
|
|
||||||
var best = message.Photo[^1];
|
|
||||||
|
|
||||||
await using var ms = new MemoryStream();
|
|
||||||
// В Telegram.Bot v22 методы называются без Async-суффикса.
|
|
||||||
await bot.GetInfoAndDownloadFile(best.FileId, ms, ct);
|
|
||||||
|
|
||||||
return await _vkApi.UploadPhotoAndGetAttachmentAsync(ms.ToArray(), ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Task HandleErrorAsync(
|
private static Task HandleErrorAsync(
|
||||||
ITelegramBotClient client,
|
ITelegramBotClient client,
|
||||||
Exception exception,
|
Exception exception,
|
||||||
HandleErrorSource errorSource,
|
HandleErrorSource errorSource,
|
||||||
CancellationToken cancellationToken)
|
CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
// Логирование делаем в Worker через исключения, но чтобы не терять ошибки polling'а — просто возвращаем CompletedTask.
|
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -228,5 +456,11 @@ public sealed class ForwardWorker : BackgroundService
|
|||||||
return text;
|
return text;
|
||||||
return string.Concat(text.AsSpan(0, maxLen), "…(len=", text.Length.ToString(), ")");
|
return string.Concat(text.AsSpan(0, maxLen), "…(len=", text.Length.ToString(), ")");
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
|
private sealed class AlbumBuffer
|
||||||
|
{
|
||||||
|
public object Sync { get; } = new();
|
||||||
|
public List<Message> Messages { get; } = new();
|
||||||
|
public CancellationTokenSource? DebounceCts;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -75,6 +75,34 @@ LIMIT 1;";
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Все telegram message_id, привязанные к одному посту ВК (альбом).</summary>
|
||||||
|
public async Task<IReadOnlyList<int>> GetTelegramMessageIdsForVkPostAsync(
|
||||||
|
long telegramChatId,
|
||||||
|
int vkPostId,
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
await using var con = new SqliteConnection(ConnectionString);
|
||||||
|
await con.OpenAsync(ct);
|
||||||
|
|
||||||
|
var sql = @"
|
||||||
|
SELECT telegram_message_id
|
||||||
|
FROM vk_mappings
|
||||||
|
WHERE telegram_chat_id = $telegram_chat_id AND vk_post_id = $vk_post_id
|
||||||
|
ORDER BY telegram_message_id;";
|
||||||
|
|
||||||
|
await using var cmd = con.CreateCommand();
|
||||||
|
cmd.CommandText = sql;
|
||||||
|
cmd.Parameters.AddWithValue("$telegram_chat_id", telegramChatId);
|
||||||
|
cmd.Parameters.AddWithValue("$vk_post_id", vkPostId);
|
||||||
|
|
||||||
|
var ids = new List<int>();
|
||||||
|
await using var reader = await cmd.ExecuteReaderAsync(ct);
|
||||||
|
while (await reader.ReadAsync(ct))
|
||||||
|
ids.Add(reader.GetInt32(0));
|
||||||
|
|
||||||
|
return ids;
|
||||||
|
}
|
||||||
|
|
||||||
public async Task UpsertAsync(
|
public async Task UpsertAsync(
|
||||||
long telegramChatId,
|
long telegramChatId,
|
||||||
int telegramMessageId,
|
int telegramMessageId,
|
||||||
|
|||||||
@@ -1,13 +1,10 @@
|
|||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using Microsoft.Extensions.Hosting;
|
|
||||||
|
|
||||||
namespace Telegram2VkBot;
|
namespace Telegram2VkBot;
|
||||||
|
|
||||||
public static class Program
|
public static class Program
|
||||||
{
|
{
|
||||||
public static async Task Main(string[] args)
|
public static async Task Main(string[] args)
|
||||||
{
|
{
|
||||||
var builder = Host.CreateApplicationBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
builder.Services.Configure<TelegramOptions>(builder.Configuration.GetSection("TELEGRAM"));
|
builder.Services.Configure<TelegramOptions>(builder.Configuration.GetSection("TELEGRAM"));
|
||||||
builder.Services.Configure<VkOptions>(builder.Configuration.GetSection("VK"));
|
builder.Services.Configure<VkOptions>(builder.Configuration.GetSection("VK"));
|
||||||
@@ -17,9 +14,25 @@ public static class Program
|
|||||||
{
|
{
|
||||||
client.Timeout = TimeSpan.FromSeconds(60);
|
client.Timeout = TimeSpan.FromSeconds(60);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
builder.Services.AddHttpClient(TelegramApiHealthCheck.HttpClientName, client =>
|
||||||
|
{
|
||||||
|
client.Timeout = TimeSpan.FromSeconds(15);
|
||||||
|
});
|
||||||
|
|
||||||
|
builder.Services.AddHttpClient("TelegramBotApi", client =>
|
||||||
|
{
|
||||||
|
client.Timeout = TimeSpan.FromSeconds(15);
|
||||||
|
});
|
||||||
|
|
||||||
builder.Services.AddSingleton<VkApiClient>();
|
builder.Services.AddSingleton<VkApiClient>();
|
||||||
builder.Services.AddSingleton<MappingRepository>();
|
builder.Services.AddSingleton<MappingRepository>();
|
||||||
|
|
||||||
|
builder.Services.AddHealthChecks()
|
||||||
|
.AddCheck<TelegramApiHealthCheck>(
|
||||||
|
name: "telegram",
|
||||||
|
tags: new[] { "telegram" });
|
||||||
|
|
||||||
builder.Services.AddHostedService<ForwardWorker>();
|
builder.Services.AddHostedService<ForwardWorker>();
|
||||||
|
|
||||||
builder.Logging.AddSimpleConsole(options =>
|
builder.Logging.AddSimpleConsole(options =>
|
||||||
@@ -28,8 +41,19 @@ public static class Program
|
|||||||
options.TimestampFormat = "yyyy-MM-dd HH:mm:ss ";
|
options.TimestampFormat = "yyyy-MM-dd HH:mm:ss ";
|
||||||
});
|
});
|
||||||
|
|
||||||
var host = builder.Build();
|
// Убираем «шум» от /health и телеграмных healthcheck-запросов.
|
||||||
await host.RunAsync();
|
// (Это системные info-логи ASP.NET/HttpClient, не логи нашего кода.)
|
||||||
|
builder.Logging.AddFilter("Microsoft.AspNetCore.Routing.EndpointMiddleware", LogLevel.Warning);
|
||||||
|
builder.Logging.AddFilter("Microsoft.AspNetCore.Hosting.Diagnostics", LogLevel.Warning);
|
||||||
|
builder.Logging.AddFilter("Microsoft.Extensions.Diagnostics.HealthChecks", LogLevel.Warning);
|
||||||
|
builder.Logging.AddFilter("System.Net.Http.HttpClient.TelegramHealth", LogLevel.Warning);
|
||||||
|
builder.Logging.AddFilter("System.Net.Http.HttpClient.TelegramBotApi", LogLevel.Warning);
|
||||||
|
|
||||||
|
var app = builder.Build();
|
||||||
|
|
||||||
|
app.MapHealthChecks("/health");
|
||||||
|
app.MapGet("/", () => Results.Redirect("/health"));
|
||||||
|
|
||||||
|
await app.RunAsync().ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk.Worker">
|
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net8.0</TargetFramework>
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
@@ -9,10 +9,7 @@
|
|||||||
<None Update="appsettings.json">
|
<None Update="appsettings.json">
|
||||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||||
</None>
|
</None>
|
||||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="9.0.9" />
|
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.0" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
|
|
||||||
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
|
|
||||||
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.0" />
|
|
||||||
<PackageReference Include="Telegram.Bot" Version="22.9.5.3" />
|
<PackageReference Include="Telegram.Bot" Version="22.9.5.3" />
|
||||||
<PackageReference Include="VkNet" Version="1.78.0" />
|
<PackageReference Include="VkNet" Version="1.78.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
|
namespace Telegram2VkBot;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Проверка доступности Telegram Bot API (getMe).
|
||||||
|
/// </summary>
|
||||||
|
public sealed class TelegramApiHealthCheck : IHealthCheck
|
||||||
|
{
|
||||||
|
public const string HttpClientName = "TelegramHealth";
|
||||||
|
|
||||||
|
private readonly TelegramOptions _telegram;
|
||||||
|
private readonly IHttpClientFactory _httpFactory;
|
||||||
|
|
||||||
|
public TelegramApiHealthCheck(IOptions<TelegramOptions> telegram, IHttpClientFactory httpFactory)
|
||||||
|
{
|
||||||
|
_telegram = telegram.Value;
|
||||||
|
_httpFactory = httpFactory;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<HealthCheckResult> CheckHealthAsync(
|
||||||
|
HealthCheckContext context,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(_telegram.BotToken))
|
||||||
|
return HealthCheckResult.Unhealthy("TELEGRAM__BotToken не задан.");
|
||||||
|
|
||||||
|
var url = $"https://api.telegram.org/bot{_telegram.BotToken}/getMe";
|
||||||
|
var http = _httpFactory.CreateClient(HttpClientName);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var response = await http.GetAsync(url, cancellationToken).ConfigureAwait(false);
|
||||||
|
var json = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
|
if (!response.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
return HealthCheckResult.Unhealthy(
|
||||||
|
$"Telegram API HTTP {(int)response.StatusCode}",
|
||||||
|
data: new Dictionary<string, object> { ["body"] = Truncate(json, 500) });
|
||||||
|
}
|
||||||
|
|
||||||
|
using var doc = JsonDocument.Parse(json);
|
||||||
|
if (!doc.RootElement.TryGetProperty("ok", out var ok) || ok.ValueKind != JsonValueKind.True)
|
||||||
|
{
|
||||||
|
var desc = doc.RootElement.TryGetProperty("description", out var d) ? d.GetString() : json;
|
||||||
|
return HealthCheckResult.Unhealthy($"Telegram getMe: ok=false, {desc}");
|
||||||
|
}
|
||||||
|
|
||||||
|
var username = doc.RootElement.TryGetProperty("result", out var result)
|
||||||
|
&& result.TryGetProperty("username", out var un)
|
||||||
|
? un.GetString()
|
||||||
|
: null;
|
||||||
|
|
||||||
|
return HealthCheckResult.Healthy(
|
||||||
|
username is null ? "Telegram API доступен." : $"Telegram API: @{username}");
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
return HealthCheckResult.Unhealthy("Не удалось связаться с Telegram API.", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Truncate(string s, int max)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(s) || s.Length <= max)
|
||||||
|
return s;
|
||||||
|
return string.Concat(s.AsSpan(0, max), "…");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using System.Net.Http.Headers;
|
using System.Net.Http.Headers;
|
||||||
|
using System.Text.Json;
|
||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using VkNet;
|
using VkNet;
|
||||||
@@ -11,9 +12,8 @@ namespace Telegram2VkBot;
|
|||||||
public sealed class VkApiClient : IDisposable
|
public sealed class VkApiClient : IDisposable
|
||||||
{
|
{
|
||||||
public const string UploadHttpClientName = "VkUpload";
|
public const string UploadHttpClientName = "VkUpload";
|
||||||
private const int LogParamMaxLength = 240;
|
private const string VkApiBaseUrl = "https://api.vk.com/method/";
|
||||||
private const int LogBodyMaxLength = 8192;
|
private const int LogBodyMaxLength = 8192;
|
||||||
private const string MultipartBoundary = "-------0988";
|
|
||||||
|
|
||||||
private readonly VkOptions _options;
|
private readonly VkOptions _options;
|
||||||
private readonly IHttpClientFactory _httpFactory;
|
private readonly IHttpClientFactory _httpFactory;
|
||||||
@@ -134,10 +134,12 @@ public sealed class VkApiClient : IDisposable
|
|||||||
photoBytes.Length,
|
photoBytes.Length,
|
||||||
TruncateForLog(uploadUrl, 512));
|
TruncateForLog(uploadUrl, 512));
|
||||||
|
|
||||||
using var form = new MultipartFormDataContent(MultipartBoundary);
|
// Не задавать свою boundary: нестандартная строка (например «-------0988») часто ломает разбор
|
||||||
|
// multipart на стороне VK → в ответе photo остаётся пустым.
|
||||||
|
using var form = new MultipartFormDataContent();
|
||||||
var bytes = new ByteArrayContent(photoBytes);
|
var bytes = new ByteArrayContent(photoBytes);
|
||||||
bytes.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
|
bytes.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
|
||||||
form.Add(bytes, "photo", $"{Guid.NewGuid():N}.jpg");
|
form.Add(bytes, "photo", "photo.jpg");
|
||||||
|
|
||||||
var http = _httpFactory.CreateClient(UploadHttpClientName);
|
var http = _httpFactory.CreateClient(UploadHttpClientName);
|
||||||
using var uploadResp = await http.PostAsync(uploadUrl, form, ct).ConfigureAwait(false);
|
using var uploadResp = await http.PostAsync(uploadUrl, form, ct).ConfigureAwait(false);
|
||||||
@@ -154,34 +156,110 @@ public sealed class VkApiClient : IDisposable
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
IReadOnlyCollection<Photo> saved;
|
// VkNet иногда «висит» на SaveWallPhoto (внутренний RestClient). Тот же запрос через наш HttpClient с таймаутом.
|
||||||
try
|
var (ownerId, photoId) = await SaveWallPhotoHttpAsync(result, groupIdUlong, ct).ConfigureAwait(false);
|
||||||
{
|
if (ownerId == null || photoId == null)
|
||||||
// Для стены сообщества указываем только group_id. user_id=0 VkNet добавил бы в запрос и VK отклоняет такую связку.
|
|
||||||
saved = await _api.Photo.SaveWallPhotoAsync(
|
|
||||||
response: result,
|
|
||||||
userId: null,
|
|
||||||
groupId: groupIdUlong,
|
|
||||||
caption: null,
|
|
||||||
token: ct)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
}
|
|
||||||
catch (VkApiException ex)
|
|
||||||
{
|
|
||||||
_logger.LogError(ex, "VkNet Photo.SaveWallPhotoAsync failed (VK code {ErrorCode}): {Message}", ex.ErrorCode, ex.Message);
|
|
||||||
throw;
|
|
||||||
}
|
|
||||||
|
|
||||||
var photo = saved.FirstOrDefault();
|
|
||||||
if (photo == null)
|
|
||||||
{
|
|
||||||
_logger.LogWarning("VkNet SaveWallPhoto: пустой результат");
|
|
||||||
return null;
|
return null;
|
||||||
|
|
||||||
|
var attachment = $"photo{ownerId.Value}_{photoId.Value}";
|
||||||
|
_logger.LogInformation("photos.saveWallPhoto → вложение: {Attachment}", attachment);
|
||||||
|
return attachment;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Прямой вызов photos.saveWallPhoto (без VkNet): корректно передаёт длинное поле photo из ответа upload-сервера.
|
||||||
|
/// </summary>
|
||||||
|
private async Task<(long? OwnerId, long? Id)> SaveWallPhotoHttpAsync(
|
||||||
|
string uploadResponseJson,
|
||||||
|
ulong groupId,
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var uploadDoc = JsonDocument.Parse(uploadResponseJson);
|
||||||
|
var root = uploadDoc.RootElement;
|
||||||
|
|
||||||
|
if (!root.TryGetProperty("server", out var serverEl) || !root.TryGetProperty("hash", out var hashEl))
|
||||||
|
{
|
||||||
|
_logger.LogWarning("Ответ upload-сервера без server/hash");
|
||||||
|
return (null, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
var attachment = $"photo{photo.OwnerId}_{photo.Id}";
|
if (!root.TryGetProperty("photo", out var photoEl))
|
||||||
_logger.LogInformation("VkNet SaveWallPhoto response: {Attachment}", attachment);
|
{
|
||||||
return attachment;
|
_logger.LogWarning("Ответ upload-сервера без photo");
|
||||||
|
return (null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
var server = serverEl.ValueKind == JsonValueKind.Number
|
||||||
|
? serverEl.GetInt64().ToString(CultureInfo.InvariantCulture)
|
||||||
|
: serverEl.GetString() ?? "";
|
||||||
|
|
||||||
|
var hash = hashEl.ValueKind == JsonValueKind.String
|
||||||
|
? hashEl.GetString() ?? ""
|
||||||
|
: hashEl.GetRawText();
|
||||||
|
|
||||||
|
var photoParam = photoEl.ValueKind == JsonValueKind.String
|
||||||
|
? photoEl.GetString() ?? ""
|
||||||
|
: photoEl.GetRawText();
|
||||||
|
|
||||||
|
if (string.IsNullOrEmpty(photoParam))
|
||||||
|
{
|
||||||
|
_logger.LogWarning(
|
||||||
|
"Ответ upload-сервера: photo пуст — файл не распознан (multipart). Проверьте загрузку на upload_url.");
|
||||||
|
return (null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogInformation(
|
||||||
|
"photos.saveWallPhoto → group_id={GroupId}, server={Server}, photoLen={PhotoLen}, hashLen={HashLen}",
|
||||||
|
groupId,
|
||||||
|
server,
|
||||||
|
photoParam.Length,
|
||||||
|
hash.Length);
|
||||||
|
|
||||||
|
var query = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["access_token"] = _options.AccessToken,
|
||||||
|
["v"] = _options.ApiVersion,
|
||||||
|
["group_id"] = groupId.ToString(CultureInfo.InvariantCulture),
|
||||||
|
["server"] = server,
|
||||||
|
["photo"] = photoParam,
|
||||||
|
["hash"] = hash,
|
||||||
|
};
|
||||||
|
|
||||||
|
using var content = new FormUrlEncodedContent(query);
|
||||||
|
var http = _httpFactory.CreateClient(UploadHttpClientName);
|
||||||
|
using var resp = await http
|
||||||
|
.PostAsync(VkApiBaseUrl + "photos.saveWallPhoto", content, ct)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
var body = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||||||
|
|
||||||
|
_logger.LogInformation(
|
||||||
|
"photos.saveWallPhoto ← HTTP {StatusCode}, body: {Body}",
|
||||||
|
(int)resp.StatusCode,
|
||||||
|
TruncateForLog(body, LogBodyMaxLength));
|
||||||
|
|
||||||
|
if (!resp.IsSuccessStatusCode)
|
||||||
|
throw new InvalidOperationException($"photos.saveWallPhoto HTTP: {(int)resp.StatusCode} {TruncateForLog(body, 2000)}");
|
||||||
|
|
||||||
|
using var outDoc = JsonDocument.Parse(body);
|
||||||
|
var outRoot = outDoc.RootElement;
|
||||||
|
|
||||||
|
if (outRoot.TryGetProperty("error", out var err))
|
||||||
|
{
|
||||||
|
var code = err.TryGetProperty("error_code", out var ec) ? ec.GetInt32().ToString(CultureInfo.InvariantCulture) : "?";
|
||||||
|
var msg = err.TryGetProperty("error_msg", out var em) ? em.GetString() : null;
|
||||||
|
throw new InvalidOperationException($"photos.saveWallPhoto VK error: code={code} msg={msg}");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!outRoot.TryGetProperty("response", out var response) || response.ValueKind != JsonValueKind.Array || response.GetArrayLength() == 0)
|
||||||
|
{
|
||||||
|
_logger.LogWarning("photos.saveWallPhoto: пустой или неожиданный response");
|
||||||
|
return (null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
var first = response[0];
|
||||||
|
var oid = first.GetProperty("owner_id").GetInt64();
|
||||||
|
var pid = first.GetProperty("id").GetInt64();
|
||||||
|
return (oid, pid);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static readonly Regex PhotoAttachmentRegex = new(@"^photo(-?\d+)_(\d+)$", RegexOptions.Compiled | RegexOptions.CultureInvariant);
|
private static readonly Regex PhotoAttachmentRegex = new(@"^photo(-?\d+)_(\d+)$", RegexOptions.Compiled | RegexOptions.CultureInvariant);
|
||||||
|
|||||||
Reference in new issue
Block a user