fix: build and lots of obsolete warnings

This commit is contained in:
Andriy
2025-02-09 17:40:03 +02:00
parent 8917a8ba5f
commit c3a553f68d
29 changed files with 103 additions and 108 deletions
+3 -6
View File
@@ -3,10 +3,9 @@ using BotFramework.Config;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.IO; using System.IO;
using System.Text.Json;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot;
using Telegram.Bot.Types; using Telegram.Bot.Types;
namespace Kruzya.TelegramBot.Core.Controllers 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 const string SecretTokenHeader = "X-Telegram-Bot-Api-Secret-Token";
private readonly ILogger<Telegram> _logger; private readonly ILogger<Telegram> _logger;
private readonly ITelegramBotClient _client;
private readonly IUpdateTarget _updateTarget; private readonly IUpdateTarget _updateTarget;
private readonly string _secretToken; private readonly string _secretToken;
public Telegram(ILogger<Telegram> logger, ITelegramBotClient client, IUpdateTarget updateTarget, IOptions<BotConfig> config) public Telegram(ILogger<Telegram> logger, IUpdateTarget updateTarget, IOptions<BotConfig> config)
{ {
_logger = logger; _logger = logger;
_client = client;
_updateTarget = updateTarget; _updateTarget = updateTarget;
_secretToken = config.Value.Webhook.SecretToken; _secretToken = config.Value.Webhook.SecretToken;
@@ -50,7 +47,7 @@ namespace Kruzya.TelegramBot.Core.Controllers
} }
var body = await (new StreamReader(Request.Body)).ReadToEndAsync(); var body = await (new StreamReader(Request.Body)).ReadToEndAsync();
LaunchHandle(JsonConvert.DeserializeObject<Update>(body)); LaunchHandle(JsonSerializer.Deserialize<Update>(body));
return Ok(); return Ok();
} }
+5 -2
View File
@@ -4,11 +4,11 @@
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<AssemblyName>TelegramBot</AssemblyName> <AssemblyName>TelegramBot</AssemblyName>
<RootNamespace>Kruzya.TelegramBot.Core</RootNamespace> <RootNamespace>Kruzya.TelegramBot.Core</RootNamespace>
<Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(RunConfiguration)' == 'Core' " /> <PropertyGroup Condition=" '$(RunConfiguration)' == 'Core' " />
<ItemGroup> <ItemGroup>
<PackageReference Include="AleXr64.BotFramework" Version="2.0.8-gf720999661" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.7"> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.7">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
@@ -17,6 +17,9 @@
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.7" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.7" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.0.2" /> <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.0.2" />
<PackageReference Include="System.Linq.Async" Version="6.0.1" /> <PackageReference Include="System.Linq.Async" Version="6.0.1" />
</ItemGroup>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\AleXr64\Telegram-bot-framework\TGBotFramework\BotFramework\BotFramework.csproj" />
</ItemGroup>
</Project> </Project>
+5 -5
View File
@@ -1,21 +1,21 @@
using System; using System;
using System.Net.Http; using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks; using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Kruzya.TelegramBot.Core.Extensions; namespace Kruzya.TelegramBot.Core.Extensions;
public static class HttpClientExtension public static class HttpClientExtension
{ {
public static async Task<T> GetJsonAsync<T>(this HttpClient client, Uri requestUri) public static async Task<T?> GetJsonAsync<T>(this HttpClient client, Uri requestUri)
{ {
var response = await client.GetStringAsync(requestUri); var response = await client.GetStringAsync(requestUri);
return JsonConvert.DeserializeObject<T>(response); return JsonSerializer.Deserialize<T>(response);
} }
public static async Task<T> GetJsonAsync<T>(this HttpClient client, string requestUri) public static async Task<T?> GetJsonAsync<T>(this HttpClient client, string requestUri)
{ {
var response = await client.GetStringAsync(requestUri); var response = await client.GetStringAsync(requestUri);
return JsonConvert.DeserializeObject<T>(response); return JsonSerializer.Deserialize<T>(response);
} }
} }
+4 -4
View File
@@ -26,8 +26,8 @@ public abstract class CommonHandler : BotEventHandler
protected virtual async Task<Message> Reply(string text) protected virtual async Task<Message> Reply(string text)
{ {
return await Bot.SendTextMessageAsync(Chat.Id, text, return await Bot.SendMessage(Chat.Id, text,
replyToMessageId: Message?.MessageId, parseMode: ParseMode.Html); replyParameters: Message?.MessageId, parseMode: ParseMode.Html);
} }
protected async Task<bool> CanPunish() protected async Task<bool> CanPunish()
@@ -38,14 +38,14 @@ public abstract class CommonHandler : BotEventHandler
protected async Task BanMember(long userId, DateTime banEnd) protected async Task BanMember(long userId, DateTime banEnd)
{ {
await Bot.RestrictChatMemberAsync( await Bot.RestrictChatMember(
Chat.Id, Chat.Id,
userId, userId,
new ChatPermissions new ChatPermissions
{ {
CanSendMessages = false CanSendMessages = false
}, },
banEnd untilDate: banEnd
); );
} }
+1 -7
View File
@@ -60,17 +60,11 @@ public class Ban : CommonHandler
return; return;
} }
await Bot.RestrictChatMemberAsync(Chat.Id, RepliedUser!.Id, await Bot.RestrictChatMember(Chat.Id, RepliedUser!.Id,
new ChatPermissions new ChatPermissions
{ {
CanSendMessages = true, CanSendMessages = true,
CanChangeInfo = true,
CanInviteUsers = true,
CanPinMessages = true,
CanSendPolls = true,
CanSendMediaMessages = true,
CanSendOtherMessages = true, CanSendOtherMessages = true,
CanAddWebPagePreviews = true
}); });
await Reply($"{From.ToHtml()} <code>разблокировал</code> {RepliedUser!.ToHtml()}"); await Reply($"{From.ToHtml()} <code>разблокировал</code> {RepliedUser!.ToHtml()}");
+2 -2
View File
@@ -46,7 +46,7 @@ public class Greet : BotEventHandler
reply.Text("Пожалуйста, ознакомьтесь с правилами. /rules"); reply.Text("Пожалуйста, ознакомьтесь с правилами. /rules");
} }
await Bot.SendTextMessageAsync(Chat.Id, string.Format(reply.ToString(), membersHtml), await Bot.SendMessage(Chat.Id, string.Format(reply.ToString(), membersHtml),
parseMode: ParseMode.Html, replyToMessageId: message.MessageId); parseMode: ParseMode.Html, replyParameters: message.MessageId);
} }
} }
@@ -36,20 +36,20 @@ public class WarnService
{ {
try try
{ {
await _bot.RestrictChatMemberAsync( await _bot.RestrictChatMember(
chat.Id, chat.Id,
to.Id, to.Id,
new ChatPermissions new ChatPermissions
{ {
CanSendMessages = false CanSendMessages = false
}, },
DateTime.Now.AddDays(7) untilDate: DateTime.Now.AddDays(7)
); );
warnCount = 0; warnCount = 0;
} }
catch catch
{ {
await _bot.SendTextMessageAsync(chat.Id, "У меня нет прав на блокировку пользователя."); await _bot.SendMessage(chat.Id, "У меня нет прав на блокировку пользователя.");
} }
} }
@@ -1,5 +1,5 @@
using System; using System;
using Newtonsoft.Json; using System.Text.Json.Serialization;
namespace Kruzya.TelegramBot.CombotAntiSpam.Combot; namespace Kruzya.TelegramBot.CombotAntiSpam.Combot;
@@ -7,24 +7,24 @@ internal class CombotApiResponse
{ {
public class ApiResult public class ApiResult
{ {
[JsonProperty("messages")] [JsonPropertyName("messages")]
public string[] Messages { get; set; } public string[] Messages { get; set; }
[JsonProperty("time_added")] [JsonPropertyName("time_added")]
public int TimeAdded { get; set; } public int TimeAdded { get; set; }
[JsonProperty("offenses")] [JsonPropertyName("offenses")]
public int Offenses { get; set; } public int Offenses { get; set; }
public DateTime AddedAt => DateTimeOffset.FromUnixTimeSeconds(TimeAdded).DateTime; public DateTime AddedAt => DateTimeOffset.FromUnixTimeSeconds(TimeAdded).DateTime;
} }
[JsonProperty("ok")] [JsonPropertyName("ok")]
public bool IsSpammer { get; set; } public bool IsSpammer { get; set; }
[JsonProperty("description")] [JsonPropertyName("description")]
public string Description { get; set; } public string Description { get; set; }
[JsonProperty("result")] [JsonPropertyName("result")]
public ApiResult Result { get; set; } public ApiResult Result { get; set; }
} }
@@ -22,6 +22,6 @@ public class CombotClient : ICombotClient
public async Task<bool> IsSpammerAsync(User user) public async Task<bool> IsSpammerAsync(User user)
{ {
var result = await _httpClient.GetJsonAsync<CombotApiResponse>($"?user_id={user.Id}"); var result = await _httpClient.GetJsonAsync<CombotApiResponse>($"?user_id={user.Id}");
return result.IsSpammer; return result?.IsSpammer ?? false;
} }
} }
+2 -1
View File
@@ -1,9 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<AssemblyName>TelegramBot.CombotAntiSpam</AssemblyName> <AssemblyName>TelegramBot.CombotAntiSpam</AssemblyName>
<RootNamespace>Kruzya.TelegramBot.CombotAntiSpam</RootNamespace> <RootNamespace>Kruzya.TelegramBot.CombotAntiSpam</RootNamespace>
<Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
+6 -6
View File
@@ -115,7 +115,7 @@ public class Store : CommonHandler
catch (Exception) catch (Exception)
{ {
answer = "Товар недоступен"; answer = "Товар недоступен";
await Bot.EditMessageTextAsync(Chat.Id, await Bot.EditMessageText(Chat.Id,
messageId, messageId,
$"<b>{From.ToHtml()} попытался купить \"{storeItem.Name}\", но товара в наличии не оказалось.", $"<b>{From.ToHtml()} попытался купить \"{storeItem.Name}\", но товара в наличии не оказалось.",
ParseMode.Html); ParseMode.Html);
@@ -124,7 +124,7 @@ public class Store : CommonHandler
} }
reputation = await _reputation.SetUserReputationAsync(Chat, From, reputation - storeItem.Price); reputation = await _reputation.SetUserReputationAsync(Chat, From, reputation - storeItem.Price);
await Bot.EditMessageTextAsync(Chat.Id, await Bot.EditMessageText(Chat.Id,
messageId, messageId,
$"<b>{From.ToHtml()} ({reputation})</b> купил \"{storeItem.Name}\".", $"<b>{From.ToHtml()} ({reputation})</b> купил \"{storeItem.Name}\".",
ParseMode.Html); ParseMode.Html);
@@ -141,17 +141,17 @@ public class Store : CommonHandler
switch (randomMedia.Type) switch (randomMedia.Type)
{ {
case InputMediaType.Photo: case InputMediaType.Photo:
await Bot.SendPhotoAsync(Chat.Id, file, await Bot.SendVideo(Chat.Id, file,
caption: randomMedia.Caption, caption: randomMedia.Caption,
replyToMessageId: messageId, replyParameters: messageId,
parseMode: ParseMode.Html, parseMode: ParseMode.Html,
hasSpoiler: randomMedia.Nsfw hasSpoiler: randomMedia.Nsfw
); );
break; break;
case InputMediaType.Video: case InputMediaType.Video:
await Bot.SendVideoAsync(Chat.Id, file, await Bot.SendVideo(Chat.Id, file,
caption: randomMedia.Caption, caption: randomMedia.Caption,
replyToMessageId: messageId, replyParameters: messageId,
parseMode: ParseMode.Html, parseMode: ParseMode.Html,
hasSpoiler: randomMedia.Nsfw hasSpoiler: randomMedia.Nsfw
); );
+2 -2
View File
@@ -5,14 +5,14 @@ namespace West.TelegramBot.ContentStore.Model;
public class RandomMedia 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; File = file;
Caption = caption; Caption = caption;
Nsfw = nsfw; Nsfw = nsfw;
} }
public IInputFile File; public InputFile File;
public string? Caption; public string? Caption;
public bool Nsfw; public bool Nsfw;
@@ -22,7 +22,7 @@ public class AnimBoobsService : AbstractNsfwService
// https://bugs.telegram.org/c/23674 workaround // https://bugs.telegram.org/c/23674 workaround
var video = await _httpClient.GetStreamAsync($"https://westdev.me/_boobs/media/{fileName}"); 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, Type = InputMediaType.Video,
Nsfw = true Nsfw = true
@@ -1,4 +1,4 @@
using Newtonsoft.Json; using System.Text.Json;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using West.TelegramBot.ContentStore.Model; using West.TelegramBot.ContentStore.Model;
@@ -18,7 +18,7 @@ public abstract class AnimalAsAService : IRandomMediaService
public async Task<RandomMedia> GetRandomMediaAsync(Chat chat, User user) public async Task<RandomMedia> GetRandomMediaAsync(Chat chat, User user)
{ {
var resp = await _httpClient.GetAsync("images/search"); var resp = await _httpClient.GetAsync("images/search");
var catImage = JsonConvert.DeserializeObject<List<AnimalImage>>(await resp.Content.ReadAsStringAsync())![0]; var catImage = JsonSerializer.Deserialize<List<AnimalImage>>(await resp.Content.ReadAsStringAsync())![0];
return new RandomMedia(new InputFileUrl(catImage.Url)); return new RandomMedia(new InputFileUrl(catImage.Url));
} }
} }
@@ -25,7 +25,7 @@ public abstract class AbstractKittiesService : IRandomMediaService
var response = await _api.GetKittiesImageAsync(VideoType); var response = await _api.GetKittiesImageAsync(VideoType);
return new RandomMedia( return new RandomMedia(
new InputFile(response.Content), new InputFileStream(response.Content),
new HtmlString().Url(response.Source, response.Title).ToString(), new HtmlString().Url(response.Source, response.Title).ToString(),
true true
); );
@@ -1,4 +1,4 @@
using Newtonsoft.Json; using System.Text.Json;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using West.TelegramBot.ContentStore.Model; using West.TelegramBot.ContentStore.Model;
using West.TelegramBot.ContentStore.Option; 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]}/ // "/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 httpResp = await _httpClient.GetAsync("boobs/1/1/random");
var boobsResponse = JsonConvert.DeserializeObject<List<OBoobsItem>>(await httpResp.Content.ReadAsStringAsync()); var boobsResponse = JsonSerializer.Deserialize<List<OBoobsItem>>(await httpResp.Content.ReadAsStringAsync());
var boobsItem = boobsResponse![0]; var boobsItem = boobsResponse![0];
var boobsId = boobsItem.Id.ToString("D5"); var boobsId = boobsItem.Id.ToString("D5");
+4 -2
View File
@@ -4,13 +4,15 @@ using BotFramework.Enums;
using BotFramework.Utils; using BotFramework.Utils;
using Kruzya.TelegramBot.Core.Extensions; using Kruzya.TelegramBot.Core.Extensions;
using Kruzya.TelegramBot.Core.Service; using Kruzya.TelegramBot.Core.Service;
using Newtonsoft.Json; using System.Text.Json;
namespace West.TelegramBot.DebugTools; namespace West.TelegramBot.DebugTools;
public class Handler : BotEventHandler public class Handler : BotEventHandler
{ {
private readonly UserService _userService; private readonly UserService _userService;
private static readonly JsonSerializerOptions DumpOptions = new() { WriteIndented = true };
public Handler(UserService userService) public Handler(UserService userService)
{ {
@@ -26,7 +28,7 @@ public class Handler : BotEventHandler
} }
var message = RawUpdate.Message!.ReplyToMessage ?? RawUpdate.Message; var message = RawUpdate.Message!.ReplyToMessage ?? RawUpdate.Message;
var text = HtmlString.Empty 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); await Bot.SendHtmlStringAsync(Chat, text, replyTo: message.MessageId);
} }
+1 -1
View File
@@ -58,6 +58,6 @@ public class Common : BotEventHandler
.Br(); .Br();
} }
await Bot.SendTextMessageAsync(Chat.Id, msg.ToString(), parseMode: ParseMode.Html); await Bot.SendMessage(Chat.Id, msg.ToString(), parseMode: ParseMode.Html);
} }
} }
@@ -54,7 +54,7 @@ public abstract class AbstractAnimationReply : BotEventHandler
animationFileOption.SetValue(animation.FileId); animationFileOption.SetValue(animation.FileId);
_db.AddOrUpdate(animationFileOption); _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<bool> HandleAnimation() protected virtual async Task<bool> HandleAnimation()
@@ -84,8 +84,8 @@ public abstract class AbstractAnimationReply : BotEventHandler
return false; return false;
} }
await Bot.SendAnimationAsync(Chat.Id, new InputFileId(animationFileId), await Bot.SendAnimation(Chat.Id, new InputFileId(animationFileId),
replyToMessageId: GetMessageIdToReply() ?? Message?.MessageId); replyParameters: GetMessageIdToReply() ?? Message?.MessageId);
nextUseOption.SetValue(DateTime.Now + Cooldown); nextUseOption.SetValue(DateTime.Now + Cooldown);
_db.AddOrUpdate(nextUseOption); _db.AddOrUpdate(nextUseOption);
+1 -1
View File
@@ -35,7 +35,7 @@ public class Bayan : AbstractAnimationReply
{ {
if (await HandleAnimation()) if (await HandleAnimation())
{ {
await Bot.DeleteMessageAsync(Chat.Id, Message!.MessageId); await Bot.DeleteMessage(Chat.Id, Message!.MessageId);
} }
} }
+7 -7
View File
@@ -61,7 +61,7 @@ public class Guess : CommonHandler
var doesExist = guessDict.Any(pair => pair.Value.UserId == From.Id); var doesExist = guessDict.Any(pair => pair.Value.UserId == From.Id);
if (doesExist) if (doesExist)
{ {
await Bot.SendTextMessageAsync(Chat, "Вы уже запустили игру."); await Bot.SendMessage(Chat, "Вы уже запустили игру.");
return; return;
} }
@@ -81,8 +81,8 @@ public class Guess : CommonHandler
new("3") { CallbackData = $"guess|{From.Id}|answer|3" } new("3") { CallbackData = $"guess|{From.Id}|answer|3" }
}); });
var message = await Bot.SendTextMessageAsync(Chat.Id, "Выберите число от 1 до 3.", var message = await Bot.SendMessage(Chat.Id, "Выберите число от 1 до 3.",
replyToMessageId: messageId, replyParameters: messageId,
replyMarkup: keyBoard replyMarkup: keyBoard
); );
@@ -127,7 +127,7 @@ public class Guess : CommonHandler
return; return;
} }
await Bot.AnswerCallbackQueryAsync(CallbackQuery.Id); await Bot.AnswerCallbackQuery(CallbackQuery.Id);
guessDict.TryRemove((int) messageId, out _); guessDict.TryRemove((int) messageId, out _);
_guessCache.SetValue(Chat.Id, guessDict, -1); _guessCache.SetValue(Chat.Id, guessDict, -1);
@@ -152,7 +152,7 @@ public class Guess : CommonHandler
_db.AddOrUpdate(cooldownOption); _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. // Drop bot message.
_requests.Add(new DeleteRequest _requests.Add(new DeleteRequest
@@ -166,8 +166,8 @@ public class Guess : CommonHandler
protected override async Task<Message> Reply(string text) protected override async Task<Message> Reply(string text)
{ {
// TODO: move feature with autocleaning to Core CommonHandler. // TODO: move feature with autocleaning to Core CommonHandler.
var message = await Bot.SendTextMessageAsync(Chat.Id, text, var message = await Bot.SendMessage(Chat.Id, text,
replyToMessageId: Message?.MessageId, parseMode: ParseMode.Html); replyParameters: Message?.MessageId, parseMode: ParseMode.Html);
_requests.Add(new DeleteRequest _requests.Add(new DeleteRequest
{ {
+3 -3
View File
@@ -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<Message> Reply(string text) protected override async Task<Message> Reply(string text)
{ {
// TODO: move feature with autocleaning to Core CommonHandler. // TODO: move feature with autocleaning to Core CommonHandler.
var message = await Bot.SendTextMessageAsync(Chat.Id, text, var message = await Bot.SendMessage(Chat.Id, text,
replyToMessageId: Message?.MessageId, parseMode: ParseMode.Html); replyParameters: Message?.MessageId, parseMode: ParseMode.Html);
_requests.Add(new DeleteRequest _requests.Add(new DeleteRequest
{ {
+17 -15
View File
@@ -12,6 +12,7 @@ using Telegram.Bot;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups; using Telegram.Bot.Types.ReplyMarkups;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
namespace Kruzya.TelegramBot.RichSiteSummary.Handler; namespace Kruzya.TelegramBot.RichSiteSummary.Handler;
@@ -71,11 +72,12 @@ public class FeedList : AbstractHandler
var inlineButtons = new InlineKeyboardMarkup(buttons); var inlineButtons = new InlineKeyboardMarkup(buttons);
if (message == null) 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 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))) if (!(await GenerateMenu(query)))
{ {
await Bot.SendTextMessageAsync(Chat, $"No one feed match by search pattern (<code>{query}</code>).", 0, ParseMode.Html, null, true); await Bot.SendMessage(Chat, $"No one feed match by search pattern (<code>{query}</code>).", ParseMode.Html,
linkPreviewOptions: true);
} }
} }
@@ -96,8 +99,7 @@ public class FeedList : AbstractHandler
{ {
if (!(await GenerateMenu(":sub"))) if (!(await GenerateMenu(":sub")))
{ {
await Bot.SendTextMessageAsync(Chat, await Bot.SendMessage(Chat, "There are no one subscription. Add new with /feed_list or /feed_search.");
"There are no one subscription. Add new with /feed_list or /feed_search.");
} }
} }
@@ -191,13 +193,13 @@ public class FeedList : AbstractHandler
if (editableMessage == null) if (editableMessage == null)
{ {
await Bot.SendTextMessageAsync(Chat, "Select the feed for viewing details", 0, null, await Bot.SendMessage(Chat, "Select the feed for viewing details", linkPreviewOptions: true,
null, true, true, false, 0, replyMarkup: new InlineKeyboardMarkup(buttons)); disableNotification: true, replyMarkup: new InlineKeyboardMarkup(buttons));
} }
else else
{ {
await Bot.EditMessageTextAsync(editableMessage.Chat, editableMessage.MessageId, "Select the feed for viewing details", null, null, false, await Bot.EditMessageText(editableMessage.Chat, editableMessage.MessageId,
new InlineKeyboardMarkup(buttons)); "Select the feed for viewing details", replyMarkup: new InlineKeyboardMarkup(buttons));
} }
return true; return true;
@@ -219,7 +221,7 @@ public class FeedList : AbstractHandler
var fromId = Int64.Parse(data[1]); var fromId = Int64.Parse(data[1]);
if (fromId != From.Id) 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); "You can't perform this action: command called by another user.", true);
return; return;
} }
@@ -238,13 +240,13 @@ public class FeedList : AbstractHandler
case "do": case "do":
if (RawUpdate.CallbackQuery.From.Id != RawUpdate.CallbackQuery.Message.Chat.Id) 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[] var allowedUserStatuses = new ChatMemberStatus[]
{ChatMemberStatus.Administrator, ChatMemberStatus.Creator}; {ChatMemberStatus.Administrator, ChatMemberStatus.Creator};
if (!allowedUserStatuses.Contains(userStatus)) 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); "You can't perform this action: you don't have administrator permissions.", true);
return; return;
} }
@@ -268,12 +270,12 @@ public class FeedList : AbstractHandler
idx++; idx++;
} }
await Bot.SendTextMessageAsync(RawUpdate.CallbackQuery.Message.Chat, messageTextBuilder.ToString(), await Bot.SendMessage(RawUpdate.CallbackQuery.Message.Chat, messageTextBuilder.ToString(),
0, ParseMode.Html, null, true); ParseMode.Html, linkPreviewOptions: true);
break; 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) protected async Task ChangeFeedSubscription(Guid feedId, Chat chat, User from, Message message)
@@ -31,6 +31,6 @@ public class StatsHandler : AbstractHandler
textMessage.Append( textMessage.Append(
$"- exists <b>{subscriptionsCount} subscriptions on feeds</b> (<b>unique subscribers: {uniqueSubscribers}</b>)"); $"- exists <b>{subscriptionsCount} subscriptions on feeds</b> (<b>unique subscribers: {uniqueSubscribers}</b>)");
await Bot.SendTextMessageAsync(Chat, textMessage.ToString(), parseMode: ParseMode.Html); await Bot.SendMessage(Chat, textMessage.ToString(), parseMode: ParseMode.Html);
} }
} }
@@ -36,14 +36,12 @@ public class MessageSender : AbstractTimedHostedService
{ {
if (string.IsNullOrWhiteSpace(message.ImageUrl)) if (string.IsNullOrWhiteSpace(message.ImageUrl))
{ {
await _bot.BotClient.SendTextMessageAsync(message.ChatId, message.Text, 0, message.ParseMode, null, await _bot.BotClient.SendMessage(message.ChatId, message.Text, message.ParseMode, linkPreviewOptions: message.DisableWebPagePreview);
message.DisableWebPagePreview);
} }
else else
{ {
await _bot.BotClient.SendPhotoAsync(message.ChatId, new InputFileUrl(message.ImageUrl), 0, message.Text, await _bot.BotClient.SendPhoto(message.ChatId, new InputFileUrl(message.ImageUrl), message.Text, message.ParseMode);
message.ParseMode, null, false, message.DisableWebPagePreview);
} }
} }
catch (ApiRequestException e) catch (ApiRequestException e)
+4 -4
View File
@@ -19,9 +19,9 @@ public class Handler : BotEventHandler
return; return;
} }
await Bot.SendChatActionAsync(Chat.Id, ChatAction.UploadDocument); await Bot.SendChatAction(Chat.Id, ChatAction.UploadDocument);
using var file = new MemoryStream(); using var file = new MemoryStream();
await Bot.GetInfoAndDownloadFileAsync(sticker.FileId, file); await Bot.GetInfoAndDownloadFile(sticker.FileId, file);
file.Position = 0; file.Position = 0;
using var img = await Image.LoadAsync(file); using var img = await Image.LoadAsync(file);
@@ -30,7 +30,7 @@ public class Handler : BotEventHandler
using var outfile = new MemoryStream(); using var outfile = new MemoryStream();
await img.SaveAsPngAsync(outfile); await img.SaveAsPngAsync(outfile);
outfile.Position = 0; outfile.Position = 0;
await Bot.SendDocumentAsync(Chat.Id, new InputFile(outfile, "sticker.png"), await Bot.SendDocument(Chat.Id, new InputFileStream(outfile, "sticker.png"),
replyToMessageId: RawUpdate?.Message?.MessageId); replyParameters: RawUpdate?.Message?.MessageId);
} }
} }
+2 -2
View File
@@ -23,7 +23,7 @@ public static class MessageExtension
{ {
try try
{ {
var chat = await bot.GetChatAsync( var chat = await bot.GetChat(
new ChatId(message.Text.Substring(mention.Offset, mention.Length))); new ChatId(message.Text.Substring(mention.Offset, mention.Length)));
if (chat != null) 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[] if ((new ChatMemberStatus[]
{ {
+4 -5
View File
@@ -8,7 +8,6 @@ using Kruzya.TelegramBot.Core.Data;
using Kruzya.TelegramBot.Core.Extensions; using Kruzya.TelegramBot.Core.Extensions;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Telegram.Bot; using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.Enums;
namespace Kruzya.TelegramBot.UrlLimitations; 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) > if (message.Entities.Count(e => e.Type == MessageEntityType.Url || e.Type == MessageEntityType.TextLink) >
0 || await message.HasUnknownMention(Bot)) 0 || await message.HasUnknownMention(Bot))
{ {
var targetChat = new ChatId(Chat.Id); var targetChat = Chat.Id;
Task.WaitAll( Task.WaitAll(
Bot.BanChatMemberAsync(new ChatId(Chat.Id), From.Id, DateTime.Now.AddDays(1)), Bot.BanChatMember(targetChat, From.Id, DateTime.Now.AddDays(1)),
Bot.DeleteMessageAsync(targetChat, message.MessageId), Bot.DeleteMessage(targetChat, message.MessageId),
Bot.SendTextMessageAsync(targetChat, Bot.SendMessage(targetChat,
$"Member {From.ToHtml(true)} has been banned.\n<b>Reason</b>: <pre>Spam suspicion</pre>", parseMode: ParseMode.Html) $"Member {From.ToHtml(true)} has been banned.\n<b>Reason</b>: <pre>Spam suspicion</pre>", parseMode: ParseMode.Html)
); );
} }
+7 -8
View File
@@ -48,7 +48,7 @@ public class Handler : BotEventHandler
var memberList = tagDictionary.GetValueOrDefault(groupName, new List<long>()); var memberList = tagDictionary.GetValueOrDefault(groupName, new List<long>());
if (memberList.Contains(fromId)) if (memberList.Contains(fromId))
{ {
await Bot.SendTextMessageAsync(chatId, $"{from.ToHtml()} уже находится в группе {groupName}", await Bot.SendMessage(chatId, $"{from.ToHtml()} уже находится в группе {groupName}",
parseMode: ParseMode.Html); parseMode: ParseMode.Html);
return; return;
} }
@@ -58,8 +58,8 @@ public class Handler : BotEventHandler
userGroupOption.SetValue(tagDictionary); userGroupOption.SetValue(tagDictionary);
_db.AddOrUpdate(userGroupOption); _db.AddOrUpdate(userGroupOption);
_userCache.SetValue(repliedMessage.From.Id, repliedMessage.From, Int32.MaxValue); _userCache.SetValue(repliedMessage.From.Id, repliedMessage.From, int.MaxValue);
await Bot.SendTextMessageAsync(chatId, $"{from.ToHtml()} добавлен в группу {groupName}", await Bot.SendMessage(chatId, $"{from.ToHtml()} добавлен в группу {groupName}",
parseMode: ParseMode.Html); parseMode: ParseMode.Html);
} }
@@ -89,16 +89,15 @@ public class Handler : BotEventHandler
msg.UserMention(await GetUser(userId, Chat)).Text(", "); 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<User> GetUser(long userId, Chat chat) protected async Task<User> GetUser(long userId, Chat chat)
{ {
User user; if (!_userCache.TryGetValue(userId, out var user))
if (!_userCache.TryGetValue(userId, out user))
{ {
user = (await Bot.GetChatMemberAsync(Chat.Id, userId)).User; user = (await Bot.GetChatMember(Chat.Id, userId)).User;
_userCache.SetValue(userId, user, Int32.MaxValue); _userCache.SetValue(userId, user, int.MaxValue);
} }
return user; return user;