chore: init commit from GitHub
Some checks are pending
Deploy / update (push) Waiting to run
Build Project .NET / build (push) Waiting to run

This commit is contained in:
Lisoveliy
2025-05-12 19:44:33 +03:00
parent 11a3f40596
commit aebe654c38
107 changed files with 18953 additions and 403 deletions

366
TelegramBot/.gitignore vendored Normal file
View File

@@ -0,0 +1,366 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# DocFx
/.vscode/
log/
obj/
_site/
.optemp/
_themes/
_themes.MSDN.Modern/
_themes.VS.Modern/
.openpublishing.buildcore.ps1
.openpublishing.redirection.sorted.json
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Folder configuration on Mac
.DS_Store
# Custom added by ghogen
settings.json
telegramconfig.local.json

61
TelegramBot/BotHandler.cs Normal file
View File

@@ -0,0 +1,61 @@
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using TelegramBot.Commands;
using TelegramBot.Commands.CommandMessages;
namespace TelegramBot;
public static class BotHandler
{
private static readonly LinkMessage LinkMessageProvider = new();
private static readonly StartCommandMessage StartCommandMessageProvider = new();
private static readonly ChangelogCommandMessage ChangelogCommandMessageProvider = new();
private static readonly ErrorMessage ErrorMessageProvider = new();
public static async Task HandleUpdateAsync(
ITelegramBotClient botClient,
Update update,
CancellationToken cancellationToken
)
{
switch (update.Type)
{
case UpdateType.Message:
switch (update.Message?.Text)
{
case StartCommandMessage.CommandName:
await StartCommandMessageProvider.InvokeFromMessage(botClient, update, cancellationToken);
break;
case ChangelogCommandMessage.CommandName:
await ChangelogCommandMessageProvider.InvokeFromMessage(botClient, update, cancellationToken);
break;
default:
Console.WriteLine(update.Message?.Text);
if (string.IsNullOrEmpty(update.Message?.Text))
{
await ErrorMessageProvider.InvokeFromMessage(botClient, update, cancellationToken);
break;
}
await LinkMessageProvider.InvokeFromMessage(botClient, update, cancellationToken);
break;
}
break;
case UpdateType.InlineQuery:
await LinkMessageProvider.InvokeFromInlineQuery(botClient, update, cancellationToken);
break;
}
}
public static Task HandleErrorAsync(
ITelegramBotClient botClient,
Exception exception,
CancellationToken cancellationToken
)
{
Console.WriteLine("Ошибка ядра:\n--------------------------");
Console.WriteLine(exception);
return Task.CompletedTask;
// throw exception;
}
}

View File

@@ -0,0 +1,20 @@
using System.Text;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
namespace TelegramBot.Commands.CommandMessages;
public class ChangelogCommandMessage : CommandMessage
{
public const string CommandName = "/changelog";
public override async Task InvokeFromMessage(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{
var text = new StringBuilder();
foreach (var log in Program.Config.Changelog)
{
text.Append($"Нововведения от <b>{log.Date}</b>:\n\n{log.Caption}\n\n");
}
await botClient.SendTextMessageAsync(update.Message?.Chat!, text.ToString(), cancellationToken: cancellationToken, parseMode: ParseMode.Html);
}
}

View File

@@ -0,0 +1,12 @@
using System.Diagnostics;
using System.Reflection;
using Telegram.Bot;
using Telegram.Bot.Types;
namespace TelegramBot.Commands.CommandMessages;
public abstract class CommandMessage : IMessage
{
public abstract Task InvokeFromMessage(ITelegramBotClient botClient, Update update,
CancellationToken cancellationToken);
}

View File

@@ -0,0 +1,20 @@
using System.Diagnostics;
using System.Reflection;
using Telegram.Bot;
using Telegram.Bot.Types;
namespace TelegramBot.Commands.CommandMessages;
public class StartCommandMessage : CommandMessage
{
public const string CommandName = "/start";
public override async Task InvokeFromMessage(ITelegramBotClient botClient,
Update update,
CancellationToken cancellationToken)
{
var text = Program.Config.StartMessage;
text += $"\nBuild assembly version: {FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion}";
text += $"\n\nНововведения по комманде /changelog";
await botClient.SendTextMessageAsync(update.Message?.Chat!, text, cancellationToken: cancellationToken);
}
}

View File

@@ -0,0 +1,12 @@
using Telegram.Bot;
using Telegram.Bot.Types;
namespace TelegramBot.Commands;
public class ErrorMessage : IMessage
{
public async Task InvokeFromMessage(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{
await botClient.SendTextMessageAsync(update.Message?.Chat!, "Ошибка! Команда не найдена", cancellationToken: cancellationToken);
}
}

View File

@@ -0,0 +1,11 @@
using Telegram.Bot;
using Telegram.Bot.Types;
namespace TelegramBot.Commands;
public interface IMessage
{
public Task InvokeFromMessage(ITelegramBotClient botClient,
Update update,
CancellationToken cancellationToken);
}

View File

@@ -0,0 +1,98 @@
using System.Net.Http.Json;
using System.Text;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.InlineQueryResults;
using TelegramBot.DTOs;
namespace TelegramBot.Commands;
public class LinkMessage : IMessage
{
/// <summary>
/// Create message from API
/// </summary>
/// <param name="botClient"></param>
/// <param name="inputUrl"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
async Task<(string? message, string? preview)> GetMessage(ITelegramBotClient botClient, string inputUrl,
CancellationToken cancellationToken)
{
try
{
using var client = new HttpClient();
var res = await client.GetAsync($"{Program.Config.ApiPath}/link/getService?link=" + inputUrl,
cancellationToken);
var typeRes = await res.Content.ReadFromJsonAsync<GetLink>(cancellationToken: cancellationToken);
if (!res.IsSuccessStatusCode)
{
return (string.Empty, $"Произошла ошибка при обработке запроса\n{res.StatusCode.ToString()}");
}
var message = new StringBuilder();
var preview = new StringBuilder();
foreach (var service in typeRes?.service.Another()!)
{
res = await client.PostAsJsonAsync($"{Program.Config.ApiPath}/link/fromLink", new
{
link = inputUrl,
service,
}, cancellationToken: cancellationToken);
if (!res.IsSuccessStatusCode)
{
preview.AppendLine($"❌ {service}\n");
message.AppendLine(
$"❌ {service}: 🤨👨🏿‍🦰😡😮‍💨😰 {(await res.Content.ReadFromJsonAsync<ErrorDto>(cancellationToken: cancellationToken))?.title}");
message.AppendLine();
continue;
}
var apiRes = await res.Content.ReadFromJsonAsync<LinkDto>(cancellationToken: cancellationToken);
preview.AppendLine($"✅ {service}\n");
message.AppendLine($"✅ {service} - {apiRes?.link}");
message.AppendLine();
}
return (message.ToString(), preview.ToString());
}
catch (Exception e)
{
Console.WriteLine("Ошибка:\n--------------------------");
Console.WriteLine(e);
return (e.ToString(), "Произошла ошибка при обработке запроса\nдетали в сообщении");
}
}
public async Task InvokeFromMessage(ITelegramBotClient botClient, Update update,
CancellationToken cancellationToken)
{
var result = (await GetMessage(botClient, update.Message?.Text!, cancellationToken)).message;
await botClient.SendTextMessageAsync(update.Message?.Chat!, string.IsNullOrEmpty(result) ? "Ошибка🤔:\nНе удалось определить сервис исходной ссылки.\nДоступные сервисы для конвертации:\nTidal\nYandex\nSpotify" : result, cancellationToken: cancellationToken);
}
public async Task InvokeFromInlineQuery(ITelegramBotClient botClient, Update update,
CancellationToken cancellationToken)
{
if(string.IsNullOrEmpty(update.InlineQuery!.Query))
return;
var message = await new LinkMessage().GetMessage(botClient, update.InlineQuery!.Query, cancellationToken);
if(message.message != null)
try
{
await botClient.AnswerInlineQueryAsync(update.InlineQuery.Id,
new[]
{
new InlineQueryResultArticle("0", message.preview!,
new InputTextMessageContent(message.message))
}, cancellationToken: cancellationToken);
}
catch (Exception e)
{
Console.WriteLine($"Failed to send answer to {update.Message?.Chat.Username}");
}
}
}

View File

@@ -0,0 +1,15 @@
namespace TelegramBot.Config;
public class AppSettings
{
public string? Token { get; init; }
public string? ApiPath { get; init; }
public string? StartMessage { get; init; }
public List<Changelog> Changelog { get; init; } = null!;
}
public class Changelog
{
public string? Date { get; init; }
public string? Caption { get; init; }
}

View File

@@ -0,0 +1,15 @@
using SWAD.API.Consts.Enums;
namespace TelegramBot.DTOs;
public record GetLink(
MusicService service
);
public record LinkDto(
string? link
);
public record ErrorDto(
string title
);

15
TelegramBot/Dockerfile Normal file
View File

@@ -0,0 +1,15 @@
# https://hub.docker.com/_/microsoft-dotnet
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /source
# copy csproj and restore as distinct layers
COPY ./ ./
RUN dotnet restore
WORKDIR /source/TelegramBot
RUN dotnet publish -c release -o /app --no-restore
# final stage/image
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY --from=build /app ./
ENTRYPOINT ["dotnet", "/app/TelegramBot.dll"]

View File

@@ -0,0 +1,13 @@
using SWAD.API.Consts.Enums;
namespace TelegramBot;
public static class EnumExtensions
{
public static List<MusicService> Another(this MusicService service)
{
var list = Enum.GetValues<MusicService>().ToList();
list.Remove(service);
return list;
}
}

71
TelegramBot/Program.cs Normal file
View File

@@ -0,0 +1,71 @@
using System.Diagnostics;
using System.Reflection;
using Microsoft.Extensions.Logging;
using Telegram.Bot;
using Telegram.Bot.Polling;
using Microsoft.Extensions.Configuration;
using TelegramBot.Config;
namespace TelegramBot;
public static class Program
{
private static ILogger Logger { get; } = LoggerFactory.Create(x => { x.AddConsole(); })
.CreateLogger("MainThread");
private static ITelegramBotClient bot { get; set; }
public static AppSettings Config { get; private set; }
public static void Main()
{
Splash(Logger);
LoadConfig();
var cts = LoadBot();
while(!cts.IsCancellationRequested)
Thread.Sleep(1000);
}
private static void Splash(ILogger logger)
{
var splash = """
____ ____ _ ____ _
/ ___|_ ____ _ _ __ | _ \ _ _ __| | ___ | __ ) ___ | |_
\___ \ \ /\ / / _` | '_ \| | | | | | |/ _` |/ _ \ | _ \ / _ \| __|
___) \ V V / (_| | |_) | |_| | |_| | (_| | __/_| |_) | (_) | |_
|____/ \_/\_/ \__,_| .__/|____/ \__,_|\__,_|\___(_)____/ \___/ \__|
|_|
""";
logger.LogWarning(splash);
logger.LogInformation(
$"Build assembly version: {FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion}");
}
private static void LoadConfig()
{
Logger.LogInformation("Loading config...");
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddJsonFile("telegramconfig.json", optional: false)
#if DEBUG
.AddJsonFile("telegramconfig.local.json", true, true)
#endif
.Build();
Config = configuration.GetSection("AppSettings").Get<AppSettings>() ?? throw new NullReferenceException();
}
private static CancellationTokenSource LoadBot()
{
Logger.LogInformation("Creating bot...");
bot = new TelegramBotClient(Config.Token ?? throw new NullReferenceException());
var cts = new CancellationTokenSource();
var receiverOptions = new ReceiverOptions
{
AllowedUpdates = { }
};
bot.StartReceiving(BotHandler.HandleUpdateAsync,
BotHandler.HandleErrorAsync, receiverOptions, cts.Token);
return cts;
}
}

View File

@@ -0,0 +1,47 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<VersionSuffix>0.1.$([System.DateTime]::UtcNow.ToString(MMdd)).$([System.DateTime]::Now.ToString(HHmm))</VersionSuffix>
<AssemblyVersion Condition=" '$(VersionSuffix)' == '' ">0.0.0.1</AssemblyVersion>
<AssemblyVersion Condition=" '$(VersionSuffix)' != '' ">$(VersionSuffix)</AssemblyVersion>
<Version Condition=" '$(VersionSuffix)' == '' ">0.0.1.0</Version>
<Version Condition=" '$(VersionSuffix)' != '' ">$(VersionSuffix)</Version>
<Company>SpectruMTeamCode</Company>
<Authors>Lisoveliy, Sluppy(Gl3b4ty)</Authors>
<Copyright>Copyright © $(Company) $([System.DateTime]::UtcNow.ToString(yyyy))</Copyright>
<Product>SWAD Platform</Product>
<Description>Platform for sharing music links from one music service to another for free! (REST API Back-end)</Description>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
<PackageReference Include="Telegram.Bot" Version="19.0.0" />
<PackageReference Include="Telegram.Bots.Extensions.Polling" Version="5.9.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SWAD.API\SWAD.API.csproj" />
</ItemGroup>
<ItemGroup>
<None Remove="telegramconfig.json" />
<Content Include="telegramconfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Update="telegramconfig.local.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<None Remove="telegramconfig.local.json" />
<Content Include="telegramconfig.local.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,16 @@
{
"AppSettings": {
"Token": "INSERT TOKEN HERE",
"ApiPath": "http://api:8080",
"StartMessage": "Привет. Я бот https://swapdude.pro! Я помогу отправить твоим друзьям ссылку на песню с других сервисов! Просто пришли ссылку (Spotify, Yandex, Tidal) и я сконвертирую её в 2 других сервиса.\n(BETA)",
"Changelog": [
{
"Date": "08.05.2024",
"Caption": "Напиши в любом чате @swapdudebot и вставь ссылку прямо в сообщение а после нажми на кнопку над сообщением. Это избавит тебя от необходимости заходить в бот каждый раз когда тебе нужно будет скинуть трек своим друзьям!"
},
{
"Date": "22.08.2024",
"Caption": "-Улучшена стабильность бота\n-Добавлено отображение статуса поиска трека в разных сервисах при однострочном(inline запросе)"
}]
}
}