This commit is contained in:
kislovdm
2024-02-12 20:15:59 +03:00
commit 6055fcede4
15 changed files with 553 additions and 0 deletions
+25
View File
@@ -0,0 +1,25 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.8.34330.188
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sibur.BuggyBot", "Sibur.BuggyBot\Sibur.BuggyBot.csproj", "{818B0609-5FDB-41F0-9050-372CB57AD751}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{818B0609-5FDB-41F0-9050-372CB57AD751}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{818B0609-5FDB-41F0-9050-372CB57AD751}.Debug|Any CPU.Build.0 = Debug|Any CPU
{818B0609-5FDB-41F0-9050-372CB57AD751}.Release|Any CPU.ActiveCfg = Release|Any CPU
{818B0609-5FDB-41F0-9050-372CB57AD751}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {8D20BDBE-4209-43B8-812E-9300EAC636BD}
EndGlobalSection
EndGlobal
+41
View File
@@ -0,0 +1,41 @@
using Sibur.BuggyBot.Messaging;
using System;
using Telegram.Bot.Types;
namespace Sibur.BuggyBot.App;
public class App : IApp
{
private readonly ITelegram _telegram;
private readonly Random _random;
private readonly string[] _assignee = new[] { "yaprostosplu", "RobinsonBastard" };
public App(ITelegram telegram)
{
_telegram = telegram;
_telegram.Start().GetAwaiter().GetResult();
_telegram.MessageHook = OnMessage;
_random = new Random();
}
private async Task OnMessage(Message message)
{
if (message.Text?.StartsWith($"@{_telegram.NickName}") == true)
{
var assignee = _assignee[_random.Next(0, _assignee.Length)];
var msg = $"@{assignee}, прошу взять в работу.";
await _telegram.SendMessageAsync(message.Chat.Id, msg, replyToMessageId: message.MessageId);
}
Console.WriteLine($"[{message.From?.Id}] {message.Text}");
}
public async Task RunAsync()
{
while (true)
{
await Task.Delay(TimeSpan.FromSeconds(1));
}
}
}
+6
View File
@@ -0,0 +1,6 @@
namespace Sibur.BuggyBot.App;
public interface IApp
{
Task RunAsync();
}
+43
View File
@@ -0,0 +1,43 @@
using Autofac;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using NLog;
using Sibur.BuggyBot.App;
using Sibur.BuggyBot.Messaging;
using Sibur.BuggyBot.Settings;
using Telegram.Bot;
namespace Sibur.BuggyBot.Di;
public class DI
{
public IContainer Build()
{
var container = new ContainerBuilder();
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.Build();
container.Register(c => config).As<IConfiguration>().SingleInstance();
container.RegisterType<Messaging.Telegram>().As<ITelegram>().SingleInstance();
container.RegisterType<App.App>().As<IApp>();
container.Register(c =>
{
var settings = c.Resolve<IConfiguration>().GetSection("Telegram").Get<TelegramSettings>()!; ;
Console.WriteLine(JsonConvert.SerializeObject(settings));
return settings;
})
.As<TelegramSettings>().SingleInstance();
container.Register(c => LogManager.GetLogger("main")).As<ILogger>();
container.Register(c =>
{
var client = new TelegramBotClient(c.Resolve<TelegramSettings>().Token);
return client;
}).AsSelf().SingleInstance();
return container.Build();
}
}
+26
View File
@@ -0,0 +1,26 @@
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups;
namespace Sibur.BuggyBot.Messaging;
public interface ITelegram
{
Task Start();
public Func<Message, Task>? MessageHook { get; set; }
public string? NickName { get; set; }
Task SendMessageAsync(
ChatId chatId,
string text,
int? messageThreadId = default,
ParseMode? parseMode = default,
IEnumerable<MessageEntity>? entities = default,
bool? disableWebPagePreview = default,
bool? disableNotification = default,
bool? protectContent = default,
int? replyToMessageId = default,
bool? allowSendingWithoutReply = default,
IReplyMarkup? replyMarkup = default,
CancellationToken cancellationToken = default);
}
+58
View File
@@ -0,0 +1,58 @@
using NLog;
using Telegram.Bot;
using Telegram.Bot.Polling;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups;
namespace Sibur.BuggyBot.Messaging
{
public sealed class Telegram: ITelegram
{
private readonly TelegramBotClient _telegram;
private readonly ILogger _logger;
public Func<Message, Task>? MessageHook { get; set; } = null;
public string? NickName { get; set; } = null;
public Telegram(TelegramBotClient telegram, ILogger logger)
{
_telegram = telegram;
_logger = logger;
}
public async Task Start()
{
var cts = new CancellationTokenSource();
_telegram.StartReceiving(updateHandler: HandleUpdateAsync,
pollingErrorHandler: PollingErrorHandler,
receiverOptions: new ReceiverOptions(),
cancellationToken: cts.Token);
NickName = (await _telegram.GetMeAsync(cancellationToken: cts.Token)).Username;
}
private void PollingErrorHandler(ITelegramBotClient arg1, Exception arg2, CancellationToken arg3)
{
}
private void HandleUpdateAsync(ITelegramBotClient arg1, Update update, CancellationToken arg3)
{
if (update.Message != null)
{
_logger.Info($"{update.Message.Chat.Id}: {update.Message.Text}");
MessageHook?.Invoke(update.Message);
}
}
public Task SendMessageAsync(ChatId chatId, string text, int? messageThreadId = default, ParseMode? parseMode = default,
IEnumerable<MessageEntity>? entities = default, bool? disableWebPagePreview = default, bool? disableNotification = default,
bool? protectContent = default, int? replyToMessageId = default, bool? allowSendingWithoutReply = default,
IReplyMarkup? replyMarkup = default, CancellationToken cancellationToken = default)
{
return _telegram.SendTextMessageAsync(chatId, text, messageThreadId, parseMode, entities, disableWebPagePreview,
disableNotification, protectContent, replyToMessageId, allowSendingWithoutReply, replyMarkup, cancellationToken);
}
}
}
+18
View File
@@ -0,0 +1,18 @@
<?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">
<targets>
<target name="coloredConsole" xsi:type="ColoredConsole" useDefaultRowHighlightingRules="false"
layout="${longdate}|${pad:padding=5:inner=${level:uppercase=true}}|${message}" >
<highlight-row condition="level == LogLevel.Debug" foregroundColor="DarkGray" />
<highlight-row condition="level == LogLevel.Info" foregroundColor="Gray" />
<highlight-row condition="level == LogLevel.Warn" foregroundColor="Yellow" />
<highlight-row condition="level == LogLevel.Error" foregroundColor="Red" />
<highlight-row condition="level == LogLevel.Fatal" foregroundColor="Red" backgroundColor="White" />
</target>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="coloredConsole" />
</rules>
</nlog>
+14
View File
@@ -0,0 +1,14 @@
using Autofac;
using Sibur.BuggyBot.App;
using Sibur.BuggyBot.Di;
class Program
{
static async Task Main(string[] args)
{
var container = new DI().Build();
var app = container.Resolve<IApp>();
await app.RunAsync();
}
}
@@ -0,0 +1,6 @@
namespace Sibur.BuggyBot.Settings;
public sealed class TelegramSettings
{
public string Token { get; init; } = "";
}
+30
View File
@@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Autofac" Version="8.0.0" />
<PackageReference Include="NLog" Version="5.2.8" />
<PackageReference Include="Telegram.Bot" Version="19.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="NLog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
+6
View File
@@ -0,0 +1,6 @@
{
"urls": "http://*:80",
"Telegram": {
"Token": ""
}
}