From 8917a8ba5fcb9da0dc4647643ba2df2a20250fad Mon Sep 17 00:00:00 2001 From: Andriy <30056636+West14@users.noreply.github.com> Date: Sun, 9 Feb 2025 15:47:52 +0200 Subject: [PATCH 01/12] chore: drop unused modules These two are making lots of problems during update process: the `ChatQuotes` one was never operational and the `Destiny2.WhereIsXur` became obsolete, since Xur was granted his permanent place on the Tower --- Dockerfile | 2 - Kruzya.TelegramBot.sln | 14 ----- modules/ChatQuotes/ChatQuotes.cs | 31 ---------- modules/ChatQuotes/ChatQuotes.csproj | 22 -------- modules/ChatQuotes/Handler/Quote.cs | 38 ------------- .../Json/NullToEmptyObjectResolver.cs | 17 ------ .../Json/NullToEmptyObjectValueProvider.cs | 26 --------- modules/ChatQuotes/Model/Quote/MediaType.cs | 6 -- modules/ChatQuotes/Model/Quote/Message.cs | 56 ------------------- modules/ChatQuotes/Model/Quote/Request.cs | 35 ------------ modules/ChatQuotes/Model/Quote/Response.cs | 16 ------ modules/ChatQuotes/Model/Quote/Result.cs | 13 ----- modules/ChatQuotes/Model/Quote/Type.cs | 8 --- modules/ChatQuotes/Model/User.cs | 22 -------- modules/ChatQuotes/QuoteGeneratorService.cs | 41 -------------- .../Destiny2.WhereIsXur.csproj | 18 ------ .../Provider/IXurPlaceProvider.cs | 9 --- .../Destiny2.WhereIsXur/Provider/XurWiki.cs | 27 --------- modules/Destiny2.WhereIsXur/RequestHandler.cs | 36 ------------ modules/Destiny2.WhereIsXur/WhereIsXur.cs | 17 ------ 20 files changed, 454 deletions(-) delete mode 100644 modules/ChatQuotes/ChatQuotes.cs delete mode 100644 modules/ChatQuotes/ChatQuotes.csproj delete mode 100644 modules/ChatQuotes/Handler/Quote.cs delete mode 100644 modules/ChatQuotes/Json/NullToEmptyObjectResolver.cs delete mode 100644 modules/ChatQuotes/Json/NullToEmptyObjectValueProvider.cs delete mode 100644 modules/ChatQuotes/Model/Quote/MediaType.cs delete mode 100644 modules/ChatQuotes/Model/Quote/Message.cs delete mode 100644 modules/ChatQuotes/Model/Quote/Request.cs delete mode 100644 modules/ChatQuotes/Model/Quote/Response.cs delete mode 100644 modules/ChatQuotes/Model/Quote/Result.cs delete mode 100644 modules/ChatQuotes/Model/Quote/Type.cs delete mode 100644 modules/ChatQuotes/Model/User.cs delete mode 100644 modules/ChatQuotes/QuoteGeneratorService.cs delete mode 100644 modules/Destiny2.WhereIsXur/Destiny2.WhereIsXur.csproj delete mode 100644 modules/Destiny2.WhereIsXur/Provider/IXurPlaceProvider.cs delete mode 100644 modules/Destiny2.WhereIsXur/Provider/XurWiki.cs delete mode 100644 modules/Destiny2.WhereIsXur/RequestHandler.cs delete mode 100644 modules/Destiny2.WhereIsXur/WhereIsXur.cs diff --git a/Dockerfile b/Dockerfile index 5f16d55..83ea206 100644 --- a/Dockerfile +++ b/Dockerfile @@ -7,13 +7,11 @@ COPY Kruzya.TelegramBot.sln ./ COPY ./Core/*.csproj ./Core/ COPY ./tests/*.csproj ./tests/ COPY ./modules/CombotAntiSpam/*.csproj ./modules/CombotAntiSpam/ -COPY ./modules/Destiny2.WhereIsXur/*.csproj ./modules/Destiny2.WhereIsXur/ COPY ./modules/RichSiteSummary/*.csproj ./modules/RichSiteSummary/ COPY ./modules/UrlLimitations/*.csproj ./modules/UrlLimitations/ COPY ./modules/ChatManagement/*.csproj ./modules/ChatManagement/ COPY ./modules/Entertainment/*.csproj ./modules/Entertainment/ COPY ./modules/UserGroupTag/*.csproj ./modules/UserGroupTag/ -COPY ./modules/ChatQuotes/*.csproj ./modules/ChatQuotes/ COPY ./modules/Reputation/*.csproj ./modules/Reputation/ COPY ./modules/ContentStore/*.csproj ./modules/ContentStore/ COPY ./modules/DebugTools/*.csproj ./modules/DebugTools/ diff --git a/Kruzya.TelegramBot.sln b/Kruzya.TelegramBot.sln index 3dc09f6..7a6e911 100644 --- a/Kruzya.TelegramBot.sln +++ b/Kruzya.TelegramBot.sln @@ -15,16 +15,12 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Tests", "tests\Tests.csproj EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UrlLimitations", "modules\UrlLimitations\UrlLimitations.csproj", "{B82E3339-3B34-4600-8C59-C5A3640B1982}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Destiny2.WhereIsXur", "modules\Destiny2.WhereIsXur\Destiny2.WhereIsXur.csproj", "{AE782132-BED8-4D1E-98FA-CB768171D332}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ChatManagement", "modules\ChatManagement\ChatManagement.csproj", "{55ACF7F7-409A-45EE-A41D-D8417DE7EAA7}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UserGroupTag", "modules\UserGroupTag\UserGroupTag.csproj", "{5B89E22A-78CF-4037-BE0D-5F88EF47022B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Entertainment", "modules\Entertainment\Entertainment.csproj", "{1D62101B-C2B1-4E79-8F7A-690E44E3EE81}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ChatQuotes", "modules\ChatQuotes\ChatQuotes.csproj", "{04F16325-8F44-4250-9B2E-0F77E8F65CBF}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Reputation", "modules\Reputation\Reputation.csproj", "{03F3C7D5-6FEF-4A83-9191-501091BFC1AC}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ContentStore", "modules\ContentStore\ContentStore.csproj", "{4F1E8FE8-640F-4671-87FC-0FFCCB6EDF5E}" @@ -61,10 +57,6 @@ Global {B82E3339-3B34-4600-8C59-C5A3640B1982}.Debug|Any CPU.Build.0 = Debug|Any CPU {B82E3339-3B34-4600-8C59-C5A3640B1982}.Release|Any CPU.ActiveCfg = Release|Any CPU {B82E3339-3B34-4600-8C59-C5A3640B1982}.Release|Any CPU.Build.0 = Release|Any CPU - {AE782132-BED8-4D1E-98FA-CB768171D332}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {AE782132-BED8-4D1E-98FA-CB768171D332}.Debug|Any CPU.Build.0 = Debug|Any CPU - {AE782132-BED8-4D1E-98FA-CB768171D332}.Release|Any CPU.ActiveCfg = Release|Any CPU - {AE782132-BED8-4D1E-98FA-CB768171D332}.Release|Any CPU.Build.0 = Release|Any CPU {55ACF7F7-409A-45EE-A41D-D8417DE7EAA7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {55ACF7F7-409A-45EE-A41D-D8417DE7EAA7}.Debug|Any CPU.Build.0 = Debug|Any CPU {55ACF7F7-409A-45EE-A41D-D8417DE7EAA7}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -77,10 +69,6 @@ Global {1D62101B-C2B1-4E79-8F7A-690E44E3EE81}.Debug|Any CPU.Build.0 = Debug|Any CPU {1D62101B-C2B1-4E79-8F7A-690E44E3EE81}.Release|Any CPU.ActiveCfg = Release|Any CPU {1D62101B-C2B1-4E79-8F7A-690E44E3EE81}.Release|Any CPU.Build.0 = Release|Any CPU - {04F16325-8F44-4250-9B2E-0F77E8F65CBF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {04F16325-8F44-4250-9B2E-0F77E8F65CBF}.Debug|Any CPU.Build.0 = Debug|Any CPU - {04F16325-8F44-4250-9B2E-0F77E8F65CBF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {04F16325-8F44-4250-9B2E-0F77E8F65CBF}.Release|Any CPU.Build.0 = Release|Any CPU {03F3C7D5-6FEF-4A83-9191-501091BFC1AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03F3C7D5-6FEF-4A83-9191-501091BFC1AC}.Debug|Any CPU.Build.0 = Debug|Any CPU {03F3C7D5-6FEF-4A83-9191-501091BFC1AC}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -109,11 +97,9 @@ Global {F1E1FBB7-ABA4-4304-9A42-D4975822B002} = {C7821F15-DEDD-474F-A575-A296D4B58F10} {C50D64C3-204B-4B58-927B-C8D759787252} = {C7821F15-DEDD-474F-A575-A296D4B58F10} {B82E3339-3B34-4600-8C59-C5A3640B1982} = {C7821F15-DEDD-474F-A575-A296D4B58F10} - {AE782132-BED8-4D1E-98FA-CB768171D332} = {C7821F15-DEDD-474F-A575-A296D4B58F10} {55ACF7F7-409A-45EE-A41D-D8417DE7EAA7} = {C7821F15-DEDD-474F-A575-A296D4B58F10} {5B89E22A-78CF-4037-BE0D-5F88EF47022B} = {C7821F15-DEDD-474F-A575-A296D4B58F10} {1D62101B-C2B1-4E79-8F7A-690E44E3EE81} = {C7821F15-DEDD-474F-A575-A296D4B58F10} - {04F16325-8F44-4250-9B2E-0F77E8F65CBF} = {C7821F15-DEDD-474F-A575-A296D4B58F10} {03F3C7D5-6FEF-4A83-9191-501091BFC1AC} = {C7821F15-DEDD-474F-A575-A296D4B58F10} {4F1E8FE8-640F-4671-87FC-0FFCCB6EDF5E} = {C7821F15-DEDD-474F-A575-A296D4B58F10} {B95C9180-4893-4A33-BF43-AB2EE998650C} = {C7821F15-DEDD-474F-A575-A296D4B58F10} diff --git a/modules/ChatQuotes/ChatQuotes.cs b/modules/ChatQuotes/ChatQuotes.cs deleted file mode 100644 index 95addda..0000000 --- a/modules/ChatQuotes/ChatQuotes.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System.Globalization; -using Kruzya.TelegramBot.Core; -using Microsoft.Extensions.DependencyInjection; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Serialization; -using West.TelegramBot.ChatQuotes.Json; - -namespace West.TelegramBot.ChatQuotes; - -public class ChatQuotes : Module -{ - public static readonly JsonSerializerSettings SerializerSettings = new() - { - MetadataPropertyHandling = MetadataPropertyHandling.Ignore, - DateParseHandling = DateParseHandling.None, - Converters = - { - new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }, - new StringEnumConverter(new CamelCaseNamingStrategy()) - }, - ContractResolver = new NullToEmptyObjectResolver() - }; - - public ChatQuotes(Core core) : base(core) { } - - public override void ConfigureServices(IServiceCollection services) - { - services.AddSingleton(); - } -} \ No newline at end of file diff --git a/modules/ChatQuotes/ChatQuotes.csproj b/modules/ChatQuotes/ChatQuotes.csproj deleted file mode 100644 index 7dbc820..0000000 --- a/modules/ChatQuotes/ChatQuotes.csproj +++ /dev/null @@ -1,22 +0,0 @@ - - - - net8.0 - enable - enable - West.TelegramBot.ChatQuotes - TelegramBot.ChatQuotes - - - - - - - - - - - - - - diff --git a/modules/ChatQuotes/Handler/Quote.cs b/modules/ChatQuotes/Handler/Quote.cs deleted file mode 100644 index eadc57c..0000000 --- a/modules/ChatQuotes/Handler/Quote.cs +++ /dev/null @@ -1,38 +0,0 @@ -using BotFramework; -using BotFramework.Attributes; -using BotFramework.Enums; -using Telegram.Bot; -using Telegram.Bot.Types; - -namespace West.TelegramBot.ChatQuotes.Handler; - -public class Quote : BotEventHandler -{ - private readonly QuoteGeneratorService _quoteGenerator; - - public Quote(QuoteGeneratorService quoteGenerator) - { - _quoteGenerator = quoteGenerator; - } - - [InChat(InChat.Public)] - [Command("q", CommandParseMode.Both)] - public async Task HandleQuote() - { - var msg = RawUpdate.Message; - var replyToMessage = msg?.ReplyToMessage; - if (msg == null || replyToMessage == null) - { - return; - } - - var quoteImage = await _quoteGenerator.GenerateQuoteImage(replyToMessage); - if (quoteImage == null) - { - return; - } - - await Bot.SendStickerAsync(Chat.Id, new InputFile(quoteImage), - replyToMessageId: msg.MessageId); - } -} \ No newline at end of file diff --git a/modules/ChatQuotes/Json/NullToEmptyObjectResolver.cs b/modules/ChatQuotes/Json/NullToEmptyObjectResolver.cs deleted file mode 100644 index 4a06d91..0000000 --- a/modules/ChatQuotes/Json/NullToEmptyObjectResolver.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; - -namespace West.TelegramBot.ChatQuotes.Json; - -class NullToEmptyObjectResolver : DefaultContractResolver -{ - protected override IList CreateProperties(Type type, MemberSerialization memberSerialization) - { - return type.GetProperties() - .Select(p => { - var jp = base.CreateProperty(p, memberSerialization); - jp.ValueProvider = new NullToEmptyObjectValueProvider(p); - return jp; - }).ToList(); - } -} \ No newline at end of file diff --git a/modules/ChatQuotes/Json/NullToEmptyObjectValueProvider.cs b/modules/ChatQuotes/Json/NullToEmptyObjectValueProvider.cs deleted file mode 100644 index cb6d497..0000000 --- a/modules/ChatQuotes/Json/NullToEmptyObjectValueProvider.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System.Reflection; -using Newtonsoft.Json.Serialization; -using Telegram.Bot.Types; - -namespace West.TelegramBot.ChatQuotes.Json; - -public class NullToEmptyObjectValueProvider : IValueProvider -{ - private readonly PropertyInfo _memberInfo; - public NullToEmptyObjectValueProvider(PropertyInfo memberInfo) - { - _memberInfo = memberInfo; - } - - public object? GetValue(object target) - { - var result = _memberInfo.GetValue(target); - if (_memberInfo.PropertyType == typeof(Message) && result == null) result = new object(); - return result; - } - - public void SetValue(object target, object? value) - { - _memberInfo.SetValue(target, value); - } -} \ No newline at end of file diff --git a/modules/ChatQuotes/Model/Quote/MediaType.cs b/modules/ChatQuotes/Model/Quote/MediaType.cs deleted file mode 100644 index 10b63a9..0000000 --- a/modules/ChatQuotes/Model/Quote/MediaType.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace West.TelegramBot.ChatQuotes.Model.Quote; - -public enum MediaType -{ - Sticker = 0 -} \ No newline at end of file diff --git a/modules/ChatQuotes/Model/Quote/Message.cs b/modules/ChatQuotes/Model/Quote/Message.cs deleted file mode 100644 index b3bf0b7..0000000 --- a/modules/ChatQuotes/Model/Quote/Message.cs +++ /dev/null @@ -1,56 +0,0 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using File = Telegram.Bot.Types.File; -using TgUser = Telegram.Bot.Types.User; - -namespace West.TelegramBot.ChatQuotes.Model.Quote; - -[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))] -public class Message -{ - public List? Media { get; set; } - public MediaType? MediaType { get; set; } - public long ChatId { get; set; } - public bool Avatar { get; set; } = true; - public User? From { get; set; } - public string? Text { get; set; } - public Telegram.Bot.Types.Message? ReplyMessage { get; set; } - - public static Message FromMessage(Telegram.Bot.Types.Message msg) - { - var quoteMessage = new Message(); - - if (msg.Text != null) - { - quoteMessage.Text = msg.Text; - } - - var sticker = msg.Sticker; - if (sticker != null) - { - var file = new File - { - FileId = sticker.FileId, - FileSize = sticker.FileSize, - FileUniqueId = sticker.FileUniqueId - }; - quoteMessage.Media = new List { file }; - quoteMessage.MediaType = Quote.MediaType.Sticker; - } - - TgUser? user = null; - if (msg.ForwardSenderName != null && msg.ForwardFrom == null) - { - user = new TgUser - { - FirstName = msg.ForwardSenderName - }; - } - - quoteMessage.ChatId = msg.From?.Id ?? msg.Chat.Id; - quoteMessage.ReplyMessage = msg.ReplyToMessage; - quoteMessage.From = User.FromTgUser(user ?? msg.ForwardFrom ?? msg.From!); - - return quoteMessage; - } -} \ No newline at end of file diff --git a/modules/ChatQuotes/Model/Quote/Request.cs b/modules/ChatQuotes/Model/Quote/Request.cs deleted file mode 100644 index 2a68390..0000000 --- a/modules/ChatQuotes/Model/Quote/Request.cs +++ /dev/null @@ -1,35 +0,0 @@ -#nullable enable - -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; - -namespace West.TelegramBot.ChatQuotes.Model.Quote; - -[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))] -public class Request -{ - public Request(Telegram.Bot.Types.Message msg) - { - // TODO: move default values to config - Format = "webp"; - BackgroundColor = "#1b1429"; - Width = 512; - Height = 768; - Scale = 2; - - Messages = new List {Message.FromMessage(msg)}; - } - - public Type Type { get; set; } - public string Format { get; set; } - public string BackgroundColor { get; set; } - public int Width { get; set; } - public int Height { get; set; } - public int Scale { get; set; } - public List? Messages { get; set; } - - public string ToJson() - { - return JsonConvert.SerializeObject(this, ChatQuotes.SerializerSettings); - } -} \ No newline at end of file diff --git a/modules/ChatQuotes/Model/Quote/Response.cs b/modules/ChatQuotes/Model/Quote/Response.cs deleted file mode 100644 index 23ca597..0000000 --- a/modules/ChatQuotes/Model/Quote/Response.cs +++ /dev/null @@ -1,16 +0,0 @@ -#nullable disable - -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; - -namespace West.TelegramBot.ChatQuotes.Model.Quote; - -[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))] -public class Response -{ - public bool Ok { get; set; } - - public Result Result { get; set; } - public static Response FromJson(string json) - => JsonConvert.DeserializeObject(json, ChatQuotes.SerializerSettings); -} \ No newline at end of file diff --git a/modules/ChatQuotes/Model/Quote/Result.cs b/modules/ChatQuotes/Model/Quote/Result.cs deleted file mode 100644 index 56f87e8..0000000 --- a/modules/ChatQuotes/Model/Quote/Result.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; - -namespace West.TelegramBot.ChatQuotes.Model.Quote; - -[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))] -public class Result -{ - public string Image { get; set; } = ""; - public Type Type { get; set; } - public long Width { get; set; } - public long Height { get; set; } -} \ No newline at end of file diff --git a/modules/ChatQuotes/Model/Quote/Type.cs b/modules/ChatQuotes/Model/Quote/Type.cs deleted file mode 100644 index b30a38c..0000000 --- a/modules/ChatQuotes/Model/Quote/Type.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace West.TelegramBot.ChatQuotes.Model.Quote; - -public enum Type -{ - Quote = 0, - Image, - Null -} \ No newline at end of file diff --git a/modules/ChatQuotes/Model/User.cs b/modules/ChatQuotes/Model/User.cs deleted file mode 100644 index 455d297..0000000 --- a/modules/ChatQuotes/Model/User.cs +++ /dev/null @@ -1,22 +0,0 @@ -using Newtonsoft.Json; - -namespace West.TelegramBot.ChatQuotes.Model; - -public class User : Telegram.Bot.Types.User -{ - [JsonProperty] - public string Name => LastName != null ? $"{FirstName} {LastName}" : FirstName; - - public static User FromTgUser(Telegram.Bot.Types.User user) - { - return new User - { - Id = user.Id, - FirstName = user.FirstName, - LastName = user.LastName, - Username = user.Username, - LanguageCode = user.LanguageCode, - IsBot = user.IsBot - }; - } -} \ No newline at end of file diff --git a/modules/ChatQuotes/QuoteGeneratorService.cs b/modules/ChatQuotes/QuoteGeneratorService.cs deleted file mode 100644 index 8c7263c..0000000 --- a/modules/ChatQuotes/QuoteGeneratorService.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System.Net.Http.Headers; -using System.Text; -using Microsoft.Extensions.Configuration; -using Newtonsoft.Json; -using West.TelegramBot.ChatQuotes.Model.Quote; -using Message = Telegram.Bot.Types.Message; - -namespace West.TelegramBot.ChatQuotes; - -public class QuoteGeneratorService -{ - private readonly HttpClient _httpClient; - private readonly MediaTypeHeaderValue _mediaType; - - public QuoteGeneratorService(IConfiguration configuration) - { - _httpClient = new HttpClient - { - BaseAddress = new Uri(configuration.GetValue("QuoteApiUrl")) - }; - - _mediaType = MediaTypeHeaderValue.Parse("application/json"); - } - - public async Task GenerateQuoteImage(Message msg) - { - var request = new Request(msg); - var content = new ByteArrayContent(Encoding.UTF8.GetBytes(request.ToJson().ToCharArray())) - { - Headers = - { - ContentType = _mediaType - } - }; - - var resp = await _httpClient.PostAsync("/generate", content); - var quoteResponse = JsonConvert.DeserializeObject(await resp.Content.ReadAsStringAsync()); - - return quoteResponse.Ok ? new MemoryStream(Convert.FromBase64String(quoteResponse.Result.Image)) : null; - } -} \ No newline at end of file diff --git a/modules/Destiny2.WhereIsXur/Destiny2.WhereIsXur.csproj b/modules/Destiny2.WhereIsXur/Destiny2.WhereIsXur.csproj deleted file mode 100644 index dcb29ac..0000000 --- a/modules/Destiny2.WhereIsXur/Destiny2.WhereIsXur.csproj +++ /dev/null @@ -1,18 +0,0 @@ - - - - net8.0 - TelegramBot.D2_WhereIsXur - Kruzya.TelegramBot.Destiny2.WhereIsXur - - - - - - - - - - - - diff --git a/modules/Destiny2.WhereIsXur/Provider/IXurPlaceProvider.cs b/modules/Destiny2.WhereIsXur/Provider/IXurPlaceProvider.cs deleted file mode 100644 index b9a101d..0000000 --- a/modules/Destiny2.WhereIsXur/Provider/IXurPlaceProvider.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System.Threading.Tasks; - -namespace Kruzya.TelegramBot.Destiny2.WhereIsXur.Provider; - -public interface IXurPlaceProvider -{ - public Task GetPlaceAsync(); - public string GetPlace(); -} \ No newline at end of file diff --git a/modules/Destiny2.WhereIsXur/Provider/XurWiki.cs b/modules/Destiny2.WhereIsXur/Provider/XurWiki.cs deleted file mode 100644 index 6f32b08..0000000 --- a/modules/Destiny2.WhereIsXur/Provider/XurWiki.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.Threading.Tasks; -using Fizzler.Systems.HtmlAgilityPack; -using HtmlAgilityPack; - -namespace Kruzya.TelegramBot.Destiny2.WhereIsXur.Provider; - -public class XurWiki : IXurPlaceProvider -{ - public async Task GetPlaceAsync() - { - var web = new HtmlWeb(); - var document = await web.LoadFromWebAsync("https://xur.wiki"); - - var place = document.DocumentNode.QuerySelector(".location_name"); - if (place != null) - { - return place.InnerText.Trim(); - } - - return ""; - } - - public string GetPlace() - { - return GetPlaceAsync().GetAwaiter().GetResult(); - } -} \ No newline at end of file diff --git a/modules/Destiny2.WhereIsXur/RequestHandler.cs b/modules/Destiny2.WhereIsXur/RequestHandler.cs deleted file mode 100644 index acce169..0000000 --- a/modules/Destiny2.WhereIsXur/RequestHandler.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Threading.Tasks; -using BotFramework; -using BotFramework.Attributes; -using Kruzya.TelegramBot.Destiny2.WhereIsXur.Provider; -using Telegram.Bot; -using Telegram.Bot.Types.Enums; - -namespace Kruzya.TelegramBot.Destiny2.WhereIsXur; - -public class RequestHandler : BotEventHandler -{ - protected readonly IXurPlaceProvider _placeProvider; - - public RequestHandler(IXurPlaceProvider xurPlaceProvider) - { - _placeProvider = xurPlaceProvider; - } - - [Command("d2_xur")] - public async Task WhereIsXur() - { - var place = await _placeProvider.GetPlaceAsync(); - if (string.IsNullOrWhiteSpace(place)) - { - await Response("unknown"); - return; - } - - await Response(place); - } - - protected async Task Response(string place) - { - await Bot.SendTextMessageAsync(Chat, $"Xûr place is {place}", parseMode: ParseMode.Html); - } -} \ No newline at end of file diff --git a/modules/Destiny2.WhereIsXur/WhereIsXur.cs b/modules/Destiny2.WhereIsXur/WhereIsXur.cs deleted file mode 100644 index bd4fcf4..0000000 --- a/modules/Destiny2.WhereIsXur/WhereIsXur.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Kruzya.TelegramBot.Core; -using Kruzya.TelegramBot.Destiny2.WhereIsXur.Provider; -using Microsoft.Extensions.DependencyInjection; - -namespace Kruzya.TelegramBot.Destiny2.WhereIsXur; - -public class WhereIsXur : Module -{ - public WhereIsXur(Core.Core core) : base(core) - { - } - - public override void ConfigureServices(IServiceCollection services) - { - services.AddSingleton(); - } -} \ No newline at end of file From c3a553f68d4b5e94db2441c0d761beec97eb1b11 Mon Sep 17 00:00:00 2001 From: Andriy <30056636+West14@users.noreply.github.com> Date: Sun, 9 Feb 2025 17:40:03 +0200 Subject: [PATCH 02/12] fix: build and lots of obsolete warnings --- Core/Controllers/Telegram.cs | 9 ++---- Core/Core.csproj | 7 ++-- Core/Extensions/HttpClientExtension.cs | 10 +++--- Core/Handler/CommonHandler.cs | 8 ++--- modules/ChatManagement/Handler/Ban.cs | 8 +---- modules/ChatManagement/Handler/Greet.cs | 4 +-- modules/ChatManagement/Service/WarnService.cs | 6 ++-- .../Combot/CombotApiResponse.cs | 14 ++++---- modules/CombotAntiSpam/Combot/CombotClient.cs | 2 +- modules/CombotAntiSpam/CombotAntiSpam.csproj | 3 +- modules/ContentStore/Handler/Store.cs | 12 +++---- modules/ContentStore/Model/RandomMedia.cs | 4 +-- .../ContentStore/Service/AnimBoobsService.cs | 2 +- .../ContentStore/Service/AnimalAsAService.cs | 4 +-- .../Service/Kitties/AbstractKittiesService.cs | 2 +- modules/ContentStore/Service/OBoobsService.cs | 4 +-- modules/DebugTools/Handler.cs | 6 ++-- modules/Entertainment/Handler/Common.cs | 2 +- .../Handler/Fun/AbstractAnimationReply.cs | 6 ++-- modules/Entertainment/Handler/Fun/Bayan.cs | 2 +- modules/Entertainment/Handler/Guess.cs | 14 ++++---- modules/Entertainment/Handler/Roll.cs | 6 ++-- modules/RichSiteSummary/Handler/FeedList.cs | 32 ++++++++++--------- .../RichSiteSummary/Handler/StatsHandler.cs | 2 +- .../RichSiteSummary/Service/MessageSender.cs | 6 ++-- modules/StickerTools/Handler.cs | 8 ++--- modules/UrlLimitations/MessageExtension.cs | 4 +-- modules/UrlLimitations/MessageHandler.cs | 9 +++--- modules/UserGroupTag/Handler.cs | 15 ++++----- 29 files changed, 103 insertions(+), 108 deletions(-) diff --git a/Core/Controllers/Telegram.cs b/Core/Controllers/Telegram.cs index 230ee59..2736019 100644 --- a/Core/Controllers/Telegram.cs +++ b/Core/Controllers/Telegram.cs @@ -3,10 +3,9 @@ using BotFramework.Config; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Newtonsoft.Json; using System.IO; +using System.Text.Json; using System.Threading.Tasks; -using Telegram.Bot; using Telegram.Bot.Types; namespace Kruzya.TelegramBot.Core.Controllers @@ -16,14 +15,12 @@ namespace Kruzya.TelegramBot.Core.Controllers private const string SecretTokenHeader = "X-Telegram-Bot-Api-Secret-Token"; private readonly ILogger _logger; - private readonly ITelegramBotClient _client; private readonly IUpdateTarget _updateTarget; private readonly string _secretToken; - public Telegram(ILogger logger, ITelegramBotClient client, IUpdateTarget updateTarget, IOptions config) + public Telegram(ILogger logger, IUpdateTarget updateTarget, IOptions config) { _logger = logger; - _client = client; _updateTarget = updateTarget; _secretToken = config.Value.Webhook.SecretToken; @@ -50,7 +47,7 @@ namespace Kruzya.TelegramBot.Core.Controllers } var body = await (new StreamReader(Request.Body)).ReadToEndAsync(); - LaunchHandle(JsonConvert.DeserializeObject(body)); + LaunchHandle(JsonSerializer.Deserialize(body)); return Ok(); } diff --git a/Core/Core.csproj b/Core/Core.csproj index 491a28a..f05885c 100644 --- a/Core/Core.csproj +++ b/Core/Core.csproj @@ -4,11 +4,11 @@ net8.0 TelegramBot Kruzya.TelegramBot.Core + enable - all runtime; build; native; contentfiles; analyzers; buildtransitive @@ -17,6 +17,9 @@ - + + + + diff --git a/Core/Extensions/HttpClientExtension.cs b/Core/Extensions/HttpClientExtension.cs index 793472b..58bec94 100644 --- a/Core/Extensions/HttpClientExtension.cs +++ b/Core/Extensions/HttpClientExtension.cs @@ -1,21 +1,21 @@ using System; using System.Net.Http; +using System.Text.Json; using System.Threading.Tasks; -using Newtonsoft.Json; namespace Kruzya.TelegramBot.Core.Extensions; public static class HttpClientExtension { - public static async Task GetJsonAsync(this HttpClient client, Uri requestUri) + public static async Task GetJsonAsync(this HttpClient client, Uri requestUri) { var response = await client.GetStringAsync(requestUri); - return JsonConvert.DeserializeObject(response); + return JsonSerializer.Deserialize(response); } - public static async Task GetJsonAsync(this HttpClient client, string requestUri) + public static async Task GetJsonAsync(this HttpClient client, string requestUri) { var response = await client.GetStringAsync(requestUri); - return JsonConvert.DeserializeObject(response); + return JsonSerializer.Deserialize(response); } } \ No newline at end of file diff --git a/Core/Handler/CommonHandler.cs b/Core/Handler/CommonHandler.cs index e9b5313..fbf0286 100644 --- a/Core/Handler/CommonHandler.cs +++ b/Core/Handler/CommonHandler.cs @@ -26,8 +26,8 @@ public abstract class CommonHandler : BotEventHandler protected virtual async Task Reply(string text) { - return await Bot.SendTextMessageAsync(Chat.Id, text, - replyToMessageId: Message?.MessageId, parseMode: ParseMode.Html); + return await Bot.SendMessage(Chat.Id, text, + replyParameters: Message?.MessageId, parseMode: ParseMode.Html); } protected async Task CanPunish() @@ -38,14 +38,14 @@ public abstract class CommonHandler : BotEventHandler protected async Task BanMember(long userId, DateTime banEnd) { - await Bot.RestrictChatMemberAsync( + await Bot.RestrictChatMember( Chat.Id, userId, new ChatPermissions { CanSendMessages = false }, - banEnd + untilDate: banEnd ); } diff --git a/modules/ChatManagement/Handler/Ban.cs b/modules/ChatManagement/Handler/Ban.cs index 927ab32..dd50369 100644 --- a/modules/ChatManagement/Handler/Ban.cs +++ b/modules/ChatManagement/Handler/Ban.cs @@ -60,17 +60,11 @@ public class Ban : CommonHandler return; } - await Bot.RestrictChatMemberAsync(Chat.Id, RepliedUser!.Id, + await Bot.RestrictChatMember(Chat.Id, RepliedUser!.Id, new ChatPermissions { CanSendMessages = true, - CanChangeInfo = true, - CanInviteUsers = true, - CanPinMessages = true, - CanSendPolls = true, - CanSendMediaMessages = true, CanSendOtherMessages = true, - CanAddWebPagePreviews = true }); await Reply($"{From.ToHtml()} разблокировал {RepliedUser!.ToHtml()}"); diff --git a/modules/ChatManagement/Handler/Greet.cs b/modules/ChatManagement/Handler/Greet.cs index fa1db42..7b23850 100644 --- a/modules/ChatManagement/Handler/Greet.cs +++ b/modules/ChatManagement/Handler/Greet.cs @@ -46,7 +46,7 @@ public class Greet : BotEventHandler reply.Text("Пожалуйста, ознакомьтесь с правилами. /rules"); } - await Bot.SendTextMessageAsync(Chat.Id, string.Format(reply.ToString(), membersHtml), - parseMode: ParseMode.Html, replyToMessageId: message.MessageId); + await Bot.SendMessage(Chat.Id, string.Format(reply.ToString(), membersHtml), + parseMode: ParseMode.Html, replyParameters: message.MessageId); } } \ No newline at end of file diff --git a/modules/ChatManagement/Service/WarnService.cs b/modules/ChatManagement/Service/WarnService.cs index ed72b10..e9f51a7 100644 --- a/modules/ChatManagement/Service/WarnService.cs +++ b/modules/ChatManagement/Service/WarnService.cs @@ -36,20 +36,20 @@ public class WarnService { try { - await _bot.RestrictChatMemberAsync( + await _bot.RestrictChatMember( chat.Id, to.Id, new ChatPermissions { CanSendMessages = false }, - DateTime.Now.AddDays(7) + untilDate: DateTime.Now.AddDays(7) ); warnCount = 0; } catch { - await _bot.SendTextMessageAsync(chat.Id, "У меня нет прав на блокировку пользователя."); + await _bot.SendMessage(chat.Id, "У меня нет прав на блокировку пользователя."); } } diff --git a/modules/CombotAntiSpam/Combot/CombotApiResponse.cs b/modules/CombotAntiSpam/Combot/CombotApiResponse.cs index da82a5b..660cc55 100644 --- a/modules/CombotAntiSpam/Combot/CombotApiResponse.cs +++ b/modules/CombotAntiSpam/Combot/CombotApiResponse.cs @@ -1,5 +1,5 @@ using System; -using Newtonsoft.Json; +using System.Text.Json.Serialization; namespace Kruzya.TelegramBot.CombotAntiSpam.Combot; @@ -7,24 +7,24 @@ internal class CombotApiResponse { public class ApiResult { - [JsonProperty("messages")] + [JsonPropertyName("messages")] public string[] Messages { get; set; } - [JsonProperty("time_added")] + [JsonPropertyName("time_added")] public int TimeAdded { get; set; } - [JsonProperty("offenses")] + [JsonPropertyName("offenses")] public int Offenses { get; set; } public DateTime AddedAt => DateTimeOffset.FromUnixTimeSeconds(TimeAdded).DateTime; } - [JsonProperty("ok")] + [JsonPropertyName("ok")] public bool IsSpammer { get; set; } - [JsonProperty("description")] + [JsonPropertyName("description")] public string Description { get; set; } - [JsonProperty("result")] + [JsonPropertyName("result")] public ApiResult Result { get; set; } } \ No newline at end of file diff --git a/modules/CombotAntiSpam/Combot/CombotClient.cs b/modules/CombotAntiSpam/Combot/CombotClient.cs index ddfe4c1..7830922 100644 --- a/modules/CombotAntiSpam/Combot/CombotClient.cs +++ b/modules/CombotAntiSpam/Combot/CombotClient.cs @@ -22,6 +22,6 @@ public class CombotClient : ICombotClient public async Task IsSpammerAsync(User user) { var result = await _httpClient.GetJsonAsync($"?user_id={user.Id}"); - return result.IsSpammer; + return result?.IsSpammer ?? false; } } \ No newline at end of file diff --git a/modules/CombotAntiSpam/CombotAntiSpam.csproj b/modules/CombotAntiSpam/CombotAntiSpam.csproj index 0f8eb7e..9c75500 100644 --- a/modules/CombotAntiSpam/CombotAntiSpam.csproj +++ b/modules/CombotAntiSpam/CombotAntiSpam.csproj @@ -1,9 +1,10 @@ - + net8.0 TelegramBot.CombotAntiSpam Kruzya.TelegramBot.CombotAntiSpam + enable diff --git a/modules/ContentStore/Handler/Store.cs b/modules/ContentStore/Handler/Store.cs index d360370..8c13e2c 100644 --- a/modules/ContentStore/Handler/Store.cs +++ b/modules/ContentStore/Handler/Store.cs @@ -115,7 +115,7 @@ public class Store : CommonHandler catch (Exception) { answer = "Товар недоступен"; - await Bot.EditMessageTextAsync(Chat.Id, + await Bot.EditMessageText(Chat.Id, messageId, $"{From.ToHtml()} попытался купить \"{storeItem.Name}\", но товара в наличии не оказалось.", ParseMode.Html); @@ -124,7 +124,7 @@ public class Store : CommonHandler } reputation = await _reputation.SetUserReputationAsync(Chat, From, reputation - storeItem.Price); - await Bot.EditMessageTextAsync(Chat.Id, + await Bot.EditMessageText(Chat.Id, messageId, $"{From.ToHtml()} ({reputation}) купил \"{storeItem.Name}\".", ParseMode.Html); @@ -141,17 +141,17 @@ public class Store : CommonHandler switch (randomMedia.Type) { case InputMediaType.Photo: - await Bot.SendPhotoAsync(Chat.Id, file, + await Bot.SendVideo(Chat.Id, file, caption: randomMedia.Caption, - replyToMessageId: messageId, + replyParameters: messageId, parseMode: ParseMode.Html, hasSpoiler: randomMedia.Nsfw ); break; case InputMediaType.Video: - await Bot.SendVideoAsync(Chat.Id, file, + await Bot.SendVideo(Chat.Id, file, caption: randomMedia.Caption, - replyToMessageId: messageId, + replyParameters: messageId, parseMode: ParseMode.Html, hasSpoiler: randomMedia.Nsfw ); diff --git a/modules/ContentStore/Model/RandomMedia.cs b/modules/ContentStore/Model/RandomMedia.cs index a54a884..924386e 100644 --- a/modules/ContentStore/Model/RandomMedia.cs +++ b/modules/ContentStore/Model/RandomMedia.cs @@ -5,14 +5,14 @@ namespace West.TelegramBot.ContentStore.Model; public class RandomMedia { - public RandomMedia(IInputFile file, string? caption = null, bool nsfw = false) + public RandomMedia(InputFile file, string? caption = null, bool nsfw = false) { File = file; Caption = caption; Nsfw = nsfw; } - public IInputFile File; + public InputFile File; public string? Caption; public bool Nsfw; diff --git a/modules/ContentStore/Service/AnimBoobsService.cs b/modules/ContentStore/Service/AnimBoobsService.cs index 42fa277..95a0729 100644 --- a/modules/ContentStore/Service/AnimBoobsService.cs +++ b/modules/ContentStore/Service/AnimBoobsService.cs @@ -22,7 +22,7 @@ public class AnimBoobsService : AbstractNsfwService // https://bugs.telegram.org/c/23674 workaround var video = await _httpClient.GetStreamAsync($"https://westdev.me/_boobs/media/{fileName}"); - return new RandomMedia(new InputFile(video, fileName)) + return new RandomMedia(new InputFileStream(video, fileName)) { Type = InputMediaType.Video, Nsfw = true diff --git a/modules/ContentStore/Service/AnimalAsAService.cs b/modules/ContentStore/Service/AnimalAsAService.cs index 7a6af3b..f1f5114 100644 --- a/modules/ContentStore/Service/AnimalAsAService.cs +++ b/modules/ContentStore/Service/AnimalAsAService.cs @@ -1,4 +1,4 @@ -using Newtonsoft.Json; +using System.Text.Json; using Telegram.Bot.Types; using West.TelegramBot.ContentStore.Model; @@ -18,7 +18,7 @@ public abstract class AnimalAsAService : IRandomMediaService public async Task GetRandomMediaAsync(Chat chat, User user) { var resp = await _httpClient.GetAsync("images/search"); - var catImage = JsonConvert.DeserializeObject>(await resp.Content.ReadAsStringAsync())![0]; + var catImage = JsonSerializer.Deserialize>(await resp.Content.ReadAsStringAsync())![0]; return new RandomMedia(new InputFileUrl(catImage.Url)); } } \ No newline at end of file diff --git a/modules/ContentStore/Service/Kitties/AbstractKittiesService.cs b/modules/ContentStore/Service/Kitties/AbstractKittiesService.cs index 2528939..9460020 100644 --- a/modules/ContentStore/Service/Kitties/AbstractKittiesService.cs +++ b/modules/ContentStore/Service/Kitties/AbstractKittiesService.cs @@ -25,7 +25,7 @@ public abstract class AbstractKittiesService : IRandomMediaService var response = await _api.GetKittiesImageAsync(VideoType); return new RandomMedia( - new InputFile(response.Content), + new InputFileStream(response.Content), new HtmlString().Url(response.Source, response.Title).ToString(), true ); diff --git a/modules/ContentStore/Service/OBoobsService.cs b/modules/ContentStore/Service/OBoobsService.cs index 8cbfeb6..bb04525 100644 --- a/modules/ContentStore/Service/OBoobsService.cs +++ b/modules/ContentStore/Service/OBoobsService.cs @@ -1,4 +1,4 @@ -using Newtonsoft.Json; +using System.Text.Json; using Telegram.Bot.Types; using West.TelegramBot.ContentStore.Model; using West.TelegramBot.ContentStore.Option; @@ -20,7 +20,7 @@ public class OBoobsService : AbstractNsfwService { // "/boobs/{start=0; sql offset}/{count=1; sql limit}/{order=-id;[id,rank,-rank,interest,-interest,random]}/ var httpResp = await _httpClient.GetAsync("boobs/1/1/random"); - var boobsResponse = JsonConvert.DeserializeObject>(await httpResp.Content.ReadAsStringAsync()); + var boobsResponse = JsonSerializer.Deserialize>(await httpResp.Content.ReadAsStringAsync()); var boobsItem = boobsResponse![0]; var boobsId = boobsItem.Id.ToString("D5"); diff --git a/modules/DebugTools/Handler.cs b/modules/DebugTools/Handler.cs index 1d53edd..d803611 100644 --- a/modules/DebugTools/Handler.cs +++ b/modules/DebugTools/Handler.cs @@ -4,13 +4,15 @@ using BotFramework.Enums; using BotFramework.Utils; using Kruzya.TelegramBot.Core.Extensions; using Kruzya.TelegramBot.Core.Service; -using Newtonsoft.Json; +using System.Text.Json; namespace West.TelegramBot.DebugTools; public class Handler : BotEventHandler { private readonly UserService _userService; + private static readonly JsonSerializerOptions DumpOptions = new() { WriteIndented = true }; + public Handler(UserService userService) { @@ -26,7 +28,7 @@ public class Handler : BotEventHandler } var message = RawUpdate.Message!.ReplyToMessage ?? RawUpdate.Message; var text = HtmlString.Empty - .CodeWithStyle("language-json", JsonConvert.SerializeObject(message, Formatting.Indented)); + .CodeWithStyle("language-json", JsonSerializer.Serialize(message, DumpOptions)); await Bot.SendHtmlStringAsync(Chat, text, replyTo: message.MessageId); } diff --git a/modules/Entertainment/Handler/Common.cs b/modules/Entertainment/Handler/Common.cs index b5aa1e5..711ac13 100644 --- a/modules/Entertainment/Handler/Common.cs +++ b/modules/Entertainment/Handler/Common.cs @@ -58,6 +58,6 @@ public class Common : BotEventHandler .Br(); } - await Bot.SendTextMessageAsync(Chat.Id, msg.ToString(), parseMode: ParseMode.Html); + await Bot.SendMessage(Chat.Id, msg.ToString(), parseMode: ParseMode.Html); } } \ No newline at end of file diff --git a/modules/Entertainment/Handler/Fun/AbstractAnimationReply.cs b/modules/Entertainment/Handler/Fun/AbstractAnimationReply.cs index 44d0b97..90321d2 100644 --- a/modules/Entertainment/Handler/Fun/AbstractAnimationReply.cs +++ b/modules/Entertainment/Handler/Fun/AbstractAnimationReply.cs @@ -54,7 +54,7 @@ public abstract class AbstractAnimationReply : BotEventHandler animationFileOption.SetValue(animation.FileId); _db.AddOrUpdate(animationFileOption); - await Bot.SendTextMessageAsync(Chat.Id, "Animation has been set.", replyToMessageId: Message!.ReplyToMessage!.MessageId); + await Bot.SendMessage(Chat.Id, "Animation has been set.", replyParameters: Message!.ReplyToMessage!.MessageId); } protected virtual async Task HandleAnimation() @@ -84,8 +84,8 @@ public abstract class AbstractAnimationReply : BotEventHandler return false; } - await Bot.SendAnimationAsync(Chat.Id, new InputFileId(animationFileId), - replyToMessageId: GetMessageIdToReply() ?? Message?.MessageId); + await Bot.SendAnimation(Chat.Id, new InputFileId(animationFileId), + replyParameters: GetMessageIdToReply() ?? Message?.MessageId); nextUseOption.SetValue(DateTime.Now + Cooldown); _db.AddOrUpdate(nextUseOption); diff --git a/modules/Entertainment/Handler/Fun/Bayan.cs b/modules/Entertainment/Handler/Fun/Bayan.cs index 671dbf2..504dbb3 100644 --- a/modules/Entertainment/Handler/Fun/Bayan.cs +++ b/modules/Entertainment/Handler/Fun/Bayan.cs @@ -35,7 +35,7 @@ public class Bayan : AbstractAnimationReply { if (await HandleAnimation()) { - await Bot.DeleteMessageAsync(Chat.Id, Message!.MessageId); + await Bot.DeleteMessage(Chat.Id, Message!.MessageId); } } diff --git a/modules/Entertainment/Handler/Guess.cs b/modules/Entertainment/Handler/Guess.cs index 013f9b0..11141cc 100644 --- a/modules/Entertainment/Handler/Guess.cs +++ b/modules/Entertainment/Handler/Guess.cs @@ -61,7 +61,7 @@ public class Guess : CommonHandler var doesExist = guessDict.Any(pair => pair.Value.UserId == From.Id); if (doesExist) { - await Bot.SendTextMessageAsync(Chat, "Вы уже запустили игру."); + await Bot.SendMessage(Chat, "Вы уже запустили игру."); return; } @@ -81,8 +81,8 @@ public class Guess : CommonHandler new("3") { CallbackData = $"guess|{From.Id}|answer|3" } }); - var message = await Bot.SendTextMessageAsync(Chat.Id, "Выберите число от 1 до 3.", - replyToMessageId: messageId, + var message = await Bot.SendMessage(Chat.Id, "Выберите число от 1 до 3.", + replyParameters: messageId, replyMarkup: keyBoard ); @@ -127,7 +127,7 @@ public class Guess : CommonHandler return; } - await Bot.AnswerCallbackQueryAsync(CallbackQuery.Id); + await Bot.AnswerCallbackQuery(CallbackQuery.Id); guessDict.TryRemove((int) messageId, out _); _guessCache.SetValue(Chat.Id, guessDict, -1); @@ -152,7 +152,7 @@ public class Guess : CommonHandler _db.AddOrUpdate(cooldownOption); - await Bot.EditMessageTextAsync(Chat, (int) messageId, message + postFix, parseMode: ParseMode.Html); + await Bot.EditMessageText(Chat, (int) messageId, message + postFix, parseMode: ParseMode.Html); // Drop bot message. _requests.Add(new DeleteRequest @@ -166,8 +166,8 @@ public class Guess : CommonHandler protected override async Task Reply(string text) { // TODO: move feature with autocleaning to Core CommonHandler. - var message = await Bot.SendTextMessageAsync(Chat.Id, text, - replyToMessageId: Message?.MessageId, parseMode: ParseMode.Html); + var message = await Bot.SendMessage(Chat.Id, text, + replyParameters: Message?.MessageId, parseMode: ParseMode.Html); _requests.Add(new DeleteRequest { diff --git a/modules/Entertainment/Handler/Roll.cs b/modules/Entertainment/Handler/Roll.cs index 8d4ab2b..182153d 100644 --- a/modules/Entertainment/Handler/Roll.cs +++ b/modules/Entertainment/Handler/Roll.cs @@ -132,14 +132,14 @@ public class Roll : CommonHandler } } - await Bot.SendTextMessageAsync(Chat, $"{string.Join(", ", numbers)}\n\nPositive: {positive}.\nNegative: {negative}"); + await Bot.SendMessage(Chat, $"{string.Join(", ", numbers)}\n\nPositive: {positive}.\nNegative: {negative}"); } protected override async Task Reply(string text) { // TODO: move feature with autocleaning to Core CommonHandler. - var message = await Bot.SendTextMessageAsync(Chat.Id, text, - replyToMessageId: Message?.MessageId, parseMode: ParseMode.Html); + var message = await Bot.SendMessage(Chat.Id, text, + replyParameters: Message?.MessageId, parseMode: ParseMode.Html); _requests.Add(new DeleteRequest { diff --git a/modules/RichSiteSummary/Handler/FeedList.cs b/modules/RichSiteSummary/Handler/FeedList.cs index 5edd191..1433593 100644 --- a/modules/RichSiteSummary/Handler/FeedList.cs +++ b/modules/RichSiteSummary/Handler/FeedList.cs @@ -12,6 +12,7 @@ using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.ReplyMarkups; +using static Microsoft.EntityFrameworkCore.DbLoggerCategory; namespace Kruzya.TelegramBot.RichSiteSummary.Handler; @@ -71,11 +72,12 @@ public class FeedList : AbstractHandler var inlineButtons = new InlineKeyboardMarkup(buttons); if (message == null) { - await Bot.SendTextMessageAsync(new ChatId(chat.Id), text, 0, ParseMode.Html, null, true, true, false, 0, replyMarkup: inlineButtons); + await Bot.SendMessage(chat, text, ParseMode.Html, linkPreviewOptions: true, + disableNotification: true, replyMarkup: inlineButtons); } else { - await Bot.EditMessageTextAsync(chat, message.MessageId, text, ParseMode.Html, null, true, replyMarkup: inlineButtons); + await Bot.EditMessageText(chat, message.MessageId, text, ParseMode.Html, linkPreviewOptions: true, replyMarkup: inlineButtons); } } @@ -87,7 +89,8 @@ public class FeedList : AbstractHandler { if (!(await GenerateMenu(query))) { - await Bot.SendTextMessageAsync(Chat, $"No one feed match by search pattern ({query}).", 0, ParseMode.Html, null, true); + await Bot.SendMessage(Chat, $"No one feed match by search pattern ({query}).", ParseMode.Html, + linkPreviewOptions: true); } } @@ -96,8 +99,7 @@ public class FeedList : AbstractHandler { if (!(await GenerateMenu(":sub"))) { - await Bot.SendTextMessageAsync(Chat, - "There are no one subscription. Add new with /feed_list or /feed_search."); + await Bot.SendMessage(Chat, "There are no one subscription. Add new with /feed_list or /feed_search."); } } @@ -191,13 +193,13 @@ public class FeedList : AbstractHandler if (editableMessage == null) { - await Bot.SendTextMessageAsync(Chat, "Select the feed for viewing details", 0, null, - null, true, true, false, 0, replyMarkup: new InlineKeyboardMarkup(buttons)); + await Bot.SendMessage(Chat, "Select the feed for viewing details", linkPreviewOptions: true, + disableNotification: true, replyMarkup: new InlineKeyboardMarkup(buttons)); } else { - await Bot.EditMessageTextAsync(editableMessage.Chat, editableMessage.MessageId, "Select the feed for viewing details", null, null, false, - new InlineKeyboardMarkup(buttons)); + await Bot.EditMessageText(editableMessage.Chat, editableMessage.MessageId, + "Select the feed for viewing details", replyMarkup: new InlineKeyboardMarkup(buttons)); } return true; @@ -219,7 +221,7 @@ public class FeedList : AbstractHandler var fromId = Int64.Parse(data[1]); if (fromId != From.Id) { - await Bot.AnswerCallbackQueryAsync(RawUpdate.CallbackQuery.Id, + await Bot.AnswerCallbackQuery(RawUpdate.CallbackQuery.Id, "You can't perform this action: command called by another user.", true); return; } @@ -238,13 +240,13 @@ public class FeedList : AbstractHandler case "do": if (RawUpdate.CallbackQuery.From.Id != RawUpdate.CallbackQuery.Message.Chat.Id) { - var userStatus = (await Bot.GetChatMemberAsync(RawUpdate.CallbackQuery.Message.Chat, RawUpdate.CallbackQuery.From.Id)).Status; + var userStatus = (await Bot.GetChatMember(RawUpdate.CallbackQuery.Message.Chat, RawUpdate.CallbackQuery.From.Id)).Status; var allowedUserStatuses = new ChatMemberStatus[] {ChatMemberStatus.Administrator, ChatMemberStatus.Creator}; if (!allowedUserStatuses.Contains(userStatus)) { - await Bot.AnswerCallbackQueryAsync(RawUpdate.CallbackQuery.Id, + await Bot.AnswerCallbackQuery(RawUpdate.CallbackQuery.Id, "You can't perform this action: you don't have administrator permissions.", true); return; } @@ -268,12 +270,12 @@ public class FeedList : AbstractHandler idx++; } - await Bot.SendTextMessageAsync(RawUpdate.CallbackQuery.Message.Chat, messageTextBuilder.ToString(), - 0, ParseMode.Html, null, true); + await Bot.SendMessage(RawUpdate.CallbackQuery.Message.Chat, messageTextBuilder.ToString(), + ParseMode.Html, linkPreviewOptions: true); break; } - await Bot.AnswerCallbackQueryAsync(RawUpdate.CallbackQuery.Id); + await Bot.AnswerCallbackQuery(RawUpdate.CallbackQuery.Id); } protected async Task ChangeFeedSubscription(Guid feedId, Chat chat, User from, Message message) diff --git a/modules/RichSiteSummary/Handler/StatsHandler.cs b/modules/RichSiteSummary/Handler/StatsHandler.cs index 80d0f05..ee71244 100644 --- a/modules/RichSiteSummary/Handler/StatsHandler.cs +++ b/modules/RichSiteSummary/Handler/StatsHandler.cs @@ -31,6 +31,6 @@ public class StatsHandler : AbstractHandler textMessage.Append( $"- exists {subscriptionsCount} subscriptions on feeds (unique subscribers: {uniqueSubscribers})"); - await Bot.SendTextMessageAsync(Chat, textMessage.ToString(), parseMode: ParseMode.Html); + await Bot.SendMessage(Chat, textMessage.ToString(), parseMode: ParseMode.Html); } } \ No newline at end of file diff --git a/modules/RichSiteSummary/Service/MessageSender.cs b/modules/RichSiteSummary/Service/MessageSender.cs index 8e1cd2c..67a85da 100644 --- a/modules/RichSiteSummary/Service/MessageSender.cs +++ b/modules/RichSiteSummary/Service/MessageSender.cs @@ -36,14 +36,12 @@ public class MessageSender : AbstractTimedHostedService { if (string.IsNullOrWhiteSpace(message.ImageUrl)) { - await _bot.BotClient.SendTextMessageAsync(message.ChatId, message.Text, 0, message.ParseMode, null, - message.DisableWebPagePreview); + await _bot.BotClient.SendMessage(message.ChatId, message.Text, message.ParseMode, linkPreviewOptions: message.DisableWebPagePreview); } else { - await _bot.BotClient.SendPhotoAsync(message.ChatId, new InputFileUrl(message.ImageUrl), 0, message.Text, - message.ParseMode, null, false, message.DisableWebPagePreview); + await _bot.BotClient.SendPhoto(message.ChatId, new InputFileUrl(message.ImageUrl), message.Text, message.ParseMode); } } catch (ApiRequestException e) diff --git a/modules/StickerTools/Handler.cs b/modules/StickerTools/Handler.cs index 10ee052..777e584 100644 --- a/modules/StickerTools/Handler.cs +++ b/modules/StickerTools/Handler.cs @@ -19,9 +19,9 @@ public class Handler : BotEventHandler return; } - await Bot.SendChatActionAsync(Chat.Id, ChatAction.UploadDocument); + await Bot.SendChatAction(Chat.Id, ChatAction.UploadDocument); using var file = new MemoryStream(); - await Bot.GetInfoAndDownloadFileAsync(sticker.FileId, file); + await Bot.GetInfoAndDownloadFile(sticker.FileId, file); file.Position = 0; using var img = await Image.LoadAsync(file); @@ -30,7 +30,7 @@ public class Handler : BotEventHandler using var outfile = new MemoryStream(); await img.SaveAsPngAsync(outfile); outfile.Position = 0; - await Bot.SendDocumentAsync(Chat.Id, new InputFile(outfile, "sticker.png"), - replyToMessageId: RawUpdate?.Message?.MessageId); + await Bot.SendDocument(Chat.Id, new InputFileStream(outfile, "sticker.png"), + replyParameters: RawUpdate?.Message?.MessageId); } } \ No newline at end of file diff --git a/modules/UrlLimitations/MessageExtension.cs b/modules/UrlLimitations/MessageExtension.cs index 36fec19..f1a1d96 100644 --- a/modules/UrlLimitations/MessageExtension.cs +++ b/modules/UrlLimitations/MessageExtension.cs @@ -23,7 +23,7 @@ public static class MessageExtension { try { - var chat = await bot.GetChatAsync( + var chat = await bot.GetChat( new ChatId(message.Text.Substring(mention.Offset, mention.Length))); if (chat != null) @@ -42,7 +42,7 @@ public static class MessageExtension } } - var status = (await bot.GetChatMemberAsync(message.Chat, userId)).Status; + var status = (await bot.GetChatMember(message.Chat, userId)).Status; if ((new ChatMemberStatus[] { diff --git a/modules/UrlLimitations/MessageHandler.cs b/modules/UrlLimitations/MessageHandler.cs index a893784..4561135 100644 --- a/modules/UrlLimitations/MessageHandler.cs +++ b/modules/UrlLimitations/MessageHandler.cs @@ -8,7 +8,6 @@ using Kruzya.TelegramBot.Core.Data; using Kruzya.TelegramBot.Core.Extensions; using Microsoft.Extensions.Logging; using Telegram.Bot; -using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; namespace Kruzya.TelegramBot.UrlLimitations; @@ -46,11 +45,11 @@ public class MessageHandler : BotEventHandler if (message.Entities.Count(e => e.Type == MessageEntityType.Url || e.Type == MessageEntityType.TextLink) > 0 || await message.HasUnknownMention(Bot)) { - var targetChat = new ChatId(Chat.Id); + var targetChat = Chat.Id; Task.WaitAll( - Bot.BanChatMemberAsync(new ChatId(Chat.Id), From.Id, DateTime.Now.AddDays(1)), - Bot.DeleteMessageAsync(targetChat, message.MessageId), - Bot.SendTextMessageAsync(targetChat, + Bot.BanChatMember(targetChat, From.Id, DateTime.Now.AddDays(1)), + Bot.DeleteMessage(targetChat, message.MessageId), + Bot.SendMessage(targetChat, $"Member {From.ToHtml(true)} has been banned.\nReason:
Spam suspicion
", parseMode: ParseMode.Html) ); } diff --git a/modules/UserGroupTag/Handler.cs b/modules/UserGroupTag/Handler.cs index fc436db..932bfcb 100644 --- a/modules/UserGroupTag/Handler.cs +++ b/modules/UserGroupTag/Handler.cs @@ -48,7 +48,7 @@ public class Handler : BotEventHandler var memberList = tagDictionary.GetValueOrDefault(groupName, new List()); if (memberList.Contains(fromId)) { - await Bot.SendTextMessageAsync(chatId, $"{from.ToHtml()} уже находится в группе {groupName}", + await Bot.SendMessage(chatId, $"{from.ToHtml()} уже находится в группе {groupName}", parseMode: ParseMode.Html); return; } @@ -58,8 +58,8 @@ public class Handler : BotEventHandler userGroupOption.SetValue(tagDictionary); _db.AddOrUpdate(userGroupOption); - _userCache.SetValue(repliedMessage.From.Id, repliedMessage.From, Int32.MaxValue); - await Bot.SendTextMessageAsync(chatId, $"{from.ToHtml()} добавлен в группу {groupName}", + _userCache.SetValue(repliedMessage.From.Id, repliedMessage.From, int.MaxValue); + await Bot.SendMessage(chatId, $"{from.ToHtml()} добавлен в группу {groupName}", parseMode: ParseMode.Html); } @@ -89,16 +89,15 @@ public class Handler : BotEventHandler msg.UserMention(await GetUser(userId, Chat)).Text(", "); } - await Bot.SendTextMessageAsync(Chat.Id, msg.ToString().TrimEnd(',', ' '), parseMode: ParseMode.Html); + await Bot.SendMessage(Chat.Id, msg.ToString().TrimEnd(',', ' '), parseMode: ParseMode.Html); } protected async Task GetUser(long userId, Chat chat) { - User user; - if (!_userCache.TryGetValue(userId, out user)) + if (!_userCache.TryGetValue(userId, out var user)) { - user = (await Bot.GetChatMemberAsync(Chat.Id, userId)).User; - _userCache.SetValue(userId, user, Int32.MaxValue); + user = (await Bot.GetChatMember(Chat.Id, userId)).User; + _userCache.SetValue(userId, user, int.MaxValue); } return user; From 50774e1af639af38aa5f5048df0bb7b93454ca3e Mon Sep 17 00:00:00 2001 From: Andriy <30056636+West14@users.noreply.github.com> Date: Sun, 9 Feb 2025 17:50:46 +0200 Subject: [PATCH 03/12] fix: remove another bunch of obsolete method calls --- Core/AutoDelete/DeleteService.cs | 2 +- Core/Extensions/BotExtension.cs | 8 ++++---- Core/Handler/CommonHandler.cs | 2 +- Core/Handler/SettingsHandler.cs | 10 +++++----- Core/Service/UserService.cs | 2 +- Core/WebhookAspNetProvider.cs | 4 ++-- modules/ChatManagement/Handler/Ban.cs | 4 ++-- .../ChatManagement/Handler/BanStickerSet.Handler.cs | 6 +++--- modules/ChatManagement/Handler/BanStickerSet.Utils.cs | 6 +++--- modules/ChatManagement/Handler/Rules.cs | 2 +- modules/ChatManagement/Handler/WhoIs.cs | 2 +- modules/ChatManagement/Notifier.cs | 6 +++--- modules/ChatManagement/ParamParser/StickerSet.cs | 4 ++-- modules/CodeWatcher/Handler.cs | 8 ++++---- modules/CombotAntiSpam/UserJoinHandler.cs | 6 +++--- modules/ContentStore/Handler/Store.cs | 6 +++--- modules/Reputation/Handler/Reputation.cs | 2 +- 17 files changed, 40 insertions(+), 40 deletions(-) diff --git a/Core/AutoDelete/DeleteService.cs b/Core/AutoDelete/DeleteService.cs index 70f0250..574ba06 100644 --- a/Core/AutoDelete/DeleteService.cs +++ b/Core/AutoDelete/DeleteService.cs @@ -39,7 +39,7 @@ public class DeleteService : AbstractTimedHostedService { try { - await _bot.BotClient.DeleteMessageAsync(request.ChatId, request.MessageId); + await _bot.BotClient.DeleteMessage(request.ChatId, request.MessageId); } catch (ApiRequestException e) { diff --git a/Core/Extensions/BotExtension.cs b/Core/Extensions/BotExtension.cs index 2bd90ac..092ad8b 100644 --- a/Core/Extensions/BotExtension.cs +++ b/Core/Extensions/BotExtension.cs @@ -12,7 +12,7 @@ public static class BotExtension if (victim != null && canUse) { - var victimMember = await bot.GetChatMemberAsync(chat, victim.Id); + var victimMember = await bot.GetChatMember(chat, victim.Id); canUse = victimMember is not ChatMemberOwner && victimMember is not ChatMemberAdministrator && !victim.IsBot; } @@ -21,7 +21,7 @@ public static class BotExtension public static async Task IsUserAdminAsync(this ITelegramBotClient bot, Chat chat, User user) { - var callerMember = await bot.GetChatMemberAsync(chat, user.Id); + var callerMember = await bot.GetChatMember(chat, user.Id); var isAdmin = callerMember is ChatMemberOwner; if (callerMember is ChatMemberAdministrator callerAdmin) @@ -34,12 +34,12 @@ public static class BotExtension public static async Task CanDeleteMessagesAsync(this ITelegramBotClient bot, Chat chat) { - return await CanDeleteMessagesAsync(bot, chat, await bot.GetMeAsync()); + return await CanDeleteMessagesAsync(bot, chat, await bot.GetMe()); } public static async Task CanDeleteMessagesAsync(this ITelegramBotClient bot, Chat chat, User user) { - return await bot.GetChatMemberAsync(chat.Id, user.Id) is ChatMemberOwner + return await bot.GetChatMember(chat.Id, user.Id) is ChatMemberOwner or ChatMemberAdministrator {CanRestrictMembers: true}; } } \ No newline at end of file diff --git a/Core/Handler/CommonHandler.cs b/Core/Handler/CommonHandler.cs index fbf0286..e606d20 100644 --- a/Core/Handler/CommonHandler.cs +++ b/Core/Handler/CommonHandler.cs @@ -56,6 +56,6 @@ public abstract class CommonHandler : BotEventHandler protected async Task AnswerQuery(string id, string? message = null) { - await Bot.AnswerCallbackQueryAsync(id, message); + await Bot.AnswerCallbackQuery(id, message); } } \ No newline at end of file diff --git a/Core/Handler/SettingsHandler.cs b/Core/Handler/SettingsHandler.cs index 039efbd..0e9d321 100644 --- a/Core/Handler/SettingsHandler.cs +++ b/Core/Handler/SettingsHandler.cs @@ -32,7 +32,7 @@ public class SettingsHandler : CommonHandler return; } - await Bot.SendTextMessageAsync( + await Bot.SendMessage( Chat.Id, "What do you want to change?", replyMarkup: GetSettingsMarkup() @@ -66,7 +66,7 @@ public class SettingsHandler : CommonHandler if (paramList[2] == "main_menu") { await AnswerQuery(query.Id); - await Bot.EditMessageTextAsync(Chat.Id, query.Message!.MessageId, "What do you want to change?", + await Bot.EditMessageText(Chat.Id, query.Message!.MessageId, "What do you want to change?", replyMarkup: GetSettingsMarkup()); return; } @@ -103,14 +103,14 @@ public class SettingsHandler : CommonHandler await onOffOpt.SetValueAsync(chatId, !await onOffOpt.GetValueAsync(chatId)); await AnswerQuery(query.Id); - await Bot.EditMessageReplyMarkupAsync(chatId, messageId, GetSettingsMarkup()); + await Bot.EditMessageReplyMarkup(chatId, messageId, GetSettingsMarkup()); break; case OptionType.Select: var selectOpt = (IOption) option; await AnswerQuery(query.Id); - await Bot.EditMessageTextAsync(Chat.Id, messageId, "Here's what you can choose:", + await Bot.EditMessageText(Chat.Id, messageId, "Here's what you can choose:", replyMarkup: await GetChoiceSelectKeyboard(selectOpt)); break; @@ -133,7 +133,7 @@ public class SettingsHandler : CommonHandler await selectOption.SetValueAsync(Chat.Id, choice.Id); await AnswerQuery(query.Id); - await Bot.EditMessageReplyMarkupAsync(Chat.Id, query.Message!.MessageId, await GetChoiceSelectKeyboard(selectOption)); + await Bot.EditMessageReplyMarkup(Chat.Id, query.Message!.MessageId, await GetChoiceSelectKeyboard(selectOption)); } private async Task GetKeyboardButton(IOption option) diff --git a/Core/Service/UserService.cs b/Core/Service/UserService.cs index 116f92f..55e2d1f 100644 --- a/Core/Service/UserService.cs +++ b/Core/Service/UserService.cs @@ -69,7 +69,7 @@ public class UserService private async Task GetUserByChat(long chatId, long userId) { - return (await _bot.GetChatMemberAsync(chatId, userId)).User; + return (await _bot.GetChatMember(chatId, userId)).User; } public bool IsUserSuper(User user) diff --git a/Core/WebhookAspNetProvider.cs b/Core/WebhookAspNetProvider.cs index fe13169..2fc3088 100644 --- a/Core/WebhookAspNetProvider.cs +++ b/Core/WebhookAspNetProvider.cs @@ -29,12 +29,12 @@ namespace Kruzya.TelegramBot.Core public async Task StartAsync(CancellationToken token) { - await _client.SetWebhookAsync(_config.Webhook.Url, secretToken: _secretToken, cancellationToken: token); + await _client.SetWebhook(_config.Webhook.Url, secretToken: _secretToken, cancellationToken: token); } public async Task StopAsync(CancellationToken token) { - await _client.DeleteWebhookAsync(cancellationToken: token); + await _client.DeleteWebhook(cancellationToken: token); } } } diff --git a/modules/ChatManagement/Handler/Ban.cs b/modules/ChatManagement/Handler/Ban.cs index dd50369..9af4c02 100644 --- a/modules/ChatManagement/Handler/Ban.cs +++ b/modules/ChatManagement/Handler/Ban.cs @@ -42,11 +42,11 @@ public class Ban : CommonHandler } catch { - await Bot.SendTextMessageAsync(Chat.Id, "Нет прав на блокировку пользователя."); + await Bot.SendMessage(Chat.Id, "Нет прав на блокировку пользователя."); return; } - await Bot.SendTextMessageAsync( + await Bot.SendMessage( Chat.Id, $"{From.ToHtml()} заблокировал {RepliedUser!.ToHtml()} {banEndMsg}", disableNotification: true, parseMode: ParseMode.Html); diff --git a/modules/ChatManagement/Handler/BanStickerSet.Handler.cs b/modules/ChatManagement/Handler/BanStickerSet.Handler.cs index ab8063d..48639dd 100644 --- a/modules/ChatManagement/Handler/BanStickerSet.Handler.cs +++ b/modules/ChatManagement/Handler/BanStickerSet.Handler.cs @@ -38,7 +38,7 @@ public partial class BanStickerSet var replyToMsgId = Message?.ReplyToMessage?.MessageId; if (replyToMsgId != null) { - await Bot.DeleteMessageAsync(Chat.Id, (int) replyToMsgId); + await Bot.DeleteMessage(Chat.Id, (int) replyToMsgId); } await Reply(FormatStickerSetAction(stickerSet.Set, "заблокирован")); @@ -90,7 +90,7 @@ public partial class BanStickerSet { try { - var stickerSet = await Bot.GetStickerSetAsync(list[i]); + var stickerSet = await Bot.GetStickerSet(list[i]); htmlString.Text($"{i + 1}. ") .Url("https://t.me/addstickers/" + stickerSet.Name, stickerSet.Title) .Br(); @@ -125,7 +125,7 @@ public partial class BanStickerSet "Этот набор стикеров заблокирован. Чтобы я мог его удалить, выдайте мне право на удаление сообщений."); } - await Bot.DeleteMessageAsync(Chat.Id, message.MessageId); + await Bot.DeleteMessage(Chat.Id, message.MessageId); } } } \ No newline at end of file diff --git a/modules/ChatManagement/Handler/BanStickerSet.Utils.cs b/modules/ChatManagement/Handler/BanStickerSet.Utils.cs index 78e1d85..a45d5cd 100644 --- a/modules/ChatManagement/Handler/BanStickerSet.Utils.cs +++ b/modules/ChatManagement/Handler/BanStickerSet.Utils.cs @@ -14,9 +14,9 @@ public partial class BanStickerSet { private async Task CanBotDeleteMessages() { - return await Bot.GetChatMemberAsync( + return await Bot.GetChatMember( Chat.Id, - (await Bot.GetMeAsync()).Id + (await Bot.GetMe()).Id ) is ChatMemberAdministrator {CanDeleteMessages: true}; } @@ -58,7 +58,7 @@ public partial class BanStickerSet private async Task CanUseCommands() { - return await Bot.GetChatMemberAsync(Chat.Id, From.Id) is ChatMemberAdministrator {CanDeleteMessages: true} + return await Bot.GetChatMember(Chat.Id, From.Id) is ChatMemberAdministrator {CanDeleteMessages: true} or ChatMemberOwner; } } \ No newline at end of file diff --git a/modules/ChatManagement/Handler/Rules.cs b/modules/ChatManagement/Handler/Rules.cs index 67ec764..058e7e0 100644 --- a/modules/ChatManagement/Handler/Rules.cs +++ b/modules/ChatManagement/Handler/Rules.cs @@ -39,7 +39,7 @@ class Rules : CommonHandler try { - await Bot.CopyMessageAsync(Chat.Id, Chat.Id, await _rulesService.GetRulesMessageIdAsync(Chat) ?? 0); + await Bot.CopyMessage(Chat.Id, Chat.Id, await _rulesService.GetRulesMessageIdAsync(Chat) ?? 0); } catch (ApiRequestException) { diff --git a/modules/ChatManagement/Handler/WhoIs.cs b/modules/ChatManagement/Handler/WhoIs.cs index 4ff9ba3..86e563c 100644 --- a/modules/ChatManagement/Handler/WhoIs.cs +++ b/modules/ChatManagement/Handler/WhoIs.cs @@ -55,7 +55,7 @@ public class WhoIs : CommonHandler return customStatus; } - var chatMember = await Bot.GetChatMemberAsync(Chat.Id, user.Id); + var chatMember = await Bot.GetChatMember(Chat.Id, user.Id); return chatMember.Status switch { ChatMemberStatus.Creator => "Владелец", diff --git a/modules/ChatManagement/Notifier.cs b/modules/ChatManagement/Notifier.cs index 806aea0..7c873c2 100644 --- a/modules/ChatManagement/Notifier.cs +++ b/modules/ChatManagement/Notifier.cs @@ -9,14 +9,14 @@ public class Notifier { public static async void WarnNotify(ITelegramBotClient bot, Chat chat, User from, User to, int count, bool isBanned = false) { - await bot.SendTextMessageAsync(chat.Id, $"{to.ToHtml()}, Вам выдано предупреждение! " + + await bot.SendMessage(chat.Id, $"{to.ToHtml()}, Вам выдано предупреждение! " + $"Текущее кол-во: {count}/3", disableNotification: true, parseMode: ParseMode.Html); if (isBanned) { - await bot.SendTextMessageAsync( + await bot.SendMessage( chat.Id, $"{from.ToHtml()} заблокировал {to.ToHtml()} на 7 дней", disableNotification: true, parseMode: ParseMode.Html); @@ -25,7 +25,7 @@ public class Notifier public static async void UnWarnNotify(ITelegramBotClient bot, Chat chat, User from, User to, int count) { - await bot.SendTextMessageAsync(chat.Id, + await bot.SendMessage(chat.Id, $"{to.ToHtml()}, с Вас снято предупреждение! " + $"Текущее кол-во: {count}/3", disableNotification: true, diff --git a/modules/ChatManagement/ParamParser/StickerSet.cs b/modules/ChatManagement/ParamParser/StickerSet.cs index 676ae02..fc68970 100644 --- a/modules/ChatManagement/ParamParser/StickerSet.cs +++ b/modules/ChatManagement/ParamParser/StickerSet.cs @@ -43,7 +43,7 @@ public class StickerSet var sticker = message?.ReplyToMessage?.Sticker; if (sticker is { SetName: { } }) { - result.Set = bot.GetStickerSetAsync(sticker.SetName).GetAwaiter().GetResult(); + result.Set = bot.GetStickerSet(sticker.SetName).GetAwaiter().GetResult(); result.IsValid = true; return true; } @@ -56,7 +56,7 @@ public class StickerSet { try { - result.Set = bot.GetStickerSetAsync(setName.First()) + result.Set = bot.GetStickerSet(setName.First()) .GetAwaiter() .GetResult(); result.IsValid = true; diff --git a/modules/CodeWatcher/Handler.cs b/modules/CodeWatcher/Handler.cs index 96e7f7f..ccbf4c4 100644 --- a/modules/CodeWatcher/Handler.cs +++ b/modules/CodeWatcher/Handler.cs @@ -103,9 +103,9 @@ public class Handler : BotEventHandler public async Task UploadDetectedCode(Message message) { var resp = await _haste.PostDocumentAsync(message.Text!); - await Bot.DeleteMessageAsync(Chat.Id, message.MessageId); + await Bot.DeleteMessage(Chat.Id, message.MessageId); - await Bot.SendTextMessageAsync(Chat.Id, + await Bot.SendMessage(Chat.Id, $"{message.From?.ToHtml()}, you posted something long and pre-escaped, so I decided to upload it to our paste service for you.\n" + $"Here is the link: {_haste.GetHasteUri() + resp.Key}", parseMode: ParseMode.Html); @@ -113,8 +113,8 @@ public class Handler : BotEventHandler public async Task RemoveDetectedCode(Message message) { - await Bot.DeleteMessageAsync(Chat.Id, message.MessageId); - var notifyMsg = await Bot.SendTextMessageAsync(Chat.Id, + await Bot.DeleteMessage(Chat.Id, message.MessageId); + var notifyMsg = await Bot.SendMessage(Chat.Id, (message.From?.ToHtml() ?? "") + ", не стоит публиковать столь большой код прямо в чат. " + "Вместо этого загрузите его на https://pastebin.com и отправьте в виде ссылки.", parseMode: ParseMode.Html); diff --git a/modules/CombotAntiSpam/UserJoinHandler.cs b/modules/CombotAntiSpam/UserJoinHandler.cs index feac54b..53c21b4 100644 --- a/modules/CombotAntiSpam/UserJoinHandler.cs +++ b/modules/CombotAntiSpam/UserJoinHandler.cs @@ -23,7 +23,7 @@ public class UserJoinHandler : BotEventHandler [Message(MessageFlag.HasNewChatMembers)] public async Task OnUserJoined() { - var canKickMembers = await Bot.IsUserAdminAsync(Chat, await Bot.GetMeAsync()); + var canKickMembers = await Bot.IsUserAdminAsync(Chat, await Bot.GetMe()); foreach (var member in RawUpdate.Message!.NewChatMembers!) { @@ -38,11 +38,11 @@ public class UserJoinHandler : BotEventHandler messageText.Append( $"More details you can find on CAS site."); - await Bot.SendTextMessageAsync(Chat, messageText.ToString(), parseMode: ParseMode.Html); + await Bot.SendMessage(Chat, messageText.ToString(), parseMode: ParseMode.Html); if (canKickMembers) { - await Bot.BanChatMemberAsync(Chat, member.Id); + await Bot.BanChatMember(Chat, member.Id); } } } diff --git a/modules/ContentStore/Handler/Store.cs b/modules/ContentStore/Handler/Store.cs index 8c13e2c..bcbb8ff 100644 --- a/modules/ContentStore/Handler/Store.cs +++ b/modules/ContentStore/Handler/Store.cs @@ -38,14 +38,14 @@ public class Store : CommonHandler if (_reputation == null) { - await Bot.SendTextMessageAsync(Chat.Id, "Reputation is unavailable."); + await Bot.SendMessage(Chat.Id, "Reputation is unavailable."); return; } var user = From; var reputation = await _reputation.GetUserReputationAsync(Chat, user); - await Bot.SendTextMessageAsync(Chat.Id, $"{user.ToHtml()} ({reputation}), чего пожелаете?", parseMode: ParseMode.Html, + await Bot.SendMessage(Chat.Id, $"{user.ToHtml()} ({reputation}), чего пожелаете?", parseMode: ParseMode.Html, replyMarkup: new InlineKeyboardMarkup( _provider.GetServices() .ToAsyncEnumerable() @@ -99,7 +99,7 @@ public class Store : CommonHandler var reputation = await _reputation.GetUserReputationAsync(Chat, From); if (reputation < storeItem.Price) { - await Bot.EditMessageTextAsync( + await Bot.EditMessageText( Chat.Id, messageId, $"{From.ToHtml()} ({reputation}), продолжай работать и тебе обязательно хватит на покупку.", diff --git a/modules/Reputation/Handler/Reputation.cs b/modules/Reputation/Handler/Reputation.cs index bece4af..df1d059 100644 --- a/modules/Reputation/Handler/Reputation.cs +++ b/modules/Reputation/Handler/Reputation.cs @@ -182,7 +182,7 @@ public class Reputation : CommonHandler i++; } - await Bot.SendTextMessageAsync(Chat!, msg.ToString(), parseMode: ParseMode.Html, + await Bot.SendMessage(Chat!, msg.ToString(), parseMode: ParseMode.Html, disableNotification: true); } From 226a15cb1eb1c7567237437eb68748d422dcc091 Mon Sep 17 00:00:00 2001 From: Andriy <30056636+West14@users.noreply.github.com> Date: Sun, 9 Feb 2025 19:06:41 +0200 Subject: [PATCH 04/12] fix(store): incorrect method call (SendVideo -> SendPhoto) --- modules/ContentStore/Handler/Store.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/ContentStore/Handler/Store.cs b/modules/ContentStore/Handler/Store.cs index bcbb8ff..f7aadf2 100644 --- a/modules/ContentStore/Handler/Store.cs +++ b/modules/ContentStore/Handler/Store.cs @@ -141,7 +141,7 @@ public class Store : CommonHandler switch (randomMedia.Type) { case InputMediaType.Photo: - await Bot.SendVideo(Chat.Id, file, + await Bot.SendPhoto(Chat.Id, file, caption: randomMedia.Caption, replyParameters: messageId, parseMode: ParseMode.Html, From 0649359c128e7340047ca0cf81d6be6047123aca Mon Sep 17 00:00:00 2001 From: Andriy <30056636+West14@users.noreply.github.com> Date: Sun, 9 Feb 2025 19:07:50 +0200 Subject: [PATCH 05/12] fix(store): message markup --- modules/ContentStore/Handler/Store.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/modules/ContentStore/Handler/Store.cs b/modules/ContentStore/Handler/Store.cs index f7aadf2..0467f89 100644 --- a/modules/ContentStore/Handler/Store.cs +++ b/modules/ContentStore/Handler/Store.cs @@ -8,6 +8,7 @@ using Kruzya.TelegramBot.Core.Handler; using Kruzya.TelegramBot.Core.Service; using Microsoft.Extensions.DependencyInjection; using Telegram.Bot; +using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.ReplyMarkups; using West.TelegramBot.ContentStore.Service; @@ -112,12 +113,12 @@ public class Store : CommonHandler { await PerformPurchase(mediaService, messageId); } - catch (Exception) + catch { answer = "Товар недоступен"; await Bot.EditMessageText(Chat.Id, messageId, - $"{From.ToHtml()} попытался купить \"{storeItem.Name}\", но товара в наличии не оказалось.", + $"{From.ToHtml()} попытался купить \"{storeItem.Name}\", но товара в наличии не оказалось.", ParseMode.Html); await AnswerQuery(query.Id, answer); return; From 1436911d2da6e77e6be7fe36c3c9858dbc80d146 Mon Sep 17 00:00:00 2001 From: Andriy <30056636+West14@users.noreply.github.com> Date: Sun, 9 Feb 2025 19:15:27 +0200 Subject: [PATCH 06/12] fix: add json property names, class -> record --- modules/ContentStore/Model/AnimalImage.cs | 13 +++++++++---- modules/ContentStore/Model/OBoobsItem.cs | 15 +++++++++++++-- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/modules/ContentStore/Model/AnimalImage.cs b/modules/ContentStore/Model/AnimalImage.cs index 4f3b619..2bbcea1 100644 --- a/modules/ContentStore/Model/AnimalImage.cs +++ b/modules/ContentStore/Model/AnimalImage.cs @@ -1,7 +1,12 @@ -namespace West.TelegramBot.ContentStore.Model; +using System.Text.Json.Serialization; -public class AnimalImage +namespace West.TelegramBot.ContentStore.Model; + +public record AnimalImage { - public string Id { get; set; } = null!; - public string Url { get; set; } = null!; + [JsonPropertyName("id")] + public required string Id { get; set; } + + [JsonPropertyName("url")] + public required string Url { get; set; } } \ No newline at end of file diff --git a/modules/ContentStore/Model/OBoobsItem.cs b/modules/ContentStore/Model/OBoobsItem.cs index 947016f..e85c8ad 100644 --- a/modules/ContentStore/Model/OBoobsItem.cs +++ b/modules/ContentStore/Model/OBoobsItem.cs @@ -1,10 +1,21 @@ -namespace West.TelegramBot.ContentStore.Model; +using System.Text.Json.Serialization; -public class OBoobsItem +namespace West.TelegramBot.ContentStore.Model; + +public record OBoobsItem { + [JsonPropertyName("id")] public int Id { get; set; } + + [JsonPropertyName("rank")] public int Rank { get; set; } + + [JsonPropertyName("author")] public string? Author { get; set; } + + [JsonPropertyName("model")] public string? Model { get; set; } + + [JsonPropertyName("rank")] public string Preview { get; set; } = string.Empty; } \ No newline at end of file From 2e6368d1235729eb63e80227da4349c0566e4bcd Mon Sep 17 00:00:00 2001 From: Andriy <30056636+West14@users.noreply.github.com> Date: Mon, 10 Feb 2025 00:40:04 +0200 Subject: [PATCH 07/12] chore: ignore .DotSettings.user --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index dcfdd5e..c9aaaa8 100644 --- a/.gitignore +++ b/.gitignore @@ -8,4 +8,5 @@ obj/ appsettings.json *.csproj.user +*.DotSettings.user appsettings.Development.json From ce8358d1ad431cb79bf798f6129ea0f8164e7a06 Mon Sep 17 00:00:00 2001 From: Andriy <30056636+West14@users.noreply.github.com> Date: Mon, 10 Feb 2025 00:47:19 +0200 Subject: [PATCH 08/12] fix: add build option to simplify local testing --- modules/RichSiteSummary/RichSiteSummary.csproj | 2 ++ modules/StickerTools/StickerTools.csproj | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/modules/RichSiteSummary/RichSiteSummary.csproj b/modules/RichSiteSummary/RichSiteSummary.csproj index 1adfa3e..70f3385 100644 --- a/modules/RichSiteSummary/RichSiteSummary.csproj +++ b/modules/RichSiteSummary/RichSiteSummary.csproj @@ -4,6 +4,8 @@ net8.0 TelegramBot.RichSiteSummary Kruzya.TelegramBot.RichSiteSummary + + true
diff --git a/modules/StickerTools/StickerTools.csproj b/modules/StickerTools/StickerTools.csproj index caa45e7..981644b 100644 --- a/modules/StickerTools/StickerTools.csproj +++ b/modules/StickerTools/StickerTools.csproj @@ -6,10 +6,12 @@ enable TelegramBot.StickerTools West.TelegramBot.StickerTools + + true - + From eb1d4ff14e4dbef87378fbbe5ebd02192b187dbf Mon Sep 17 00:00:00 2001 From: Andriy <30056636+West14@users.noreply.github.com> Date: Mon, 10 Feb 2025 00:48:16 +0200 Subject: [PATCH 09/12] fix: provide correct serializer options for update deserializer --- Core/Controllers/Telegram.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Core/Controllers/Telegram.cs b/Core/Controllers/Telegram.cs index 2736019..093ac6c 100644 --- a/Core/Controllers/Telegram.cs +++ b/Core/Controllers/Telegram.cs @@ -6,6 +6,7 @@ using Microsoft.Extensions.Options; using System.IO; using System.Text.Json; using System.Threading.Tasks; +using Telegram.Bot; using Telegram.Bot.Types; namespace Kruzya.TelegramBot.Core.Controllers @@ -47,7 +48,7 @@ namespace Kruzya.TelegramBot.Core.Controllers } var body = await (new StreamReader(Request.Body)).ReadToEndAsync(); - LaunchHandle(JsonSerializer.Deserialize(body)); + LaunchHandle(JsonSerializer.Deserialize(body, JsonBotAPI.Options)); return Ok(); } From 2b41746f64eff2cb5bb13ae96b50829cc03d2d1b Mon Sep 17 00:00:00 2001 From: Andriy <30056636+West14@users.noreply.github.com> Date: Mon, 24 Feb 2025 15:52:30 +0200 Subject: [PATCH 10/12] chore: replace local project dep with nuget package --- Core/Core.csproj | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Core/Core.csproj b/Core/Core.csproj index f05885c..52f08f6 100644 --- a/Core/Core.csproj +++ b/Core/Core.csproj @@ -9,6 +9,7 @@ + all runtime; build; native; contentfiles; analyzers; buildtransitive @@ -19,7 +20,4 @@ - - - From 1da8dce0f7fd0a5603242422a7b31ab28742a1f0 Mon Sep 17 00:00:00 2001 From: Andriy <30056636+West14@users.noreply.github.com> Date: Sun, 23 Mar 2025 11:32:03 +0200 Subject: [PATCH 11/12] fix: unban --- modules/ChatManagement/Handler/Ban.cs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/modules/ChatManagement/Handler/Ban.cs b/modules/ChatManagement/Handler/Ban.cs index 9af4c02..f931a5f 100644 --- a/modules/ChatManagement/Handler/Ban.cs +++ b/modules/ChatManagement/Handler/Ban.cs @@ -59,12 +59,24 @@ public class Ban : CommonHandler { return; } - + await Bot.RestrictChatMember(Chat.Id, RepliedUser!.Id, new ChatPermissions { CanSendMessages = true, + CanAddWebPagePreviews = true, + CanChangeInfo = true, + CanInviteUsers = true, + CanManageTopics = true, + CanPinMessages = true, + CanSendAudios = true, + CanSendDocuments = true, CanSendOtherMessages = true, + CanSendPhotos = true, + CanSendPolls = true, + CanSendVideos = true, + CanSendVideoNotes = true, + CanSendVoiceNotes = true, }); await Reply($"{From.ToHtml()} разблокировал {RepliedUser!.ToHtml()}"); From acaf615f30ae91d5d8adaa52e5ddfa9f118cf6b9 Mon Sep 17 00:00:00 2001 From: Andriy <30056636+West14@users.noreply.github.com> Date: Sun, 23 Mar 2025 11:33:19 +0200 Subject: [PATCH 12/12] style: add missing comment Telegram.Bot Api --- modules/ChatManagement/Handler/Ban.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/ChatManagement/Handler/Ban.cs b/modules/ChatManagement/Handler/Ban.cs index f931a5f..dc6a547 100644 --- a/modules/ChatManagement/Handler/Ban.cs +++ b/modules/ChatManagement/Handler/Ban.cs @@ -60,6 +60,7 @@ public class Ban : CommonHandler return; } + // TODO: in Telegram.Bot >=22.4.0 this could be replaced with new ChatPermissions(true) await Bot.RestrictChatMember(Chat.Id, RepliedUser!.Id, new ChatPermissions {