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;