diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 1b843c21..d9e0e82c 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -21,9 +21,9 @@ jobs: - uses: actions/checkout@v3 - name: Setup .NET - uses: actions/setup-dotnet@v3 + uses: actions/setup-dotnet@v4 with: - dotnet-version: 6.0.x + dotnet-version: 8.0.x - name: Restore dependencies run: dotnet restore diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml index 18267070..39193e27 100644 --- a/.github/workflows/publish.yaml +++ b/.github/workflows/publish.yaml @@ -16,9 +16,9 @@ jobs: - uses: actions/checkout@v3 - name: Setup .NET - uses: actions/setup-dotnet@v3 + uses: actions/setup-dotnet@v4 with: - dotnet-version: 6.0.x + dotnet-version: 8.0.x - name: Restore dependencies run: dotnet restore diff --git a/README.md b/README.md index 6f929fe2..59995ff4 100644 --- a/README.md +++ b/README.md @@ -2,18 +2,18 @@ | -------------------------------------------------- | -------------------------------- | [![NuGet version (Telegram.BotAPI)](https://img.shields.io/nuget/v/Telegram.BotAPI.svg?style=flat-square)](https://www.nuget.org/packages/Telegram.BotAPI/) -[![Compatible with Bot API v6.9](https://img.shields.io/badge/Bot%20API%20version-v6.9-blue?style=flat-square)](https://core.telegram.org/bots/api#september-22-2023) +[![Compatible with Bot API v7.0](https://img.shields.io/badge/Bot%20API%20version-v7.0-blue?style=flat-square)](https://core.telegram.org/bots/api#december-29-2023) **Telegram.BotAPI** is one of the most complete libraries available to interact with the Telegram Bot API in your .NET projects. Free and open source. -It contains all the methods and types available in the Bot API 6.9 released on September 22, 2023. +It contains all the methods and types available in the Bot API 7.0 released on December 29, 2023. --- ## Features -- Contains pre-defined methods for all Bot API 6.9 methods. -- Contains classes for each object type used in the Bot API 6.9. +- Contains pre-defined methods for all Bot API 7.0 methods. +- Contains classes for each object type used in the Bot API 7.0. - Sync and async methods. - Support [System.Text.Json](https://www.nuget.org/packages/System.Text.Json/) and [Newtonsoft.Json](https://www.nuget.org/packages/Newtonsoft.Json/). @@ -22,7 +22,7 @@ It contains all the methods and types available in the Bot API 6.9 released on S ## .NET platforms support - NET Standard >= 2.0 -- NET Core >= 2.0, .NET 5|6|7 +- NET Core >= 2.0, .NET 6, .NET 8 - NET Framework >= 4.6.2 - Universal Windows Platform >= 10.0.16299 - Unity >= 2018.1 @@ -43,14 +43,14 @@ dotnet add PROJECT package Telegram.BotAPI ## How to use -First, get your **bot token** from [BotFather](https://t.me/BotFather) and use it to create a new instance of `Telegram.BotAPI.BotClient` as follows. +First, get your **bot token** from [BotFather](https://t.me/BotFather) and use it to create a new instance of `Telegram.BotAPI.TelegramBotClient` as follows. ```CSharp using Telegram.BotAPI; var botToken = "bot123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"; -// You need a BotClient instance if you want access to the Bot API methods. -var api = new BotClient(botToken); +// You need a TelegramBotClient instance if you want access to the Bot API methods. +var client = new TelegramBotClient(botToken); ``` The methods and types are organized in namespaces according to their corresponding section on the [Official Bot API website](https://core.telegram.org/bots/api). So if you want to use a method or type, you must first include the corresponding namespace. @@ -59,7 +59,7 @@ Currently the following namespaces are available: | Name | Description | | :------------------------------- | :----------------------------------------------- | -| Telegram.BotAPI | Contains the BotClient and other utilities | +| Telegram.BotAPI | Contains the TelegramBotClient and other utilities | | Telegram.BotAPI.GettingUpdates | Contains methods and types for getting updates | | Telegram.BotAPI.AvailableTypes | Contains available types | | Telegram.BotAPI.AvailableMethods | Contains available methods | @@ -70,12 +70,12 @@ Currently the following namespaces are available: | Telegram.BotAPI.TelegramPassport | Contains methods and types for Telegram Passport | | Telegram.BotAPI.Games | Contains methods and types for games | -Once the namespaces are included, you are ready to start managing your bot. For example, you can use the [getMe](https://core.telegram.org/bots/api#sendmessage) method to get basic information about your bot. +Once the namespaces are included, you are ready to start managing your bot. For example, you can use the [getMe](https://core.telegram.org/bots/api#getme) method to get basic information about your bot. ```CSharp using Telegram.BotAPI.AvailableMethods; -var me = api.GetMe(); +var me = client.GetMe(); Console.WriteLine("My name is {0}.", me.FirstName); ``` @@ -83,7 +83,7 @@ Console.WriteLine("My name is {0}.", me.FirstName); Every time a user interacts with a bot, bot will receive a new update. Updates contain information about user events, such as a new message or when a button is clicked. If you want your bot to reply to a message, then your bot must be able to get updates first. -Currently, there are two ways to get updates: [Long Polling](###Long-Polling) and [webhooks](###Webhooks). +Currently, there are two ways to get updates: [Long Polling](#long-polling) and [webhooks](#webhooks). ### Long Polling @@ -93,7 +93,7 @@ To get updates using **Long Polling**, you must create a perpetual loop and chec using System.Linq; using Telegram.BotAPI.GettingUpdates; -var updates = api.GetUpdates(); +var updates = client.GetUpdates(); while (true) { if (updates.Any()) @@ -103,11 +103,11 @@ while (true) // Process update } var offset = updates.Last().UpdateId + 1; - updates = api.GetUpdates(offset); + updates = client.GetUpdates(offset); } else { - updates = api.GetUpdates(); + updates = client.GetUpdates(); } } ``` @@ -120,12 +120,16 @@ To receive updates through webhook, you must create a web application. In your A using Telegram.BotAPI.GettingUpdates; [HttpPost] -public IActionResult Post([FromBody] Update update) +public IActionResult Post( + // The secret token is optional, but it's highly recommended to use it. + [FromHeader(Name = "X-Telegram-Bot-Api-Secret-Token")] string secretToken, + [FromBody] Update update) { - if (update == null) + if (update is null) { return BadRequest(); } + // Check if the secret token is valid // Process your update return Ok(); } @@ -138,9 +142,8 @@ api.DeleteWebhook(true); // Delete old webhook api.SetWebhook("https://example.com/"); // Set new webhook ``` -> It's high recommended to use a secret path to access the api controller. - -> Using webhook will disable the `getUpdates` method. Use `deleteWebhook` to enable it again. +> It's high recommended to configurate a secret token to access the api controller through the setWebhook method. This will prevent third parties from accessing your api controller. +> Using a webhook will disable the `getUpdates` method. Use `deleteWebhook` to enable it again. ## Sending messages @@ -157,7 +160,7 @@ Your bot can also send multimedia messages like photos, gifs, videos, and others ## Uploading files -You can send attached files using InputFile objects. You have two ways to do it. +You can also send attached files using InputFile objects. You have two ways to do it: By using an InputFile object directly or by using an AttachedFile object. ### Option 1 @@ -187,6 +190,50 @@ var files = new AttachedFile[] api.SendDocument(chatId, "attach://file56", attachedFiles: files); ``` +## Making custom requests + +The library already includes all types and methods available in the Bot API. However, if you want to use your own types or if you want to be the first one to use new features when they are released, you can use the `CallMethod` and/or `CallMethodDirect` methods defined in the ITelegramBotClient instance. + +```CSharp +var args = new Dictionary() { + { "chat_id", 123456789 }, + { "text", "Hello World!" } +}; +// Message is the type you want to use to deserialize the response result. It can be an in-built type or a custom type created by you. +var message = client.CallMethod("sendMessage", args); +``` + +The previous method is used by all extension methods defined in the library. You can also create your own extension methods to make custom requests if you want. + +```CSharp +public static class TelegramBotClientExtensions +{ + public static Message SendHelloWorld(this ITelegramBotClient client, long chatId) + { + var args = new Dictionary() { + { "chat_id", chatId }, + { "text", "Hello World!" } + }; + return client.CallMethod("sendMessage", args); + } +} +``` + +The library also includes the classes `MethodNames` and `PropertyNames` that contain the names of all methods and properties. + +The `CallMethod` will trigger an exception if the response status code is not OK. If you don't like this behavior, you can use the `CallMethodDirect` method instead. + +```CSharp +var args = new Dictionary() { + { "chat_id", 123456789 }, + { "text", "Hello World!" } +}; +// BotResponse +var response = client.CallMethodDirect("sendMessage", args); +``` + +You'll get a `BotResponse` object as a response. This object contains the status code, the deserialized result or null (if error), the error description and also some error parameters if available. + --- ## Examples diff --git a/src/.editorconfig b/src/.editorconfig index 469be7a9..9b94bb60 100644 --- a/src/.editorconfig +++ b/src/.editorconfig @@ -49,6 +49,9 @@ csharp_style_prefer_not_pattern = true:suggestion csharp_style_pattern_matching_over_as_with_null_check = true:suggestion csharp_style_var_when_type_is_apparent = false:silent csharp_style_var_elsewhere = false:silent +csharp_style_prefer_primary_constructors = true:suggestion +csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true:silent +csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true:silent [*.{cs,vb}] dotnet_diagnostic.CA1707.severity=suggestion @@ -111,7 +114,7 @@ dotnet_style_object_initializer = true:suggestion dotnet_style_operator_placement_when_wrapping = beginning_of_line tab_width = 4 indent_size = 4 -end_of_line = crlf +end_of_line = lf dotnet_style_collection_initializer = true:suggestion dotnet_style_qualification_for_field = true:suggestion dotnet_style_qualification_for_property = true:suggestion @@ -139,4 +142,4 @@ dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent # Extra rules -file_header_template = Copyright (c) 2023 Quetzal Rivera.\nLicensed under the MIT License, See LICENCE in the project root for license information. +file_header_template = Copyright (c) 2024 Quetzal Rivera.\nLicensed under the MIT License, See LICENCE in the project root for license information. diff --git a/src/Telegram.BotAPI.Examples/.vscode/launch.json b/src/Telegram.BotAPI.Examples/.vscode/launch.json deleted file mode 100644 index d5936871..00000000 --- a/src/Telegram.BotAPI.Examples/.vscode/launch.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "version": "0.2.0", - "configurations": [ - { - // Use IntelliSense to find out which attributes exist for C# debugging - // Use hover for the description of the existing attributes - // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md - "name": ".NET Core Launch (console)", - "type": "coreclr", - "request": "launch", - "preLaunchTask": "build", - // If you have changed target frameworks, make sure to update the program path. - "program": "${workspaceFolder}/HelloBotNET.AppService/bin/Debug/net6.0/HelloBotNET.AppService.dll", - "args": [], - "cwd": "${workspaceFolder}/HelloBotNET.AppService", - // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console - "console": "internalConsole", - "stopAtEntry": false - }, - { - "name": ".NET Core Attach", - "type": "coreclr", - "request": "attach" - } - ] -} \ No newline at end of file diff --git a/src/Telegram.BotAPI.Examples/.vscode/tasks.json b/src/Telegram.BotAPI.Examples/.vscode/tasks.json deleted file mode 100644 index 64efc90e..00000000 --- a/src/Telegram.BotAPI.Examples/.vscode/tasks.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "version": "2.0.0", - "tasks": [ - { - "label": "build", - "command": "dotnet", - "type": "process", - "args": [ - "build", - "${workspaceFolder}/HelloBotNET.AppService/HelloBotNET.AppService.csproj", - "/property:GenerateFullPaths=true", - "/consoleloggerparameters:NoSummary" - ], - "problemMatcher": "$msCompile" - }, - { - "label": "publish", - "command": "dotnet", - "type": "process", - "args": [ - "publish", - "${workspaceFolder}/HelloBotNET.AppService/HelloBotNET.AppService.csproj", - "/property:GenerateFullPaths=true", - "/consoleloggerparameters:NoSummary" - ], - "problemMatcher": "$msCompile" - }, - { - "label": "watch", - "command": "dotnet", - "type": "process", - "args": [ - "watch", - "run", - "--project", - "${workspaceFolder}/HelloBotNET.AppService/HelloBotNET.AppService.csproj" - ], - "problemMatcher": "$msCompile" - } - ] -} \ No newline at end of file diff --git a/src/Telegram.BotAPI.Examples/BotTemplate/MyBot.cs b/src/Telegram.BotAPI.Examples/BotTemplate/MyBot.cs deleted file mode 100644 index e8925972..00000000 --- a/src/Telegram.BotAPI.Examples/BotTemplate/MyBot.cs +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using System; -using System.Linq; -using System.Text.RegularExpressions; -using Telegram.BotAPI; -using Telegram.BotAPI.AvailableMethods; -using Telegram.BotAPI.AvailableTypes; -using Telegram.BotAPI.GettingUpdates; - -namespace BotTemplateSample -{ - public sealed class MyBot : TelegramBotBase - { - public static readonly BotClient Bot = new(""); - public static readonly User Me = Bot.GetMe(); - - private Message message; - private bool hasText; - private User appUser; - - public override void OnUpdate(Update update) - { - Console.WriteLine("New update with id: {0}. Type: {1}", update?.UpdateId, update?.Type.ToString("F")); - base.OnUpdate(update); - } - - protected override void OnMessage(Message message) - { - // Ignore user 777000 (Telegram) - if (message?.From.Id == TelegramConstants.TelegramId) - { - return; - } - Console.WriteLine("New message from chat id: {0}", message.Chat.Id); - - this.appUser = message.From; // Save current user; - this.message = message; // Save current message; - this.hasText = !string.IsNullOrEmpty(message.Text); // True if message has text; - - Console.WriteLine("Message Text: {0}", this.hasText ? message.Text : "|:O"); - - if (message.Chat.Type == ChatType.Private) // Private Chats - { - } - else // Group chats - { - - } - if (this.hasText) - { - if (message.Text.StartsWith('/')) // New commands - { - // If the command includes a mention, you should verify that it is for your bot, otherwise you will need to ignore the command. - var pattern = string.Format(@"^\/(?\w*)(?:|@{0})(?:$|\s(?.*))", Me.Username); - var match = Regex.Match(message.Text, pattern, RegexOptions.IgnoreCase); - if (match.Success) - { - var command = match.Groups.Values.Single(v => v.Name == "COMMAND").Value; // Get command name - var @params = match.Groups.Values.SingleOrDefault(v => v.Name == "PARAMETERS")?.Value; // Get command params - var parameters = @params?.Split(' ').Where(s => !string.IsNullOrEmpty(s)).ToArray(); - - Console.WriteLine("New command: {0}", command); - this.OnCommand(command, parameters); - } - } - } - } - - private void OnCommand(string cmd, string[] args) - { - Console.WriteLine("Params: {0}", args.Length); - switch (cmd) - { - case "hello": - var hello = string.Format("Hello World, {0}!", this.appUser.FirstName); - Bot.SendMessage(this.message.Chat.Id, hello); - break; - } - } - - protected override void OnBotException(BotRequestException exp) - { - Console.WriteLine("New BotException: {0}", exp?.Message); - Console.WriteLine("Error Code: {0}", exp.ErrorCode); - Console.WriteLine(); - } - - protected override void OnException(Exception exp) - { - Console.WriteLine("New Exception: {0}", exp?.Message); - Console.WriteLine(); - } - } -} diff --git a/src/Telegram.BotAPI.Examples/Callback query button 01/Program.cs b/src/Telegram.BotAPI.Examples/Callback query button 01/Program.cs deleted file mode 100644 index 9bdaaebd..00000000 --- a/src/Telegram.BotAPI.Examples/Callback query button 01/Program.cs +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using System; -using System.Linq; -using Telegram.BotAPI; -using Telegram.BotAPI.AvailableMethods; -using Telegram.BotAPI.AvailableTypes; -using Telegram.BotAPI.GettingUpdates; -using Telegram.BotAPI.UpdatingMessages; - -namespace CallbackQueryButton01 -{ - class Program - { - static void Main() - { - Console.WriteLine("Start!"); - - var bot = new BotClient(""); - bot.SetMyCommands(new BotCommand("callback", "new callback")); - - // Long Polling - var updates = bot.GetUpdates(); - while (true) - { - if (updates.Length > 0) - { - foreach (var update in updates) - { - switch (update.Type) - { - case UpdateType.Message: - var message = update.Message; - if (message.Text.Contains("/callback")) - { - var replyMarkup = new InlineKeyboardMarkup - { - InlineKeyboard = new InlineKeyboardButton[][]{ - new InlineKeyboardButton[]{ - InlineKeyboardButton.SetCallbackData("Callback", "callback_data") - } - } - }; - bot.SendMessage(message.Chat.Id, "Message with callback data", replyMarkup: replyMarkup); - } - break; - case UpdateType.CallbackQuery: - var query = update.CallbackQuery; - bot.AnswerCallbackQuery(query.Id, "HELLO"); - bot.EditMessageText(new EditMessageTextArgs($"Click!\n\n{query.Data}") - { - ChatId = query.Message.Chat.Id, - MessageId = query.Message.MessageId - }); - break; - } - } - updates = updates = bot.GetUpdates(offset: updates.Max(u => u.UpdateId) + 1); - } - else - { - updates = bot.GetUpdates(); - } - } - } - } -} diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/HelloBotProperties.cs b/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/HelloBotProperties.cs deleted file mode 100644 index 4c578ef0..00000000 --- a/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/HelloBotProperties.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Telegram.BotAPI; -using Telegram.BotAPI.AvailableMethods; -using Telegram.BotAPI.AvailableTypes; -using Telegram.BotAPI.GettingUpdates; - -namespace HelloBotNET.AppService -{ - /// - /// This class defines all the necessary settings and properties for the bot to work.
- /// The application uses a single instance of this class. - ///
- public sealed class HelloBotProperties : IBotProperties - { - private readonly BotCommandHelper _commandHelper; - - public HelloBotProperties(IConfiguration configuration) - { - var telegram = configuration.GetSection("Telegram"); // JSON: "Telegram" - var botToken = telegram["BotToken"]; // ENV: Telegram__BotToken, JSON: "Telegram:BotToken" - - this.Api = new BotClient(botToken); - this.User = this.Api.GetMe(); - - this._commandHelper = new BotCommandHelper(this); - - // Delete my old commands - this.Api.DeleteMyCommands(); - // Set my commands - this.Api.SetMyCommands( - new BotCommand("hello", "Hello world!")); - - // Delete webhook to use Long Polling - this.Api.DeleteWebhook(); - } - - public BotClient Api { get; } - public User User { get; } - - IBotCommandHelper IBotProperties.CommandHelper => this._commandHelper; - } -} diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Services/HelloBot.CommandHandler.cs b/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Services/HelloBot.CommandHandler.cs deleted file mode 100644 index 1bdf7ca2..00000000 --- a/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Services/HelloBot.CommandHandler.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Telegram.BotAPI; -using Telegram.BotAPI.AvailableMethods; -using Telegram.BotAPI.AvailableTypes; - -namespace HelloBotNET.AppService.Services -{ - /// - /// It contains the main functionality of the telegram bot.
- /// The application creates a new instance of this class to process each update received. - ///
- public partial class HelloBot : TelegramBotBase - { - protected override void OnCommand(Message message, string commandName, string commandParameters) - { - var args = commandParameters.Split(' '); -#if DEBUG - this._logger.LogInformation("Params: {0}", args.Length); -#endif - - switch (commandName) - { - case "hello": // Reply to /hello command - var hello = string.Format("Hello World, {0}!", message.From!.FirstName); - this.Api.SendMessage(message.Chat.Id, hello); - break; - /* - case "command1": - // ... - break; - case "command2": - // ... - break; - */ - default: - if (message.Chat.Type == ChatType.Private) - { - this.Api.SendMessage(message.Chat.Id, "Unrecognized command."); - } - break; - } - } - } -} diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Services/HelloBot.ErrorHandler.cs b/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Services/HelloBot.ErrorHandler.cs deleted file mode 100644 index 977c4b21..00000000 --- a/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Services/HelloBot.ErrorHandler.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Telegram.BotAPI; - -namespace HelloBotNET.AppService.Services -{ - /// - /// It contains the main functionality of the telegram bot.
- /// The application creates a new instance of this class to process each update received. - ///
- public partial class HelloBot : TelegramBotBase - { - protected override void OnBotException(BotRequestException exp) - { - this._logger.LogError("BotRequestException: {Message}", exp.Message); - } - - protected override void OnException(Exception exp) - { - this._logger.LogError("Exception: {Message}", exp.Message); - } - } -} diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Services/HelloBot.MessageHandler.cs b/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Services/HelloBot.MessageHandler.cs deleted file mode 100644 index a89c2faf..00000000 --- a/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Services/HelloBot.MessageHandler.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Telegram.BotAPI; -using Telegram.BotAPI.AvailableTypes; - -namespace HelloBotNET.AppService.Services -{ - /// - /// It contains the main functionality of the telegram bot.
- /// The application creates a new instance of this class to process each update received. - ///
- public partial class HelloBot : TelegramBotBase - { - protected override void OnMessage(Message message) - { - // Ignore user 777000 (Telegram) - if (message!.From?.Id == TelegramConstants.TelegramId) - { - return; - } - - var hasText = !string.IsNullOrEmpty(message.Text); // True if message has text; - -#if DEBUG - this._logger.LogInformation("New message from chat id: {ChatId}", message!.Chat.Id); - this._logger.LogInformation("Message: {MessageContent}", hasText ? message.Text : "No text"); -#endif - - base.OnMessage(message); - } - } -} diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Services/HelloBot.UpdateHandler.cs b/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Services/HelloBot.UpdateHandler.cs deleted file mode 100644 index f6cd0e79..00000000 --- a/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Services/HelloBot.UpdateHandler.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Telegram.BotAPI; -using Telegram.BotAPI.GettingUpdates; - -namespace HelloBotNET.AppService.Services -{ - /// - /// It contains the main functionality of the telegram bot.
- /// The application creates a new instance of this class to process each update received. - ///
- public partial class HelloBot : TelegramBotBase - { - public override void OnUpdate(Update update) - { -#if DEBUG - this._logger.LogInformation("New update with id: {0}. Type: {1}", update?.UpdateId, update?.Type.ToString("F")); -#endif - - base.OnUpdate(update); - } - } -} diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Services/HelloBot.cs b/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Services/HelloBot.cs deleted file mode 100644 index 9bd848b9..00000000 --- a/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Services/HelloBot.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Telegram.BotAPI; - -namespace HelloBotNET.AppService.Services -{ - /// - /// It contains the main functionality of the telegram bot.
- /// The application creates a new instance of this class to process each update received. - ///
- public partial class HelloBot : TelegramBotBase - { - private readonly ILogger _logger; - - public HelloBot(ILogger logger, HelloBotProperties botProperties) : base(botProperties) - { - this._logger = logger; - } - } -} diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Worker.cs b/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Worker.cs deleted file mode 100644 index 90008359..00000000 --- a/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Worker.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using HelloBotNET.AppService.Services; -using Telegram.BotAPI; -using Telegram.BotAPI.GettingUpdates; - -namespace HelloBotNET.AppService -{ - public class Worker : BackgroundService - { - private readonly BotClient _api; - private readonly ILogger _logger; - private readonly IServiceProvider _serviceProvider; - - public Worker(ILogger logger, HelloBotProperties botProperties, IServiceProvider serviceProvider) - { - this._logger = logger; - this._api = botProperties.Api; - this._serviceProvider = serviceProvider; - } - - protected override async Task ExecuteAsync(CancellationToken stoppingToken) - { - this._logger.LogInformation("Worker running at: {Time}", DateTimeOffset.Now); - - // Long Polling - var updates = await this._api.GetUpdatesAsync(cancellationToken: stoppingToken).ConfigureAwait(false); - while (!stoppingToken.IsCancellationRequested) - { - if (updates.Any()) - { - Parallel.ForEach(updates, (update) => this.ProcessUpdate(update)); - - updates = await this._api.GetUpdatesAsync(updates[^1].UpdateId + 1, cancellationToken: stoppingToken).ConfigureAwait(false); - } - else - { - updates = await this._api.GetUpdatesAsync(cancellationToken: stoppingToken).ConfigureAwait(false); - } - } - } - - private void ProcessUpdate(Update update) - { - using var scope = this._serviceProvider.CreateScope(); - var bot = scope.ServiceProvider.GetRequiredService(); - bot.OnUpdate(update); - } - - public override Task StopAsync(CancellationToken cancellationToken) - { - this._logger.LogInformation("Worker stopping at: {Time}", DateTimeOffset.Now); - return base.StopAsync(cancellationToken); - } - } -} diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/HelloBotProperties.cs b/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/HelloBotProperties.cs deleted file mode 100644 index ed6c79c0..00000000 --- a/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/HelloBotProperties.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Telegram.BotAPI; -using Telegram.BotAPI.AvailableMethods; -using Telegram.BotAPI.AvailableTypes; - -namespace HelloBotNET.Webhook -{ - /// - /// This class defines all the necessary settings and properties for the bot to work.
- /// The application uses a single instance of this class. - ///
- public sealed class HelloBotProperties : IBotProperties - { - private readonly BotCommandHelper _commandHelper; - - public HelloBotProperties(IConfiguration configuration) - { - var telegram = configuration.GetSection("Telegram"); // JSON: "Telegram" - var botToken = telegram["BotToken"]; // ENV: Telegram__BotToken, JSON: "Telegram:BotToken" - this.Api = new BotClient(botToken); - this.User = this.Api.GetMe(); - - this._commandHelper = new BotCommandHelper(this); - } - - public BotClient Api { get; } - public User User { get; } - - IBotCommandHelper IBotProperties.CommandHelper => this._commandHelper; - } -} diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Services/HelloBot.cs b/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Services/HelloBot.cs deleted file mode 100644 index de42d3b6..00000000 --- a/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Services/HelloBot.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Telegram.BotAPI; - -namespace HelloBotNET.Webhook.Services -{ - /// - /// It contains the main functionality of the telegram bot.
- /// The application creates a new instance of this class to process each update received. - ///
- public partial class HelloBot : TelegramBotBase - { - private readonly ILogger _logger; - - public HelloBot(ILogger logger, HelloBotProperties botProperties) : base(botProperties) - { - this._logger = logger; - } - } -} diff --git a/src/Telegram.BotAPI.Examples/ReplyKeyboardMarkup 01/Program.cs b/src/Telegram.BotAPI.Examples/ReplyKeyboardMarkup 01/Program.cs deleted file mode 100644 index 61d90de2..00000000 --- a/src/Telegram.BotAPI.Examples/ReplyKeyboardMarkup 01/Program.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using System; -using System.Linq; -using Telegram.BotAPI; -using Telegram.BotAPI.AvailableMethods; -using Telegram.BotAPI.AvailableTypes; -using Telegram.BotAPI.GettingUpdates; - -namespace ReplyKeyboardMarkup_01 -{ - class Program - { - static void Main() - { - Console.WriteLine("Start!"); - - var bot = new BotClient(""); - bot.SetMyCommands(new BotCommand("reply", "ReplyMarkup"), new BotCommand("del", "Delete")); - - // Long Polling - var updates = bot.GetUpdates(); - while (true) - { - if (updates.Length > 0) - { - foreach (var update in updates) - { - switch (update.Type) - { - case UpdateType.Message: - if (update.Message.Text.Contains("/reply")) - { - var keyboard = new ReplyKeyboardMarkup - { - Keyboard = new KeyboardButton[][]{ - new KeyboardButton[]{ - new KeyboardButton("Button 1"), //column 1 row 1 - new KeyboardButton("Button 2") //column 1 row 2 - },// column 1 - new KeyboardButton[]{ - new KeyboardButton("Button 3") //col 2 row 1 - } // column 2 - }, - ResizeKeyboard = true - }; ; - bot.SendMessage(update.Message.Chat.Id, "new keyboard", replyMarkup: keyboard); - } - if (update.Message.Text.Contains("/del")) - { - bot.SendMessage(update.Message.Chat.Id, "remove reply keyboard", replyMarkup: new ReplyKeyboardRemove()); - } - break; - } - } - updates = bot.GetUpdates(offset: updates.Max(u => u.UpdateId) + 1); - } - else - { - updates = bot.GetUpdates(); - } - } - } - } -} diff --git a/src/Telegram.BotAPI.Examples/Telegram Calendar/Telegram Calendar.csproj b/src/Telegram.BotAPI.Examples/Telegram Calendar/Telegram Calendar.csproj deleted file mode 100644 index 9577054e..00000000 --- a/src/Telegram.BotAPI.Examples/Telegram Calendar/Telegram Calendar.csproj +++ /dev/null @@ -1,13 +0,0 @@ - - - - Exe - net6.0 - TelegramCalendar - - - - - - - diff --git a/src/Telegram.BotAPI.Tests/CommandHelper.cs b/src/Telegram.BotAPI.Tests/CommandHelper.cs deleted file mode 100644 index 0955db0e..00000000 --- a/src/Telegram.BotAPI.Tests/CommandHelper.cs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using System.Linq; - -namespace Telegram.BotAPI.Tests; - -public class CommandHelper -{ - private readonly ITestOutputHelper _outputHelper; - private IBotProperties _botProperties; - - public CommandHelper(ITestOutputHelper outputHelper) - { - this._outputHelper = outputHelper; - this._botProperties = new FakeBotProperties(); - } - - [Theory] - [InlineData("/cmd")] - [InlineData("/cmd hello world")] - [InlineData("Not a command")] - [InlineData("/cmd@OtherBot")] - [InlineData("/cmd@OtherBot param1 param2")] - [InlineData("/cmd@FakeBot")] - [InlineData("/cmd@FakeBot param1 param2")] - public void MatchCommand(string text) - { - this._outputHelper.WriteLine("Input text: {0}", text); - - var match = this._botProperties.CommandHelper.Match(text); - if (match.Success) - { - this._outputHelper.WriteLine("New command: {0}, Parameters: {1}", match.Name, match.Params); - } - else - { - this._outputHelper.WriteLine("It's not a command or it's not for me."); - } - } - - [Theory] - [InlineData("Hello world!")] - [InlineData("Two args")] - [InlineData("'This is a single parameter'")] - [InlineData("--paramName \"My parameter value\"")] - [InlineData("--paramName 'My parameter value'")] - [InlineData("--paramName \"Wrong value'")] - public void MatchParams(string @params) - { - this._outputHelper.WriteLine("Input text: {0}", @params); - - var args = BotCommandHelper.MatchParameters(@params); - - this._outputHelper.WriteLine("{0} parameters has been detected", args.Count()); - foreach (var arg in args) - { - this._outputHelper.WriteLine(arg); - } - } -} diff --git a/src/Telegram.BotAPI.Tests/FakeBotProperties.cs b/src/Telegram.BotAPI.Tests/FakeBotProperties.cs deleted file mode 100644 index 6c90e431..00000000 --- a/src/Telegram.BotAPI.Tests/FakeBotProperties.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -namespace Telegram.BotAPI.Tests; - -internal class FakeBotProperties : IBotProperties -{ - public FakeBotProperties() - { - this.User = new User() - { - FirstName = "Fake bot", - Username = "FakeBot", - IsBot = true - }; - this.CommandHelper = new BotCommandHelper(this, true); - } - - public BotClient Api => throw new NotImplementedException(); - - public User User { get; } - public BotCommandHelper CommandHelper { get; } - - IBotCommandHelper IBotProperties.CommandHelper => this.CommandHelper; -} diff --git a/src/Telegram.BotAPI.Tests/MethodTests.cs b/src/Telegram.BotAPI.Tests/MethodTests.cs deleted file mode 100644 index d57d75bc..00000000 --- a/src/Telegram.BotAPI.Tests/MethodTests.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -namespace Telegram.BotAPI.Tests; - -public sealed class MethodTests -{ - [Fact] - public void SendMessageWithNullClient() - { - Assert.Throws(() => - { - AvailableMethodsExtensions.SendMessage(null, 0, "Hello World"); - }); - } - - [Fact] - public void EqualOperator() - { - var instance1 = new Message(); - var instance2 = new Message(); - Message nullInstance1 = null; - Message nullInstance2 = null; - - Assert.True(nullInstance1 == nullInstance2); - Assert.False(instance1 == nullInstance2); - Assert.False(nullInstance1 == instance2); - Assert.False(instance1.Equals(null)); - Assert.False(null == instance2); - Assert.False(instance1 == null); - Assert.True(instance1 == instance2); - } -} diff --git a/src/Telegram.BotAPI.sln b/src/Telegram.BotAPI.sln index cf5e1e31..b1aee849 100644 --- a/src/Telegram.BotAPI.sln +++ b/src/Telegram.BotAPI.sln @@ -3,21 +3,23 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.32014.148 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Telegram.BotAPI", "Telegram.BotAPI\Telegram.BotAPI.csproj", "{333CEF37-B947-47CA-A339-9B14D4D7E20A}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Telegram.BotAPI", "library\Telegram.BotAPI\Telegram.BotAPI.csproj", "{333CEF37-B947-47CA-A339-9B14D4D7E20A}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Source", "Source", "{E90CDF4A-2731-4F91-9BD7-4A40E04DF290}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Library", "Library", "{E90CDF4A-2731-4F91-9BD7-4A40E04DF290}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{576E0D2C-631B-4C68-9AF4-0D99DC4E5951}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Telegram.BotAPI.Tests", "Telegram.BotAPI.Tests\Telegram.BotAPI.Tests.csproj", "{14B3773F-CA9B-4AB7-A799-4CAD7A43D927}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Telegram.BotAPI.Tests", "tests\Telegram.BotAPI.Tests\Telegram.BotAPI.Tests.csproj", "{14B3773F-CA9B-4AB7-A799-4CAD7A43D927}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Telegram.BotAPI.Experimental", "Telegram.BotAPI.Experimental\Telegram.BotAPI.Experimental.csproj", "{BC2BDF60-4DD0-4979-AF17-E58984CAE9F3}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Telegram.BotAPI.Experimental", "library\Telegram.BotAPI.Experimental\Telegram.BotAPI.Experimental.csproj", "{BC2BDF60-4DD0-4979-AF17-E58984CAE9F3}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{EEFA3271-1A58-4067-B29D-C1B1770C6082}" ProjectSection(SolutionItems) = preProject .editorconfig = .editorconfig EndProjectSection EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Telegram.BotAPI.Extensions", "library\Telegram.BotAPI.Extensions\Telegram.BotAPI.Extensions.csproj", "{BA0FF392-07D4-4C31-866B-93865F4E1FF2}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -36,6 +38,10 @@ Global {BC2BDF60-4DD0-4979-AF17-E58984CAE9F3}.Debug|Any CPU.Build.0 = Debug|Any CPU {BC2BDF60-4DD0-4979-AF17-E58984CAE9F3}.Release|Any CPU.ActiveCfg = Release|Any CPU {BC2BDF60-4DD0-4979-AF17-E58984CAE9F3}.Release|Any CPU.Build.0 = Release|Any CPU + {BA0FF392-07D4-4C31-866B-93865F4E1FF2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BA0FF392-07D4-4C31-866B-93865F4E1FF2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BA0FF392-07D4-4C31-866B-93865F4E1FF2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BA0FF392-07D4-4C31-866B-93865F4E1FF2}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -44,6 +50,7 @@ Global {333CEF37-B947-47CA-A339-9B14D4D7E20A} = {E90CDF4A-2731-4F91-9BD7-4A40E04DF290} {14B3773F-CA9B-4AB7-A799-4CAD7A43D927} = {576E0D2C-631B-4C68-9AF4-0D99DC4E5951} {BC2BDF60-4DD0-4979-AF17-E58984CAE9F3} = {E90CDF4A-2731-4F91-9BD7-4A40E04DF290} + {BA0FF392-07D4-4C31-866B-93865F4E1FF2} = {E90CDF4A-2731-4F91-9BD7-4A40E04DF290} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {85BE005E-491E-437E-BA2C-2202816F73AF} diff --git a/src/Telegram.BotAPI/Abstractions/IMultipartForm.cs b/src/Telegram.BotAPI/Abstractions/IMultipartForm.cs deleted file mode 100644 index 6587e605..00000000 --- a/src/Telegram.BotAPI/Abstractions/IMultipartForm.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Telegram.BotAPI.AvailableTypes; - -namespace Telegram.BotAPI; - -/// -/// Defines properties and methods for multipart form. -/// -public interface IMultipartForm -{ - /// Attached files. - public IEnumerable AttachedFiles { get; set; } - - /// True, if the current object must be treated as multipart form. - bool UseMultipart(); -} diff --git a/src/Telegram.BotAPI/Available Methods/Args/EditMessageLiveLocationArgs.cs b/src/Telegram.BotAPI/Available Methods/Args/EditMessageLiveLocationArgs.cs deleted file mode 100644 index cbb8e409..00000000 --- a/src/Telegram.BotAPI/Available Methods/Args/EditMessageLiveLocationArgs.cs +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using Telegram.BotAPI.AvailableTypes; - -namespace Telegram.BotAPI.AvailableMethods; - -/// EditMessageLiveLocation method arguments.} -[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class EditMessageLiveLocationArgs : ILocation, ICustomizableReplyMarkup -{ - /// - /// Initializes a new instance of the class. - /// - /// Longitude as defined by sender - /// Latitude as defined by sender - public EditMessageLiveLocationArgs(float longitude, float latitude) - { - this.Longitude = longitude; - this.Latitude = latitude; - } - - /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). - [JsonPropertyName(PropertyNames.ChatId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public object? ChatId { get; set; } - /// Required if inline_message_id is not specified. Identifier of the sent message. - [JsonPropertyName(PropertyNames.MessageId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public int? MessageId { get; set; } - /// Required if chat_id and message_id are not specified. Identifier of the inline message. - [JsonPropertyName(PropertyNames.InlineMessageId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string? InlineMessageId { get; set; } - /// Longitude as defined by sender. - [JsonPropertyName(PropertyNames.Longitude)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public float Longitude { get; set; } - /// Latitude as defined by sender. - [JsonPropertyName(PropertyNames.Latitude)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public float Latitude { get; set; } - /// Optional. The radius of uncertainty for the location, measured in meters; 0-1500. - [JsonPropertyName(PropertyNames.HorizontalAccuracy)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public float? HorizontalAccuracy { get; set; } - /// Optional. Time relative to the message sending date, during which the location can be updated, in seconds. For active live locations only. - [JsonPropertyName(PropertyNames.LivePeriod)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public uint? LivePeriod { get; set; } - /// Optional. The direction in which user is moving, in degrees; 1-360. For active live locations only. - [JsonPropertyName(PropertyNames.Heading)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public ushort? Heading { get; set; } - /// Optional. Maximum distance for proximity alerts about approaching another chat member, in meters. For sent live locations only. - [JsonPropertyName(PropertyNames.ProximityAlertRadius)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public uint? ProximityAlertRadius { get; set; } - /// Optional. A object for a new inline keyboard. - [JsonPropertyName(PropertyNames.ReplyMarkup)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public InlineKeyboardMarkup? ReplyMarkup { get; set; } -} diff --git a/src/Telegram.BotAPI/Available Methods/Args/SendContactArgs.cs b/src/Telegram.BotAPI/Available Methods/Args/SendContactArgs.cs deleted file mode 100644 index ae0badf4..00000000 --- a/src/Telegram.BotAPI/Available Methods/Args/SendContactArgs.cs +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; - - -namespace Telegram.BotAPI.AvailableMethods; - -/// SendContact method arguments. -[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class SendContactArgs : SendMessageWithReplyMarkupBase -{ - /// - /// Initialize a new instance of . - /// - /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Contact's phone number. - /// Contact's first name. - /// - public SendContactArgs(long chatId, string phoneNumber, string firstName) : base(chatId) - { - this.PhoneNumber = phoneNumber ?? throw new ArgumentNullException(nameof(phoneNumber)); - this.FirstName = firstName ?? throw new ArgumentNullException(nameof(firstName)); - } - /// - /// Initialize a new instance of . - /// - /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Contact's phone number. - /// Contact's first name. - /// - public SendContactArgs(string chatId, string phoneNumber, string firstName) : base(chatId) - { - this.PhoneNumber = phoneNumber ?? throw new ArgumentNullException(nameof(phoneNumber)); - this.FirstName = firstName ?? throw new ArgumentNullException(nameof(firstName)); - } - - /// Contact's phone number. - [JsonPropertyName(PropertyNames.PhoneNumber)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string PhoneNumber { get; } - /// Contact's first name. - [JsonPropertyName(PropertyNames.FirstName)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string FirstName { get; } - /// Optional. Contact's last name. - [JsonPropertyName(PropertyNames.LastName)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string? LastName { get; set; } - /// Optional. Additional data about the contact in the form of a vCard, 0-2048 bytes. - [JsonPropertyName(PropertyNames.Vcard)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string? Vcard { get; set; } -} diff --git a/src/Telegram.BotAPI/Available Methods/Args/SendDiceArgs.cs b/src/Telegram.BotAPI/Available Methods/Args/SendDiceArgs.cs deleted file mode 100644 index acd7a417..00000000 --- a/src/Telegram.BotAPI/Available Methods/Args/SendDiceArgs.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; - - -namespace Telegram.BotAPI.AvailableMethods; - -/// SendDice method arguments. -[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class SendDiceArgs : SendMessageWithReplyMarkupBase -{ - /// - /// Initialize a new instance of . - /// - /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// - public SendDiceArgs(long chatId) : base(chatId) - { - } - /// - /// Initialize a new instance of . - /// - /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// - public SendDiceArgs(string chatId) : base(chatId) - { - } - - /// Emoji on which the dice throw animation is based. Currently, must be one of “🎲”, “🎯”, “🏀”, “⚽”, “🎳”, or “🎰”. Dice can have values 1-6 for “🎲”, “🎯” and “🎳”, values 1-5 for “🏀” and “⚽”, and values 1-64 for “🎰”. Defaults to “🎲”. - [JsonPropertyName(PropertyNames.Emoji)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string? Emoji { get; set; } -} diff --git a/src/Telegram.BotAPI/Available Methods/Args/SendLocationArgs.cs b/src/Telegram.BotAPI/Available Methods/Args/SendLocationArgs.cs deleted file mode 100644 index ce8df079..00000000 --- a/src/Telegram.BotAPI/Available Methods/Args/SendLocationArgs.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; - -namespace Telegram.BotAPI.AvailableMethods; - -/// SendLocation method arguments. -[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class SendLocationArgs : SendMessageWithReplyMarkupBase, ILocation -{ - /// - /// Initialize a new instance of . - /// - /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Longitude as defined by sender. - /// Latitude as defined by sender. - public SendLocationArgs(long chatId, float longitude, float latitude) : base(chatId) - { - this.Longitude = longitude; - this.Latitude = latitude; - } - /// - /// Initialize a new instance of . - /// - /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Longitude as defined by sender. - /// Latitude as defined by sender. - public SendLocationArgs(string chatId, float longitude, float latitude) : base(chatId) - { - this.Longitude = longitude; - this.Latitude = latitude; - } - - /// Longitude as defined by sender. - [JsonPropertyName(PropertyNames.Longitude)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public float Longitude { get; } - /// Latitude as defined by sender. - [JsonPropertyName(PropertyNames.Latitude)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public float Latitude { get; } - /// Optional. The radius of uncertainty for the location, measured in meters; 0-1500. - [JsonPropertyName(PropertyNames.HorizontalAccuracy)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public float? HorizontalAccuracy { get; set; } - /// Optional. Time relative to the message sending date, during which the location can be updated, in seconds. For active live locations only. - [JsonPropertyName(PropertyNames.LivePeriod)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public uint? LivePeriod { get; set; } - /// Optional. The direction in which user is moving, in degrees; 1-360. For active live locations only. - [JsonPropertyName(PropertyNames.Heading)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public ushort? Heading { get; set; } - /// Optional. Maximum distance for proximity alerts about approaching another chat member, in meters. For sent live locations only. - [JsonPropertyName(PropertyNames.ProximityAlertRadius)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public uint? ProximityAlertRadius { get; set; } -} diff --git a/src/Telegram.BotAPI/Available Methods/Args/SendMessageArgs.cs b/src/Telegram.BotAPI/Available Methods/Args/SendMessageArgs.cs deleted file mode 100644 index dbb6da0b..00000000 --- a/src/Telegram.BotAPI/Available Methods/Args/SendMessageArgs.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using Telegram.BotAPI.AvailableTypes; - - -namespace Telegram.BotAPI.AvailableMethods; - -/// SendMessage method arguments. -[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class SendMessageArgs : SendMessageWithReplyMarkupBase, IFormattableMessage -{ - /// Initialize a new instance of . - /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Text of the message to be sent. - public SendMessageArgs(long chatId, string text) : base(chatId) - { - this.Text = text; - } - /// Initialize a new instance of . - /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Text of the message to be sent. - public SendMessageArgs(string chatId, string text) : base(chatId) - { - this.Text = text; - } - - /// Text of the message to be sent. - [JsonPropertyName(PropertyNames.Text)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string Text { get; } - /// Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. - [JsonPropertyName(PropertyNames.ParseMode)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string? ParseMode { get; set; } - /// List of special entities that appear in message text, which can be specified instead of parse_mode. - [JsonPropertyName(PropertyNames.Entities)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public IEnumerable? Entities { get; set; } - /// Optional. Disables link previews for links in this message. - [JsonPropertyName(PropertyNames.DisableWebPagePreview)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public bool? DisableWebPagePreview { get; set; } -} diff --git a/src/Telegram.BotAPI/Available Methods/Args/SendPollArgs.cs b/src/Telegram.BotAPI/Available Methods/Args/SendPollArgs.cs deleted file mode 100644 index ed764d28..00000000 --- a/src/Telegram.BotAPI/Available Methods/Args/SendPollArgs.cs +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using Telegram.BotAPI.AvailableTypes; - - -namespace Telegram.BotAPI.AvailableMethods; - -/// SendPoll method arguments. -[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class SendPollArgs : SendMessageWithReplyMarkupBase -{ - /// - /// Initialize a new instance of . - /// - /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Poll question, 1-300 characters. - /// List of answer options, 2-10 strings 1-100 characters each. - /// - public SendPollArgs(long chatId, string question, IEnumerable options) : base(chatId) - { - this.Question = question ?? throw new ArgumentNullException(nameof(question)); - this.Options = options ?? throw new ArgumentNullException(nameof(options)); - } - /// - /// Initialize a new instance of . - /// - /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Poll question, 1-300 characters. - /// List of answer options, 2-10 strings 1-100 characters each. - /// - public SendPollArgs(string chatId, string question, IEnumerable options) : base(chatId) - { - this.Question = question ?? throw new ArgumentNullException(nameof(question)); - this.Options = options ?? throw new ArgumentNullException(nameof(options)); - } - - /// Poll question, 1-300 characters. - [JsonPropertyName(PropertyNames.Question)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string Question { get; } - /// List of answer options, 2-10 strings 1-100 characters each. - [JsonPropertyName(PropertyNames.Options)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public IEnumerable Options { get; } - /// Optional. True, if the poll needs to be anonymous, defaults to True. - [JsonPropertyName(PropertyNames.IsAnonymous)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Include)] - public bool? IsAnonymous { get; set; } = true; - /// Optional. Poll type, “quiz” or “regular”, defaults to “regular”. - [JsonPropertyName(PropertyNames.Type)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string? Type { get; set; } - /// Optional. True, if the poll allows multiple answers, ignored for polls in quiz mode, defaults to False. - [JsonPropertyName(PropertyNames.AllowsMultipleAnswers)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public bool? AllowsMultipleAnswers { get; set; } - /// Optional. 0-based identifier of the correct answer option, required for polls in quiz mode. - [JsonPropertyName(PropertyNames.CorrectOptionId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public uint? CorrectOptionId { get; set; } - /// Optional. Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing. - [JsonPropertyName(PropertyNames.Explanation)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string? Explanation { get; set; } - /// Optional. Mode for parsing entities in the explanation. See formatting options for more details. - [JsonPropertyName(PropertyNames.ExplanationParseMode)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string? ExplanationParseMode { get; set; } - /// Optional. List of special entities that appear in the poll explanation, which can be specified instead of parse_mode. - [JsonPropertyName(PropertyNames.ExplanationEntities)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public IEnumerable? ExplanationEntities { get; set; } - /// Optional. Amount of time in seconds the poll will be active after creation, 5-600. Can't be used together with close_date. - [JsonPropertyName(PropertyNames.OpenPeriod)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public ushort? OpenPeriod { get; set; } - /// Optional. Point in time (Unix timestamp) when the poll will be automatically closed. Must be at least 5 and no more than 600 seconds in the future. Can't be used together with open_period. - [JsonPropertyName(PropertyNames.CloseDate)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public uint? CloseDate { get; set; } - /// Optional. Pass True, if the poll needs to be immediately closed. - [JsonPropertyName(PropertyNames.IsClosed)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public bool? IsClosed { get; set; } -} -/// Poll type, “quiz” or “regular”, defaults to “regular” -public static class PollType -{ - /// Quiz poll - public const string Quiz = "quiz"; - /// Regular poll - public const string Regular = "regular"; -} diff --git a/src/Telegram.BotAPI/Available Methods/Args/StopMessageLiveLocationArgs.cs b/src/Telegram.BotAPI/Available Methods/Args/StopMessageLiveLocationArgs.cs deleted file mode 100644 index 0c650c6c..00000000 --- a/src/Telegram.BotAPI/Available Methods/Args/StopMessageLiveLocationArgs.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using Telegram.BotAPI.AvailableTypes; - -namespace Telegram.BotAPI.AvailableMethods; - -/// StopMessageLiveLocation method arguments -[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class StopMessageLiveLocationArgs : ICustomizableReplyMarkup -{ - /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). - [JsonPropertyName(PropertyNames.ChatId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public object? ChatId { get; set; } - /// Required if inline_message_id is not specified. Identifier of the sent message. - [JsonPropertyName(PropertyNames.MessageId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public int? MessageId { get; set; } - /// Required if chat_id and message_id are not specified. Identifier of the inline message. - [JsonPropertyName(PropertyNames.InlineMessageId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string? InlineMessageId { get; set; } - /// Optional. A JSON object for a new inline keyboard. - [JsonPropertyName(PropertyNames.ReplyMarkup)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public InlineKeyboardMarkup? ReplyMarkup { get; set; } -} diff --git a/src/Telegram.BotAPI/Available Methods/editMessageLiveLocation.cs b/src/Telegram.BotAPI/Available Methods/editMessageLiveLocation.cs deleted file mode 100644 index 3ab3fd97..00000000 --- a/src/Telegram.BotAPI/Available Methods/editMessageLiveLocation.cs +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Newtonsoft.Json.Linq; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Telegram.BotAPI.AvailableTypes; - -namespace Telegram.BotAPI.AvailableMethods; - -public static partial class AvailableMethodsExtensions -{ - /// Use this method to edit live location messages sent by the bot or via the bot (for inline bots). A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. - /// BotClient - /// Parameters. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// or . On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned. - public static Message EditMessageLiveLocation(this BotClient? bot, EditMessageLiveLocationArgs args) - { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - return bot.RPC(MethodNames.EditMessageLiveLocation, args); - } - /// Use this method to edit live location messages sent by the bot or via the bot (for inline bots). A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. - /// BotClient - /// Parameters. - /// The cancellation token to cancel operation. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// or . On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned. - public static async Task EditMessageLiveLocationAsync(this BotClient? bot, EditMessageLiveLocationArgs args, [Optional] CancellationToken cancellationToken) - { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - return await bot.RPCA(MethodNames.EditMessageLiveLocation, args, cancellationToken: cancellationToken).ConfigureAwait(false); - } - /// Use this method to edit live location messages sent by the bot or via the bot (for inline bots). A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. - /// BotClient - /// Parameters. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// Thrown when T is not Telegram.BotAPI.AvailableTypes.Message or bool. - /// or . On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned. - public static T EditMessageLiveLocation(this BotClient? bot, EditMessageLiveLocationArgs args) - { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - if (typeof(T) != typeof(Message) && typeof(T) != typeof(bool) && typeof(T) != typeof(JObject) && typeof(T) != typeof(JsonDocument)) - { - throw new ArgumentException($"{nameof(T)} must be a Telegram.BotAPI.AvailableTypes.Message or bool."); - } - return bot.RPC(MethodNames.EditMessageLiveLocation, args); - } - /// Use this method to edit live location messages sent by the bot or via the bot (for inline bots). A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. - /// BotClient - /// Parameters. - /// The cancellation token to cancel operation. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// Thrown when T is not Telegram.BotAPI.AvailableTypes.Message or bool. - /// or . On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned. - public static async Task EditMessageLiveLocationAsync(this BotClient? bot, EditMessageLiveLocationArgs args, [Optional] CancellationToken cancellationToken) - { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - if (typeof(T) != typeof(Message) && typeof(T) != typeof(bool) && typeof(T) != typeof(JObject) && typeof(T) != typeof(JsonDocument)) - { - throw new ArgumentException($"{nameof(T)} must be a Telegram.BotAPI.AvailableTypes.Message or bool."); - } - return await bot.RPCA(MethodNames.EditMessageLiveLocation, args, cancellationToken: cancellationToken).ConfigureAwait(false); - } -} \ No newline at end of file diff --git a/src/Telegram.BotAPI/Available Methods/stopMessageLiveLocation.cs b/src/Telegram.BotAPI/Available Methods/stopMessageLiveLocation.cs deleted file mode 100644 index e09ba8fd..00000000 --- a/src/Telegram.BotAPI/Available Methods/stopMessageLiveLocation.cs +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Newtonsoft.Json.Linq; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Telegram.BotAPI.AvailableTypes; - -namespace Telegram.BotAPI.AvailableMethods; - -public static partial class AvailableMethodsExtensions -{ - /// Use this method to stop updating a live location message sent by the bot or via the bot (for inline bots) before live_period expires. - /// BotClient - /// Parameters. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// or . On success, if the message was sent by the bot, the sent Message is returned, otherwise True is returned. - public static Message StopMessageLiveLocation(this BotClient? bot, StopMessageLiveLocationArgs args) - { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - return bot.RPC(MethodNames.StopMessageLiveLocation, args); - } - /// Use this method to stop updating a live location message sent by the bot or via the bot (for inline bots) before live_period expires. - /// BotClient - /// Parameters. - /// The cancellation token to cancel operation. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// or . On success, if the message was sent by the bot, the sent Message is returned, otherwise True is returned. - public static async Task StopMessageLiveLocationAsync(this BotClient? bot, StopMessageLiveLocationArgs args, [Optional] CancellationToken cancellationToken) - { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - return await bot.RPCA(MethodNames.StopMessageLiveLocation, args, cancellationToken: cancellationToken).ConfigureAwait(false); - } - /// Use this method to stop updating a live location message sent by the bot or via the bot (for inline bots) before live_period expires. - /// BotClient - /// Parameters. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// Thrown when T is not Telegram.BotAPI.AvailableTypes.Message or bool. - /// or . On success, if the message was sent by the bot, the sent Message is returned, otherwise True is returned. - public static T StopMessageLiveLocation(this BotClient? bot, StopMessageLiveLocationArgs args) - { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - if (typeof(T) != typeof(Message) && typeof(T) != typeof(bool) && typeof(T) != typeof(JObject) && typeof(T) != typeof(JsonDocument)) - { - throw new ArgumentException($"{nameof(T)} must be Telegram.BotAPI.AvailableTypes.Message or bool."); - } - return bot.RPC(MethodNames.StopMessageLiveLocation, args); - } - /// Use this method to stop updating a live location message sent by the bot or via the bot (for inline bots) before live_period expires. - /// BotClient - /// Parameters. - /// The cancellation token to cancel operation. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// Thrown when T is not Telegram.BotAPI.AvailableTypes.Message or bool. - /// or . On success, if the message was sent by the bot, the sent Message is returned, otherwise True is returned. - public static async Task StopMessageLiveLocationAsync(this BotClient? bot, StopMessageLiveLocationArgs args, [Optional] CancellationToken cancellationToken) - { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - if (typeof(T) != typeof(Message) && typeof(T) != typeof(bool) && typeof(T) != typeof(JObject) && typeof(T) != typeof(JsonDocument)) - { - throw new ArgumentException($"{nameof(T)} must be Telegram.BotAPI.AvailableTypes.Message or bool."); - } - return await bot.RPCA(MethodNames.StopMessageLiveLocation, args, cancellationToken: cancellationToken).ConfigureAwait(false); - } -} diff --git a/src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeType.cs b/src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeType.cs deleted file mode 100644 index aa3b08d0..00000000 --- a/src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeType.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -namespace Telegram.BotAPI.AvailableTypes; - -/// Available types of . -public static class BotCommandScopeType -{ - /// All chat administrators. Represents the scope of bot commands, covering all group and supergroup chat administrators. - public const string AllChatAdministrators = "all_chat_administrators"; - /// All group chats. Represents the scope of bot commands, covering all group and supergroup chats. - public const string AllGroupChats = "all_group_chats"; - /// All private chats. Represents the scope of bot commands, covering all private chats. - public const string AllPrivateChats = "all_private_chats"; - /// Chat. Represents the scope of bot commands, covering a specific chat. - public const string Chat = CommonNames.Chat; - /// Chat administrators. Represents the scope of bot commands, covering all administrators of a specific group or supergroup chat. - public const string ChatAdministrators = "chat_administrators"; - /// Chat member. Represents the scope of bot commands, covering a specific member of a group or supergroup chat. - public const string ChatMember = CommonNames.ChatMember; - /// Default. Represents the default scope of bot commands. Default commands are used if no commands with a narrower scope are specified for the user. - public const string Default = "default"; -} diff --git a/src/Telegram.BotAPI/Available Types/CallbackQuery.cs b/src/Telegram.BotAPI/Available Types/CallbackQuery.cs deleted file mode 100644 index 00c38dc5..00000000 --- a/src/Telegram.BotAPI/Available Types/CallbackQuery.cs +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; - -namespace Telegram.BotAPI.AvailableTypes; - -/// This object represents an incoming callback query from a callback button in an inline keyboard. If the button that originated the query was attached to a message sent by the bot, the field message will be present. If the button was attached to a message sent via the bot (in inline mode), the field inline_message_id will be present. Exactly one of the fields data or game_short_name will be present. -[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public sealed class CallbackQuery : IEquatable -{ - /// - /// Initializes a new instance of the class. - /// - public CallbackQuery() - { - this.Id = null!; - this.From = null!; - this.ChatInstance = null!; - } - - /// Unique identifier for this query. - [JsonPropertyName(PropertyNames.Id)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string Id { get; set; } - /// Sender. - [JsonPropertyName(PropertyNames.From)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public User From { get; set; } - /// Optional. Message with the callback button that originated the query. Note that message content and message date will not be available if the message is too old. - [JsonPropertyName(PropertyNames.Message)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public Message? Message { get; set; } - /// Optional. Identifier of the message sent via the bot in inline mode, that originated the query. - [JsonPropertyName(PropertyNames.InlineMessageId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string? InlineMessageId { get; set; } - /// Global identifier, uniquely corresponding to the chat to which the message with the callback button was sent. Useful for high scores in games. - [JsonPropertyName(PropertyNames.ChatInstance)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string ChatInstance { get; set; } - /// Optional. Data associated with the callback button. Be aware that a bad client can send arbitrary data in this field. - [JsonPropertyName(PropertyNames.Data)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string? Data { get; set; } - /// Optional. Short name of a Game to be returned, serves as the unique identifier for the game. - [JsonPropertyName(PropertyNames.GameShortName)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string? GameShortName { get; set; } - /// - public override bool Equals(object? obj) - { - return this.Equals(obj as CallbackQuery); - } - /// - public bool Equals(CallbackQuery? other) - { - return other is not null && - this.Id == other.Id && - EqualityComparer.Default.Equals(this.From, other.From) && - EqualityComparer.Default.Equals(this.Message, other.Message) && - this.InlineMessageId == other.InlineMessageId && - this.ChatInstance == other.ChatInstance && - this.Data == other.Data && - this.GameShortName == other.GameShortName; - } - /// - public override int GetHashCode() - { - int hashCode = -1057610016; - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Id); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.From); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Message); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.InlineMessageId); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ChatInstance); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Data); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.GameShortName); - return hashCode; - } - /// - public static bool operator ==(CallbackQuery? left, CallbackQuery? right) - { - return EqualityComparer.Default.Equals(left!, right!); - } - /// - public static bool operator !=(CallbackQuery? left, CallbackQuery? right) - { - return !(left == right); - } - -} diff --git a/src/Telegram.BotAPI/Available Types/InputMedia/InputMediaPhoto.cs b/src/Telegram.BotAPI/Available Types/InputMedia/InputMediaPhoto.cs deleted file mode 100644 index 0a782063..00000000 --- a/src/Telegram.BotAPI/Available Types/InputMedia/InputMediaPhoto.cs +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; - -namespace Telegram.BotAPI.AvailableTypes; - -/// Represents a photo to be sent. -[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public sealed class InputMediaPhoto : InputMedia, IEquatable -{ - /// - /// Initializes a new instance of the class. - /// - /// File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass attach://<file_attach_name> to upload a new one using multipart/form-data under <file_attach_name> name. - public InputMediaPhoto(string media) : base(media) - { - } - - /// Type of the result, must be photo. - [JsonPropertyName(PropertyNames.Type)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public override string Type => InputMediaType.Photo; - /// Optional. Caption of the photo to be sent, 0-1024 characters. - [JsonPropertyName(PropertyNames.Caption)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public override string? Caption { get; set; } - /// Optional. Pass True if the photo needs to be covered with a spoiler animation. - [JsonPropertyName(PropertyNames.HasSpoiler)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public bool? HasSpoiler { get; set; } - /// - public override bool Equals(object? obj) - { - return this.Equals(obj as InputMediaPhoto); - } - /// - public bool Equals(InputMediaPhoto? other) - { - return other is not null && - this.Type == other.Type && - this.Media == other.Media && - this.Caption == other.Caption && - EqualityComparer?>.Default.Equals(this.CaptionEntities, other.CaptionEntities) && - this.ParseMode == other.ParseMode && - this.Type == other.Type && - this.Caption == other.Caption && - this.HasSpoiler == other.HasSpoiler; - } - /// - public override int GetHashCode() - { - int hashCode = 397299575; - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Type); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Media); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Caption); - hashCode = hashCode * -1521134295 + EqualityComparer?>.Default.GetHashCode(this.CaptionEntities); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ParseMode); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Type); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Caption); - hashCode = hashCode * -1521134295 + this.HasSpoiler.GetHashCode(); - return hashCode; - } - /// - public static bool operator ==(InputMediaPhoto? left, InputMediaPhoto? right) - { - return EqualityComparer.Default.Equals(left!, right!); - } - /// - public static bool operator !=(InputMediaPhoto? left, InputMediaPhoto? right) - { - return !(left == right); - } -} diff --git a/src/Telegram.BotAPI/Available Types/Interfaces/ITelegramChat.cs b/src/Telegram.BotAPI/Available Types/Interfaces/ITelegramChat.cs deleted file mode 100644 index 4ea33247..00000000 --- a/src/Telegram.BotAPI/Available Types/Interfaces/ITelegramChat.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - - -namespace Telegram.BotAPI.AvailableTypes; - -/// Defines the basic properties of a Telegram chat. -public interface ITelegramChat -{ - /// Unique identifier for this chat. - public long Id { get; set; } - /// Type of chat, can be either “private”, “group”, “supergroup” or “channel”. - public string Type { get; set; } - /// Title, for supergroups, channels and group chats. - public string Title { get; set; } - /// Username, for private chats, supergroups and channels if available. - public string? Username { get; set; } - /// Description, for supergroups and channel chats. - public string? Description { get; set; } - /// Optional. Chat invite link, for supergroups and channel chats. - public string? InviteLink { get; set; } - /// Optional. Unique identifier for the linked chat, i.e. the discussion group identifier for a channel and vice versa; for supergroups and channel chats. - public long? LinkedChatId { get; set; } -} diff --git a/src/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButtonRequestUser.cs b/src/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButtonRequestUser.cs deleted file mode 100644 index 5ccadd5a..00000000 --- a/src/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButtonRequestUser.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; - -namespace Telegram.BotAPI.AvailableTypes; - -/// -/// This object defines the criteria used to request a suitable user. The identifier of the selected user will be shared with the bot when the corresponding button is pressed. -/// -[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public sealed class KeyboardButtonRequestUser -{ - /// - /// Initialize a new instance of the class. - /// - /// Signed 32-bit identifier of the request, which will be received back in the UserShared object. Must be unique within the message. - public KeyboardButtonRequestUser(int requestId) - { - RequestId = requestId; - } - - /// - /// Signed 32-bit identifier of the request, which will be received back in the UserShared object. Must be unique within the message - /// - [JsonPropertyName(PropertyNames.RequestId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public int RequestId { get; } - /// - /// Optional. Pass True to request a bot, pass False to request a regular user. If not specified, no additional restrictions are applied. - /// - [JsonPropertyName(PropertyNames.UserIsBot)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public bool? UserIsBot { get; set; } - /// - /// Optional. Pass True to request a premium user, pass False to request a non-premium user. If not specified, no additional restrictions are applied. - /// - [JsonPropertyName(PropertyNames.UserIsPremium)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public bool? UserIsPremium { get; set; } - -} diff --git a/src/Telegram.BotAPI/Available Types/ResponseParameters.cs b/src/Telegram.BotAPI/Available Types/ResponseParameters.cs deleted file mode 100644 index 79ab16ad..00000000 --- a/src/Telegram.BotAPI/Available Types/ResponseParameters.cs +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; - -namespace Telegram.BotAPI.AvailableTypes; - -/// Contains information about why a request was unsuccessful. -[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public sealed class ResponseParameters : IEquatable -{ - /// Optional. The group has been migrated to a supergroup with the specified identifier. This number may be greater than 32 bits and some programming languages may have difficulty/silent defects in interpreting it. But it is smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this identifier. - [JsonPropertyName(PropertyNames.MigrateToChatId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public long MigrateToChatId { get; set; } - /// Optional. In case of exceeding flood control, the number of seconds left to wait before the request can be repeated. - [JsonPropertyName(PropertyNames.RetryAfter)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public uint RetryAfter { get; set; } - /// - public override bool Equals(object obj) - { - return this.Equals(obj as ResponseParameters); - } - /// - public bool Equals(ResponseParameters? other) - { - return other != null && - this.MigrateToChatId == other.MigrateToChatId && - this.RetryAfter == other.RetryAfter; - } - /// - public override int GetHashCode() - { - int hashCode = -1065444587; - hashCode = hashCode * -1521134295 + this.MigrateToChatId.GetHashCode(); - hashCode = hashCode * -1521134295 + this.RetryAfter.GetHashCode(); - return hashCode; - } - /// - public static bool operator ==(ResponseParameters? left, ResponseParameters? right) - { - return EqualityComparer.Default.Equals(left!, right!); - } - /// - public static bool operator !=(ResponseParameters? left, ResponseParameters? right) - { - return !(left == right); - } - -} diff --git a/src/Telegram.BotAPI/BotClient.HttpRequests.cs b/src/Telegram.BotAPI/BotClient.HttpRequests.cs deleted file mode 100644 index 5fe6317f..00000000 --- a/src/Telegram.BotAPI/BotClient.HttpRequests.cs +++ /dev/null @@ -1,467 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using System.IO; -using System.Linq; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Reflection; -using System.Text; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Telegram.BotAPI.AvailableTypes; - -namespace Telegram.BotAPI; - -public sealed partial class BotClient -{ - internal static readonly JsonSerializerOptions DefaultSerializerOptions = new() - { - DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull - }; - - private const string applicationJson = "application/json"; - private const string multipartFormData = "multipart/form-data"; - - /// Default HttpClient for bot requets. - public static HttpClient? DefaultHttpClient { get; private set; } - - /// Set the default HttpClient for bot requets. - /// for http requets. - /// Thrown when client is null. - public static HttpClient SetHttpClient([Optional] HttpClient client) - { - DefaultHttpClient = client ?? new HttpClient(); - AddJsonMultipart(DefaultHttpClient); - return DefaultHttpClient; - } - - private static HttpClient? AddJsonMultipart(HttpClient? client) - { - if (client == null) - { - return null; - } - if (!client.DefaultRequestHeaders.Accept.Any(u => u.MediaType == applicationJson)) - { - client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(applicationJson)); - } - if (!client.DefaultRequestHeaders.Accept.Any(u => u.MediaType == multipartFormData)) - { - client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(multipartFormData)); - } - return client; - } - - /// Makes a bot request using HTTP GET and returns the response. - /// Response type. - /// Method name. See - /// - public BotResponse GetRequest(string method) - { - var response = this.GetRequestAsync(method); - try - { - return response.Result; - } - catch (AggregateException exp) - { - throw exp.InnerException; - } - } - - /// Makes a bot request using HTTP GET and returns the response. - /// Response type. - /// Method name. See - /// The cancellation token to cancel operation. - /// - public async Task> GetRequestAsync(string method, [Optional] CancellationToken cancellationToken) - { - using var request = new HttpRequestMessage(HttpMethod.Get, this.BuildUrl(method)); - return await this.SendRequestAsync(request, cancellationToken).ConfigureAwait(false); - } - - /// Makes a bot request using HTTP POST and returns the response. - /// Response type. - /// Method name. See - /// json parameters - /// Options to control serialization behavior. - /// - public BotResponse PostRequest(string method, object args, [Optional] JsonSerializerOptions serializeOptions) - { - var response = this.PostRequestAsync(method, args, serializeOptions); - try - { - return response.Result; - } - catch (AggregateException exp) - { - throw exp.InnerException; - } - } - - /// Makes a bot request using HTTP POST and returns the response. - /// Response type. - /// Method name. See - /// json parameters - /// Options to control serialization behavior. - /// The cancellation token to cancel operation. - /// - public async Task> PostRequestAsync(string method, object args, [Optional] JsonSerializerOptions serializeOptions, [Optional] CancellationToken cancellationToken) - { - if (args == default) - { - throw new ArgumentException(nameof(args)); - } - if (serializeOptions == default) - { - serializeOptions = DefaultSerializerOptions; - } - var stream = await Tools.SerializeAsStreamAsync(args, serializeOptions, cancellationToken) - .ConfigureAwait(false); - return await this.PostRequestAsync(method, stream, cancellationToken).ConfigureAwait(false); - } - - /// Makes a bot request using HTTP POST and returns the response. - /// Response type. - /// Method name. See - /// json parameters - /// - public BotResponse PostRequest(string method, Stream args) - { - var response = this.PostRequestAsync(method, args); - try - { - return response.Result; - } - catch (AggregateException exp) - { - throw exp.InnerException; - } - } - - /// Makes a bot request using HTTP POST and returns the response. - /// Response type. - /// Method name. See - /// json parameters - /// The cancellation token to cancel operation. - /// - public async Task> PostRequestAsync(string method, Stream args, [Optional] CancellationToken cancellationToken) - { - using var request = new HttpRequestMessage(HttpMethod.Post, this.BuildUrl(method)) - { - Content = new StreamContent(args) - }; - request.Content.Headers.ContentType = new MediaTypeHeaderValue(applicationJson); - return await this.SendRequestAsync(request, cancellationToken).ConfigureAwait(false); - } - - /// Makes a bot request using HTTP POST and Multipart Form Data and returns the response. - /// Response type. - /// Method name. See . - /// Parameters encoded using multipart/form-data. - /// The cancellation token to cancel operation. - /// - public async Task> PostRequestAsyncMultipartFormData(string method, MultipartFormDataContent args, CancellationToken cancellationToken) - { - using var request = new HttpRequestMessage(HttpMethod.Post, this.BuildUrl(method)) - { - Content = args - }; - return await this.SendRequestAsync(request, cancellationToken).ConfigureAwait(false); - } - - internal async Task> SendRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) - { - var response = await this.httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); - try - { - response.EnsureSuccessStatusCode(); - var streamResponse = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); - var botResponse = await JsonSerializer.DeserializeAsync>(streamResponse, DefaultSerializerOptions, cancellationToken: cancellationToken); - return botResponse!; - } - catch (HttpRequestException exp) - { - if (response.Content.Headers.ContentType.MediaType == applicationJson) - { - var streamResponse = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); - var botResponse = await JsonSerializer.DeserializeAsync>(streamResponse, DefaultSerializerOptions, cancellationToken: cancellationToken); - return botResponse!; - } - else - { - throw new BotRequestException(exp, response); - } - } - } - - /// - /// Build the url for the request. - /// - /// The method name. - /// The url for the request. - private string BuildUrl(string method) - { - var prefix = this.UseTestEnvironment ? "/test" : string.Empty; - return $"{this.ServerAddress}/bot{this.Token}{prefix}/{method}"; - } - - /// RPC - /// return type. - /// method name - internal T RPC(string method) - { - var response = this.GetRequest(method); - if (response.Ok) - { - return response.Result; - } - else - { - if (this.IgnoreBotExceptions) - { - return default(T); - } - else - { - throw new BotRequestException(response.ErrorCode, response.Description, response.Parameters); - } - } - } - - /// RPC async - /// return type. - /// method name - /// The cancellation token to cancel operation. - internal async Task RPCA(string method, [Optional] CancellationToken cancellationToken) - { - var response = await this.GetRequestAsync(method, cancellationToken).ConfigureAwait(false); - if (response.Ok == true) - { - return response.Result; - } - else - { - if (this.IgnoreBotExceptions) - { - return default; - } - else - { - throw new BotRequestException(response.ErrorCode, response.Description, response.Parameters); - } - } - } - - /// RPC - /// return type. - /// method name - /// parameters - internal T RPC(string method, object args) - { - var response = this.PostRequest(method, args); - if (response.Ok) - { - return response.Result; - } - else - { - if (this.IgnoreBotExceptions) - { - return default; - } - else - { - throw new BotRequestException(response.ErrorCode, response.Description, response.Parameters); - } - } - } - - /// RPC - /// return type. - /// method name - /// parameters - internal T RPC(string method, Stream args) - { - var response = this.PostRequest(method, args); - if (response.Ok) - { - return response.Result; - } - else - { - if (this.IgnoreBotExceptions) - { - return default; - } - else - { - throw new BotRequestException(response.ErrorCode, response.Description, response.Parameters); - } - } - } - - /// RPC async - /// return type. - /// method name - /// parameters - /// The cancellation token to cancel operation. - internal async Task RPCA(string method, object args, [Optional] CancellationToken cancellationToken) - { - var response = await this.PostRequestAsync(method, args, cancellationToken: cancellationToken).ConfigureAwait(false); - if (response.Ok) - { - return response.Result; - } - else - { - if (this.IgnoreBotExceptions) - { - return default; - } - else - { - throw new BotRequestException(response.ErrorCode, response.Description, response.Parameters); - } - } - } - - /// RPC async - /// return type. - /// method name - /// parameters - /// The cancellation token to cancel operation. - internal async Task RPCA(string method, Stream args, [Optional] CancellationToken cancellationToken) - { - var response = await this.PostRequestAsync(method, args, cancellationToken).ConfigureAwait(false); - if (response.Ok == true) - { - return response.Result; - } - else - { - if (this.IgnoreBotExceptions) - { - return default; - } - else - { - throw new BotRequestException(response.ErrorCode, response.Description, response.Parameters); - } - } - } - - /// RPC for files - /// return type. - /// method name - /// parameters - internal T RPCF(string method, object args) - { - if (args is IMultipartForm mf) - { - if (!mf.UseMultipart()) - { - return this.RPC(method, args); - } - } - var rpcf = this.RPCAF(method, args, default); - try - { - return rpcf.Result; - } - catch (AggregateException exp) - { - throw exp.InnerException; - } - } - - /// RPC async for files - /// return type. - /// method name - /// parameters - /// The cancellation token to cancel operation. - internal async Task RPCAF(string method, object args, [Optional] CancellationToken cancellationToken) - { - // If the method is a multipart form and it say don't use multipart, use the normal RPCA method - if (args is IMultipartForm mf && !mf.UseMultipart()) - { - return await this.RPCA(method, args, cancellationToken).ConfigureAwait(false); - } - - // Create a new MultipartFormDataContent - using var content = new MultipartFormDataContent(Guid.NewGuid().ToString() + DateTime.UtcNow.Ticks); - - // Get the properties of the object - var properties = args.GetType().GetProperties(); - - // Iterate over the properties - foreach (var property in properties) - { - // Get the value of the property - var value = property.GetValue(args); - - // If value is null, skip it - if (value == null) - { - continue; - } - - // If the value is an array of AttachedFile. Attach all files. - if (value is IEnumerable attachedfiles) - { - foreach (var attachedfile in attachedfiles) - { - content.Add(attachedfile.File.Content, attachedfile.Name, attachedfile.File.Filename); - } - } - else - { - // Verify the property has the JsonPropertyName attribute - var attribute = (JsonPropertyNameAttribute?)property.GetCustomAttribute(typeof(JsonPropertyNameAttribute)); - // If the property has json attributes, process. - if (attribute != null) - { - // Get the name of the property. - var pname = attribute.Name; - - // If the value is a basic type, then, add it to the content. - if (value is string || value is bool || value.IsNumber()) - { - content.Add(new StringContent(value.ToString(), Encoding.UTF8), pname); - } - // If the value is an InputFile, process it. - else if (value is InputFile file) - { - content.Add(file.Content, pname, file.Filename); - } - // If the value is another kind of value (object or array), serialize it. - else - { - string jvalue = JsonSerializer.Serialize(value, value.GetType(), DefaultSerializerOptions); - content.Add(new StringContent(jvalue, Encoding.UTF8), pname); - } - } - } - } - - var response = await this.PostRequestAsyncMultipartFormData(method, content, cancellationToken).ConfigureAwait(false); - content.Dispose(); - if (response.Ok == true) - { - return response.Result; - } - else - { - if (this.IgnoreBotExceptions) - { - return default; - } - else - { - throw new BotRequestException(response.ErrorCode, response.Description, response.Parameters); - } - } - } -} diff --git a/src/Telegram.BotAPI/BotRequestException.cs b/src/Telegram.BotAPI/BotRequestException.cs deleted file mode 100644 index 3ad31178..00000000 --- a/src/Telegram.BotAPI/BotRequestException.cs +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using System.Collections; -using System.Net.Http; -using System.Reflection; -using Telegram.BotAPI.AvailableTypes; - -namespace Telegram.BotAPI; - -/// Exception generated when a request to Telegram Bot API got an error response. -public sealed class BotRequestException : Exception, IEquatable -{ - /// Error code. - public int ErrorCode { get; } - /// Error description. - public string Description { get; } - /// Parameters. - public ResponseParameters Parameters { get; } - - /// The original http response. Only available if the http response message could not be read as a valid BotRequest. - public HttpResponseMessage ResponseMessage { get; } - - /// Initializes a new instance of the class with the specified error code and description message. - /// Error code. - /// Description. - /// Parameters. - public BotRequestException(int errorCode, string description, ResponseParameters parameters) : base(description) - { - this.ErrorCode = errorCode; - this.Description = description; - this.Parameters = parameters; - } - - /// - /// Initializes a new instance of the class. - /// - /// The http request exception that is the cause of the current exception. - /// The failed http response. - public BotRequestException(HttpRequestException httpRequestException, HttpResponseMessage httpResponseMessage) : base("The response message cannot be read as a valid Bot Response.", httpRequestException) - { - if (httpRequestException == null) - { - throw new ArgumentNullException(nameof(httpRequestException)); - } - if (httpResponseMessage == null) - { - throw new ArgumentNullException(nameof(httpResponseMessage)); - } - this.ErrorCode = (int)httpResponseMessage.StatusCode; - this.Description = httpRequestException.Message; - this.ResponseMessage = httpResponseMessage; - } - /// - public override bool Equals(object obj) - { - return this.Equals(obj as BotRequestException); - } - /// - public bool Equals(BotRequestException? other) - { - return other != null && - EqualityComparer.Default.Equals(this.Data, other.Data) && - this.HelpLink == other.HelpLink && - this.HResult == other.HResult && - EqualityComparer.Default.Equals(this.InnerException, other.InnerException) && - this.Message == other.Message && - this.Source == other.Source && - this.StackTrace == other.StackTrace && - EqualityComparer.Default.Equals(this.TargetSite, other.TargetSite) && - this.ErrorCode == other.ErrorCode && - this.Description == other.Description && - EqualityComparer.Default.Equals(this.Parameters, other.Parameters) && - EqualityComparer.Default.Equals(this.ResponseMessage, other.ResponseMessage); - } - /// - public override int GetHashCode() - { - int hashCode = -840958873; - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Data); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.HelpLink); - hashCode = hashCode * -1521134295 + this.HResult.GetHashCode(); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.InnerException); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Message); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Source); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.StackTrace); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.TargetSite); - hashCode = hashCode * -1521134295 + this.ErrorCode.GetHashCode(); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Description); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Parameters); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ResponseMessage); - return hashCode; - } - /// - public static bool operator ==(BotRequestException? left, BotRequestException? right) - { - return EqualityComparer.Default.Equals(left!, right!); - } - /// - public static bool operator !=(BotRequestException? left, BotRequestException? right) - { - return !(left == right); - } - -} diff --git a/src/Telegram.BotAPI/BotResponse.cs b/src/Telegram.BotAPI/BotResponse.cs deleted file mode 100644 index 839699ee..00000000 --- a/src/Telegram.BotAPI/BotResponse.cs +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using Telegram.BotAPI.AvailableTypes; - -namespace Telegram.BotAPI; - -/// Represents the bot's response to the request. -/// Result type. -[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public sealed class BotResponse : IEquatable> -{ - /// True, if the request was successful, otherwise false. - [JsonPropertyName("ok")] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public bool Ok { get; set; } - /// Result. - [JsonPropertyName("result")] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public T Result { get; set; } - /// Error code. - [JsonPropertyName("error_code")] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public int ErrorCode { get; set; } - /// Error description. - [JsonPropertyName("description")] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string Description { get; set; } - /// Parameters. - [JsonPropertyName("parameters")] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public ResponseParameters Parameters { get; set; } - /// - public override bool Equals(object obj) - { - return this.Equals(obj as BotResponse); - } - /// - public bool Equals(BotResponse? other) - { - return other != null && - this.Ok == other.Ok && - EqualityComparer.Default.Equals(this.Result, other.Result) && - this.ErrorCode == other.ErrorCode && - this.Description == other.Description && - EqualityComparer.Default.Equals(this.Parameters, other.Parameters); - } - /// - public override int GetHashCode() - { - int hashCode = 493339093; - hashCode = hashCode * -1521134295 + this.Ok.GetHashCode(); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Result); - hashCode = hashCode * -1521134295 + this.ErrorCode.GetHashCode(); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Description); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Parameters); - return hashCode; - } - /// - public static bool operator ==(BotResponse? left, BotResponse? right) - { - return EqualityComparer>.Default.Equals(left!, right!); - } - /// - public static bool operator !=(BotResponse? left, BotResponse? right) - { - return !(left == right); - } - -} diff --git a/src/Telegram.BotAPI/Games/Args/SendGameArgs.cs b/src/Telegram.BotAPI/Games/Args/SendGameArgs.cs deleted file mode 100644 index aab11018..00000000 --- a/src/Telegram.BotAPI/Games/Args/SendGameArgs.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using Telegram.BotAPI.AvailableTypes; - - -namespace Telegram.BotAPI.Games; - -/// SendGame method arguments. -[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class SendGameArgs : SendMessageBase, ICustomizableReplyMarkup -{ - /// - /// Initialize a new instance of . - /// - /// Unique identifier for the target chat. - /// Short name of the game, serves as the unique identifier for the game. Set up your games via BotFather. - /// - public SendGameArgs(long chatId, string gameShortName) : base(chatId) - { - this.ChatId = chatId; - this.GameShortName = gameShortName ?? throw new ArgumentNullException(nameof(gameShortName)); - } - - /// Unique identifier for the target chat. - [JsonPropertyName(PropertyNames.ChatId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public override long ChatId { get; } - /// Short name of the game, serves as the unique identifier for the game. Set up your games via BotFather. - [JsonPropertyName(PropertyNames.GameShortName)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string GameShortName { get; } - /// Optional. A JSON-serialized object for an inline keyboard. If empty, one ‘Play game_title’ button will be shown. If not empty, the first button must launch the game. - [JsonPropertyName(PropertyNames.ReplyMarkup)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public InlineKeyboardMarkup? ReplyMarkup { get; set; } -} diff --git a/src/Telegram.BotAPI/Getting updates/Update.cs b/src/Telegram.BotAPI/Getting updates/Update.cs deleted file mode 100644 index cfc424d0..00000000 --- a/src/Telegram.BotAPI/Getting updates/Update.cs +++ /dev/null @@ -1,208 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using Telegram.BotAPI.AvailableTypes; -using Telegram.BotAPI.InlineMode; -using Telegram.BotAPI.Payments; - -namespace Telegram.BotAPI.GettingUpdates; - -/// This object represents an incoming update. -/// At most one of the optional parameters can be present in any given update. -[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public sealed class Update : IEquatable -{ - /// The update‘s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially. - [JsonPropertyName(PropertyNames.UpdateId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public int UpdateId { get; set; } - /// Optional. New incoming message of any kind — text, photo, sticker, etc. - [JsonPropertyName(PropertyNames.Message)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public Message? Message { get; set; } - /// Optional. New version of a message that is known to the bot and was edited. - [JsonPropertyName(PropertyNames.EditedMessage)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public Message? EditedMessage { get; set; } - /// Optional. New incoming channel post of any kind — text, photo, sticker, etc. - [JsonPropertyName(PropertyNames.ChannelPost)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public Message? ChannelPost { get; set; } - /// Optional. New version of a channel post that is known to the bot and was edited. - [JsonPropertyName(PropertyNames.EditedChannelPost)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public Message? EditedChannelPost { get; set; } - /// Optional. New incoming inline query. - [JsonPropertyName(PropertyNames.InlineQuery)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public InlineQuery? InlineQuery { get; set; } - /// Optional. The result of an inline query that was chosen by a user and sent to their chat partner. Please see our documentation on the feedback collecting for details on how to enable these updates for your bot. - [JsonPropertyName(PropertyNames.ChosenInlineResult)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public ChosenInlineResult? ChosenInlineResult { get; set; } - /// Optional. New incoming callback query. - [JsonPropertyName(PropertyNames.CallbackQuery)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public CallbackQuery? CallbackQuery { get; set; } - /// Optional. New incoming shipping query. Only for invoices with flexible price. - [JsonPropertyName(PropertyNames.ShippingQuery)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public ShippingQuery? ShippingQuery { get; set; } - /// Optional. New incoming pre-checkout query. Contains full information about checkout. - [JsonPropertyName(PropertyNames.PreCheckoutQuery)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public PreCheckoutQuery? PreCheckoutQuery { get; set; } - /// Optional. New poll state. Bots receive only updates about stopped polls and polls, which are sent by the bot. - [JsonPropertyName(PropertyNames.Poll)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public Poll? Poll { get; set; } - /// Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself. - [JsonPropertyName(PropertyNames.PollAnswer)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public PollAnswer? PollAnswer { get; set; } - /// Optional. The bot's chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user. - [JsonPropertyName(PropertyNames.MyChatMember)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public ChatMemberUpdated? MyChatMember { get; set; } - /// Optional. A chat member's status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify “chat_member” in the list of allowed_updates to receive these updates. - [JsonPropertyName(PropertyNames.ChatMember)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public ChatMemberUpdated? ChatMember { get; set; } - /// Optional. A request to join the chat has been sent. The bot must have the can_invite_users administrator right in the chat to receive these updates. - [JsonPropertyName(PropertyNames.ChatJoinRequest)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public ChatJoinRequest? ChatJoinRequest { get; set; } - - /// Update type. - [System.Text.Json.Serialization.JsonIgnore] - [Newtonsoft.Json.JsonIgnore] - public UpdateType Type - { - get - { - if (this.Message != default) - { - return UpdateType.Message; - } - else if (this.EditedMessage != default) - { - return UpdateType.EditedMessage; - } - else if (this.ChannelPost != default) - { - return UpdateType.ChannelPost; - } - else if (this.EditedChannelPost != default) - { - return UpdateType.EditedChannelPost; - } - else if (this.InlineQuery != default) - { - return UpdateType.InlineQuery; - } - else if (this.ChosenInlineResult != default) - { - return UpdateType.ChosenInlineResult; - } - else if (this.CallbackQuery != default) - { - return UpdateType.CallbackQuery; - } - else if (this.ShippingQuery != default) - { - return UpdateType.ShippingQuery; - } - else if (this.PreCheckoutQuery != default) - { - return UpdateType.PreCheckoutQuery; - } - else if (this.Poll != default) - { - return UpdateType.Poll; - } - else if (this.PollAnswer != default) - { - return UpdateType.PollAnswer; - } - else if (this.MyChatMember != default) - { - return UpdateType.MyChatMember; - } - else if (this.ChatMember != default) - { - return UpdateType.ChatMember; - } - else if (this.ChatJoinRequest != default) - { - return UpdateType.ChatMember; - } - else - { - return UpdateType.Unknown; - } - } - } - /// - - - public override bool Equals(object? obj) - { - return this.Equals(obj as Update); - } - /// - public bool Equals(Update? other) - { - return other is not null && - this.UpdateId == other.UpdateId && - EqualityComparer.Default.Equals(this.Message, other.Message) && - EqualityComparer.Default.Equals(this.EditedMessage, other.EditedMessage) && - EqualityComparer.Default.Equals(this.ChannelPost, other.ChannelPost) && - EqualityComparer.Default.Equals(this.EditedChannelPost, other.EditedChannelPost) && - EqualityComparer.Default.Equals(this.InlineQuery, other.InlineQuery) && - EqualityComparer.Default.Equals(this.ChosenInlineResult, other.ChosenInlineResult) && - EqualityComparer.Default.Equals(this.CallbackQuery, other.CallbackQuery) && - EqualityComparer.Default.Equals(this.ShippingQuery, other.ShippingQuery) && - EqualityComparer.Default.Equals(this.PreCheckoutQuery, other.PreCheckoutQuery) && - EqualityComparer.Default.Equals(this.Poll, other.Poll) && - EqualityComparer.Default.Equals(this.PollAnswer, other.PollAnswer) && - EqualityComparer.Default.Equals(this.MyChatMember, other.MyChatMember) && - EqualityComparer.Default.Equals(this.ChatMember, other.ChatMember) && - EqualityComparer.Default.Equals(this.ChatJoinRequest, other.ChatJoinRequest) && - this.Type == other.Type; - } - /// - public override int GetHashCode() - { - int hashCode = 990428338; - hashCode = hashCode * -1521134295 + this.UpdateId.GetHashCode(); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Message); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.EditedMessage); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ChannelPost); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.EditedChannelPost); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.InlineQuery); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ChosenInlineResult); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.CallbackQuery); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ShippingQuery); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.PreCheckoutQuery); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Poll); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.PollAnswer); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.MyChatMember); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ChatMember); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ChatJoinRequest); - hashCode = hashCode * -1521134295 + this.Type.GetHashCode(); - return hashCode; - } - /// - public static bool operator ==(Update? left, Update? right) - { - return EqualityComparer.Default.Equals(left!, right!); - } - /// - public static bool operator !=(Update? left, Update? right) - { - return !(left == right); - } - -} diff --git a/src/Telegram.BotAPI/Inline mode/InputMessageContent/InputTextMessageContent.cs b/src/Telegram.BotAPI/Inline mode/InputMessageContent/InputTextMessageContent.cs deleted file mode 100644 index 6dce14e9..00000000 --- a/src/Telegram.BotAPI/Inline mode/InputMessageContent/InputTextMessageContent.cs +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using Telegram.BotAPI.AvailableTypes; - -namespace Telegram.BotAPI.InlineMode; - -/// Represents the content of a text message to be sent as the result of an inline query. -[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public sealed class InputTextMessageContent : InputMessageContent, IEquatable -{ - /// - /// Initialize a new instance of . - /// - /// Text of the message to be sent, 1-4096 characters. - /// Disables link previews for links in the sent message. - /// - public InputTextMessageContent(string messageText, [Optional] bool? disableWebPagePreview) - { - this.MessageText = messageText ?? throw new ArgumentNullException(nameof(messageText)); - this.DisableWebPagePreview = disableWebPagePreview; - } - - /// - /// Initialize a new instance of . - /// - /// Text of the message to be sent, 1-4096 characters. - /// Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. - /// Disables link previews for links in the sent message. - /// - public InputTextMessageContent(string messageText, string parseMode, [Optional] bool? disableWebPagePreview) - { - if (string.IsNullOrEmpty(parseMode)) - { - throw new ArgumentNullException(nameof(messageText)); - } - - this.MessageText = messageText ?? throw new ArgumentNullException(nameof(messageText)); - this.ParseMode = parseMode; - this.DisableWebPagePreview = disableWebPagePreview; - } - - /// - /// Initialize a new instance of . - /// - /// Text of the message to be sent, 1-4096 characters. - /// List of special entities that appear in message text, which can be specified instead of parse_mode. - /// Disables link previews for links in the sent message. - /// - public InputTextMessageContent(string messageText, IEnumerable entities, [Optional] bool? disableWebPagePreview) - { - this.MessageText = messageText ?? throw new ArgumentNullException(nameof(messageText)); - this.Entities = entities ?? throw new ArgumentNullException(nameof(entities)); - this.DisableWebPagePreview = disableWebPagePreview; - } - - /// Text of the message to be sent, 1-4096 characters. - [JsonPropertyName(PropertyNames.MessageText)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string MessageText { get; } - /// Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. - [JsonPropertyName(PropertyNames.ParseMode)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string? ParseMode { get; } - /// Optional. List of special entities that appear in message text, which can be specified instead of parse_mode. - [JsonPropertyName(PropertyNames.Entities)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public IEnumerable? Entities { get; } - /// Optional. Disables link previews for links in the sent message. - [JsonPropertyName(PropertyNames.DisableWebPagePreview)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public bool? DisableWebPagePreview { get; } - /// - public override bool Equals(object obj) - { - return this.Equals(obj as InputTextMessageContent); - } - /// - public bool Equals(InputTextMessageContent? other) - { - return other != null && - this.MessageText == other.MessageText && - this.ParseMode == other.ParseMode && - EqualityComparer?>.Default.Equals(this.Entities, other.Entities) && - this.DisableWebPagePreview == other.DisableWebPagePreview; - } - /// - public override int GetHashCode() - { - int hashCode = 119831400; - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.MessageText); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ParseMode); - hashCode = hashCode * -1521134295 + EqualityComparer?>.Default.GetHashCode(this.Entities); - hashCode = hashCode * -1521134295 + this.DisableWebPagePreview.GetHashCode(); - return hashCode; - } - /// - public static bool operator ==(InputTextMessageContent? left, InputTextMessageContent? right) - { - return EqualityComparer.Default.Equals(left!, right!); - } - /// - public static bool operator !=(InputTextMessageContent? left, InputTextMessageContent? right) - { - return !(left == right); - } - -} diff --git a/src/Telegram.BotAPI/Stickers/Args/AddStickerToSetArgs.cs b/src/Telegram.BotAPI/Stickers/Args/AddStickerToSetArgs.cs deleted file mode 100644 index 10ad1672..00000000 --- a/src/Telegram.BotAPI/Stickers/Args/AddStickerToSetArgs.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using System.Linq; -using Telegram.BotAPI.AvailableTypes; - -namespace Telegram.BotAPI.Stickers; - -/// AddStickerToSet method arguments. -[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class AddStickerToSetArgs : IMultipartForm -{ - /// - /// Initialize a new instance of . - /// - /// User identifier of sticker set owner. - /// Sticker set name. - /// A object with information about the added sticker. If exactly the same sticker had already been added to the set, then the set isn't changed. - /// - public AddStickerToSetArgs(long userId, string name, InputSticker sticker) - { - this.UserId = userId; - this.Name = name ?? throw new ArgumentNullException(nameof(name)); - this.Sticker = sticker ?? throw new ArgumentNullException(nameof(sticker)); - } - - /// User identifier of sticker set owner. - [JsonPropertyName(PropertyNames.UserId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public long UserId { get; } - /// Sticker set name. - [JsonPropertyName(PropertyNames.Name)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string Name { get; } - /// - /// A object with information about the added sticker. If exactly the same sticker had already been added to the set, then the set isn't changed. - /// - [JsonPropertyName(PropertyNames.Sticker)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public InputSticker Sticker { get; } - - /// - [System.Text.Json.Serialization.JsonIgnore] - public IEnumerable AttachedFiles { get; set; } = new HashSet(); - - /// - bool IMultipartForm.UseMultipart() => this.AttachedFiles.Any(); -} diff --git a/src/Telegram.BotAPI/Sugar Library/ITelegramBot.cs b/src/Telegram.BotAPI/Sugar Library/ITelegramBot.cs deleted file mode 100644 index 3c51345a..00000000 --- a/src/Telegram.BotAPI/Sugar Library/ITelegramBot.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Telegram.BotAPI.GettingUpdates; - -namespace Telegram.BotAPI; - -/// Defines the OnUpdate method, used by basic Telegram bots. -public interface ITelegramBot -{ - /// Call the corresponding method according to the type of update provided. - /// Update - void OnUpdate(Update update); -} diff --git a/src/Telegram.BotAPI/Tools.cs b/src/Telegram.BotAPI/Tools.cs deleted file mode 100644 index ef642c19..00000000 --- a/src/Telegram.BotAPI/Tools.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using System.IO; -using System.Linq; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; - -namespace Telegram.BotAPI; - -internal static class Tools -{ - internal static async Task SerializeAsStreamAsync(object args, [Optional] JsonSerializerOptions options, [Optional] CancellationToken cancellationToken) - { - if (options == default) - { - options = BotClient.DefaultSerializerOptions; - } - var stream = new MemoryStream(); - await JsonSerializer.SerializeAsync(stream, args, args.GetType(), options, cancellationToken).ConfigureAwait(false); - stream.Seek(0, SeekOrigin.Begin); - return stream; - } - - internal static bool IsNumber(this object value) - { - return value is sbyte - || value is byte - || value is short - || value is ushort - || value is int - || value is uint - || value is long - || value is ulong - || value is float - || value is double - || value is decimal; - } - - /// - /// Gets the depth of an enumerable. - /// - /// Type of the enumerable - /// The enumerable value - /// The depth of the enumerator. - internal static uint GetDepth(IEnumerable enumerable) - { - // Base case: if the enumerable is empty or null, return 0 - if (enumerable == null || !enumerable.Any()) - return 0; - - // Get the first element of the enumerable - var first = enumerable.First(); - - // If the first element is also an IEnumerable, add 1 and recurse on it - if (first is IEnumerable innerEnumerable) - return 1u + GetDepth(innerEnumerable); - - // Otherwise, return 1 as the depth of the enumerable - return 1; - } -} diff --git a/src/Telegram.BotAPI/Updating messages/Args/EditMessageMediaArgs.cs b/src/Telegram.BotAPI/Updating messages/Args/EditMessageMediaArgs.cs deleted file mode 100644 index 95e066a8..00000000 --- a/src/Telegram.BotAPI/Updating messages/Args/EditMessageMediaArgs.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using System.Linq; -using Telegram.BotAPI.AvailableTypes; - -namespace Telegram.BotAPI.UpdatingMessages; - -/// EditMessageMedia method arguments. -[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class EditMessageMediaArgs : IMultipartForm -{ - /// - /// Initialize a new instance of . - /// - /// A object for a new media content of the message. - /// - public EditMessageMediaArgs(InputMedia media) - { - this.Media = media ?? throw new ArgumentNullException(nameof(media)); - } - - /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). - [JsonPropertyName(PropertyNames.ChatId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public object? ChatId { get; set; } - /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). - [JsonPropertyName(PropertyNames.MessageId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public int? MessageId { get; set; } - /// Required if chat_id and message_id are not specified. Identifier of the inline message. - [JsonPropertyName(PropertyNames.InlineMessageId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string? InlineMessageId { get; set; } - /// A object for a new media content of the message. - [JsonPropertyName(PropertyNames.Media)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public InputMedia Media { get; } - /// A object for a new inline keyboard. - [JsonPropertyName(PropertyNames.ReplyMarkup)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public InlineKeyboardMarkup? ReplyMarkup { get; set; } - - /// - [System.Text.Json.Serialization.JsonIgnore] - public IEnumerable AttachedFiles { get; set; } = new HashSet(); - - bool IMultipartForm.UseMultipart() => this.AttachedFiles.Any(); -} diff --git a/src/Telegram.BotAPI/Updating messages/Args/EditMessageReplyMarkup.cs b/src/Telegram.BotAPI/Updating messages/Args/EditMessageReplyMarkup.cs deleted file mode 100644 index ce474740..00000000 --- a/src/Telegram.BotAPI/Updating messages/Args/EditMessageReplyMarkup.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using Telegram.BotAPI.AvailableTypes; - -namespace Telegram.BotAPI.UpdatingMessages; - -/// EditMessageReplyMarkup method arguments. -[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class EditMessageReplyMarkup -{ - /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). - [JsonPropertyName(PropertyNames.ChatId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public object ChatId { get; set; } - /// Required if inline_message_id is not specified. Identifier of the message to edit. - [JsonPropertyName(PropertyNames.MessageId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public int MessageId { get; set; } - /// Required if chat_id and message_id are not specified. Identifier of the inline message. - [JsonPropertyName(PropertyNames.InlineMessageId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string InlineMessageId { get; set; } - /// A object for an inline keyboard. - [JsonPropertyName(PropertyNames.ReplyMarkup)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public InlineKeyboardMarkup ReplyMarkup { get; set; } -} diff --git a/src/Telegram.BotAPI/Updating messages/Args/EditMessageTextArgs.cs b/src/Telegram.BotAPI/Updating messages/Args/EditMessageTextArgs.cs deleted file mode 100644 index 970e4916..00000000 --- a/src/Telegram.BotAPI/Updating messages/Args/EditMessageTextArgs.cs +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using Telegram.BotAPI.AvailableTypes; - -namespace Telegram.BotAPI.UpdatingMessages; - -/// EditMessage method arguments. -[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class EditMessageTextArgs : IFormattableMessage -{ - /// - /// Initializes a new instance of the class. - /// - /// New text of the message. - public EditMessageTextArgs(string text) - { - this.Text = text ?? throw new ArgumentNullException(nameof(text)); - } - - /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). - [JsonPropertyName(PropertyNames.ChatId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public object? ChatId { get; set; } - /// Required if inline_message_id is not specified. Identifier of the message to edit. - [JsonPropertyName(PropertyNames.MessageId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public int? MessageId { get; set; } - /// Required if chat_id and message_id are not specified. Identifier of the inline message. - [JsonPropertyName(PropertyNames.InlineMessageId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string? InlineMessageId { get; set; } - /// New text of the message. - [JsonPropertyName(PropertyNames.Text)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string Text { get; } - /// Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. - [JsonPropertyName(PropertyNames.ParseMode)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string? ParseMode { get; set; } - /// List of special entities that appear in message text, which can be specified instead of parse_mode. - [JsonPropertyName(PropertyNames.Entities)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public IEnumerable? Entities { get; set; } - /// Disables link previews for links in this message - [JsonPropertyName(PropertyNames.DisableWebPagePreview)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public bool? DisableWebPagePreview { get; set; } - /// A object for an inline keyboard. - [JsonPropertyName(PropertyNames.ReplyMarkup)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public InlineKeyboardMarkup? ReplyMarkup { get; set; } -} diff --git a/src/Telegram.BotAPI/Updating messages/editMessageCaption.cs b/src/Telegram.BotAPI/Updating messages/editMessageCaption.cs deleted file mode 100644 index d0f65530..00000000 --- a/src/Telegram.BotAPI/Updating messages/editMessageCaption.cs +++ /dev/null @@ -1,403 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using System.Threading; -using System.Threading.Tasks; -using Telegram.BotAPI.AvailableTypes; - - -namespace Telegram.BotAPI.UpdatingMessages; - -public static partial class UpdatingMessagesExtensions -{ - /// Use this method to edit captions of messages. - /// BotClient - /// Parameters. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// or . On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. - public static Message EditMessageCaption(this BotClient? bot, EditMessageCaptionArgs args) - { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - return bot.RPC(MethodNames.EditMessageCaption, args); - } - - /// Use this method to edit captions of messages. - /// BotClient - /// Parameters. - /// The cancellation token to cancel operation. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// or . On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. - public static async Task EditMessageCaptionAsync(this BotClient? bot, EditMessageCaptionArgs args, [Optional] CancellationToken cancellationToken) - { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - return await bot.RPCA(MethodNames.EditMessageCaption, args, cancellationToken).ConfigureAwait(false); - } - /// Use this method to edit captions of messages. - /// BotClient - /// Parameters. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// Thrown when T is not Telegram.BotAPI.AvailableTypes.Message or bool. - /// or . On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. - public static T EditMessageCaption(this BotClient? bot, EditMessageCaptionArgs args) - { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - if (typeof(T) != typeof(Message) && typeof(T) != typeof(bool)) - { - throw new ArgumentException($"{nameof(T)} must be Telegram.BotAPI.AvailableTypes.Message or bool."); - } - return bot.RPC(MethodNames.EditMessageCaption, args); - } - /// Use this method to edit captions of messages. - /// BotClient - /// Parameters. - /// The cancellation token to cancel operation. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// Thrown when T is not Telegram.BotAPI.AvailableTypes.Message or bool. - /// or . On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. - public static async Task EditMessageCaptionAsync(this BotClient? bot, EditMessageCaptionArgs args, [Optional] CancellationToken cancellationToken) - { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - if (typeof(T) != typeof(Message) && typeof(T) != typeof(bool)) - { - throw new ArgumentException($"{nameof(T)} must be Telegram.BotAPI.AvailableTypes.Message or bool."); - } - return await bot.RPCA(MethodNames.EditMessageCaption, args, cancellationToken).ConfigureAwait(false); - } - - /// Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. - /// The bot client. - /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Required if inline_message_id is not specified. Identifier of the message to edit. - /// New caption of the message, 0-1024 characters after entities parsing. - /// Mode for parsing entities in the message caption. See formatting options for more details. - /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. - /// A JSON-serialized object for an inline keyboard. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - public static Message EditMessageCaption(this BotClient? api, long chatId, int messageId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] InlineKeyboardMarkup? replyMarkup) - { - if (api == null) { throw new ArgumentNullException(nameof(api)); } - var args = new EditMessageCaptionArgs(chatId, messageId) - { - Caption = caption, - ParseMode = parseMode, - CaptionEntities = captionEntities, - ReplyMarkup = replyMarkup - }; - return api.RPC(MethodNames.EditMessageCaption, args); - } - - /// Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. - /// The bot client. - /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Required if inline_message_id is not specified. Identifier of the message to edit. - /// New caption of the message, 0-1024 characters after entities parsing. - /// Mode for parsing entities in the message caption. See formatting options for more details. - /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. - /// A JSON-serialized object for an inline keyboard. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - public static Message EditMessageCaption(this BotClient? api, string chatId, int messageId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] InlineKeyboardMarkup? replyMarkup) - { - if (api == null) { throw new ArgumentNullException(nameof(api)); } - var args = new EditMessageCaptionArgs(chatId, messageId) - { - Caption = caption, - ParseMode = parseMode, - CaptionEntities = captionEntities, - ReplyMarkup = replyMarkup - }; - return api.RPC(MethodNames.EditMessageCaption, args); - } - - /// Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. - /// The bot client. - /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Required if inline_message_id is not specified. Identifier of the message to edit. - /// New caption of the message, 0-1024 characters after entities parsing. - /// Mode for parsing entities in the message caption. See formatting options for more details. - /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. - /// A JSON-serialized object for an inline keyboard. - /// The cancellation token to cancel operation. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - public static async Task EditMessageCaptionAsync(this BotClient? api, long chatId, int messageId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] InlineKeyboardMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) - { - if (api == null) { throw new ArgumentNullException(nameof(api)); } - var args = new EditMessageCaptionArgs(chatId, messageId) - { - Caption = caption, - ParseMode = parseMode, - CaptionEntities = captionEntities, - ReplyMarkup = replyMarkup - }; - return await api.RPCA(MethodNames.EditMessageCaption, args, cancellationToken).ConfigureAwait(false); - } - - /// Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. - /// The bot client. - /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Required if inline_message_id is not specified. Identifier of the message to edit. - /// New caption of the message, 0-1024 characters after entities parsing. - /// Mode for parsing entities in the message caption. See formatting options for more details. - /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. - /// A JSON-serialized object for an inline keyboard. - /// The cancellation token to cancel operation. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - public static async Task EditMessageCaptionAsync(this BotClient? api, string chatId, int messageId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] InlineKeyboardMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) - { - if (api == null) { throw new ArgumentNullException(nameof(api)); } - var args = new EditMessageCaptionArgs(chatId, messageId) - { - Caption = caption, - ParseMode = parseMode, - CaptionEntities = captionEntities, - ReplyMarkup = replyMarkup - }; - return await api.RPCA(MethodNames.EditMessageCaption, args, cancellationToken).ConfigureAwait(false); - } - - /// Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. - /// The bot client. - /// Required if chat_id and message_id are not specified. Identifier of the inline message. - /// New caption of the message, 0-1024 characters after entities parsing. - /// Mode for parsing entities in the message caption. See formatting options for more details. - /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. - /// A JSON-serialized object for an inline keyboard. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - public static Message EditMessageCaption(this BotClient? api, string inlineMessageId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] InlineKeyboardMarkup? replyMarkup) - { - if (api == null) { throw new ArgumentNullException(nameof(api)); } - var args = new EditMessageCaptionArgs(inlineMessageId) - { - Caption = caption, - ParseMode = parseMode, - CaptionEntities = captionEntities, - ReplyMarkup = replyMarkup - }; - return api.RPC(MethodNames.EditMessageCaption, args); - } - - /// Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. - /// The bot client. - /// Required if chat_id and message_id are not specified. Identifier of the inline message. - /// New caption of the message, 0-1024 characters after entities parsing. - /// Mode for parsing entities in the message caption. See formatting options for more details. - /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. - /// A JSON-serialized object for an inline keyboard. - /// The cancellation token to cancel operation. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - public static async Task EditMessageCaptionAsync(this BotClient? api, string inlineMessageId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] InlineKeyboardMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) - { - if (api == null) { throw new ArgumentNullException(nameof(api)); } - var args = new EditMessageCaptionArgs(inlineMessageId) - { - Caption = caption, - ParseMode = parseMode, - CaptionEntities = captionEntities, - ReplyMarkup = replyMarkup - }; - return await api.RPCA(MethodNames.EditMessageCaption, args, cancellationToken).ConfigureAwait(false); - } - - // Generics - - /// Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. - /// The bot client. - /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Required if inline_message_id is not specified. Identifier of the message to edit. - /// New caption of the message, 0-1024 characters after entities parsing. - /// Mode for parsing entities in the message caption. See formatting options for more details. - /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. - /// A JSON-serialized object for an inline keyboard. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - public static T EditMessageCaption(this BotClient? api, long chatId, int messageId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] InlineKeyboardMarkup? replyMarkup) - { - if (api == null) { throw new ArgumentNullException(nameof(api)); } - if (typeof(T) != typeof(Message) && typeof(T) != typeof(bool)) - { - throw new ArgumentException($"{nameof(T)} must be Telegram.BotAPI.AvailableTypes.Message or bool."); - } - - var args = new EditMessageCaptionArgs(chatId, messageId) - { - Caption = caption, - ParseMode = parseMode, - CaptionEntities = captionEntities, - ReplyMarkup = replyMarkup - }; - return api.RPC(MethodNames.EditMessageCaption, args); - } - - /// Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. - /// The bot client. - /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Required if inline_message_id is not specified. Identifier of the message to edit. - /// New caption of the message, 0-1024 characters after entities parsing. - /// Mode for parsing entities in the message caption. See formatting options for more details. - /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. - /// A JSON-serialized object for an inline keyboard. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - public static T EditMessageCaption(this BotClient? api, string chatId, int messageId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] InlineKeyboardMarkup? replyMarkup) - { - if (api == null) { throw new ArgumentNullException(nameof(api)); } - if (typeof(T) != typeof(Message) && typeof(T) != typeof(bool)) - { - throw new ArgumentException($"{nameof(T)} must be Telegram.BotAPI.AvailableTypes.Message or bool."); - } - var args = new EditMessageCaptionArgs(chatId, messageId) - { - Caption = caption, - ParseMode = parseMode, - CaptionEntities = captionEntities, - ReplyMarkup = replyMarkup - }; - return api.RPC(MethodNames.EditMessageCaption, args); - } - - /// Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. - /// The bot client. - /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Required if inline_message_id is not specified. Identifier of the message to edit. - /// New caption of the message, 0-1024 characters after entities parsing. - /// Mode for parsing entities in the message caption. See formatting options for more details. - /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. - /// A JSON-serialized object for an inline keyboard. - /// The cancellation token to cancel operation. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - public static async Task EditMessageCaptionAsync(this BotClient? api, long chatId, int messageId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] InlineKeyboardMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) - { - if (api == null) { throw new ArgumentNullException(nameof(api)); } - if (typeof(T) != typeof(Message) && typeof(T) != typeof(bool)) - { - throw new ArgumentException($"{nameof(T)} must be Telegram.BotAPI.AvailableTypes.Message or bool."); - } - var args = new EditMessageCaptionArgs(chatId, messageId) - { - Caption = caption, - ParseMode = parseMode, - CaptionEntities = captionEntities, - ReplyMarkup = replyMarkup - }; - return await api.RPCA(MethodNames.EditMessageCaption, args, cancellationToken).ConfigureAwait(false); - } - - /// Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. - /// The bot client. - /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Required if inline_message_id is not specified. Identifier of the message to edit. - /// New caption of the message, 0-1024 characters after entities parsing. - /// Mode for parsing entities in the message caption. See formatting options for more details. - /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. - /// A JSON-serialized object for an inline keyboard. - /// The cancellation token to cancel operation. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - public static async Task EditMessageCaptionAsync(this BotClient? api, string chatId, int messageId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] InlineKeyboardMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) - { - if (api == null) { throw new ArgumentNullException(nameof(api)); } - if (typeof(T) != typeof(Message) && typeof(T) != typeof(bool)) - { - throw new ArgumentException($"{nameof(T)} must be Telegram.BotAPI.AvailableTypes.Message or bool."); - } - var args = new EditMessageCaptionArgs(chatId, messageId) - { - Caption = caption, - ParseMode = parseMode, - CaptionEntities = captionEntities, - ReplyMarkup = replyMarkup - }; - return await api.RPCA(MethodNames.EditMessageCaption, args, cancellationToken).ConfigureAwait(false); - } - - /// Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. - /// The bot client. - /// Required if chat_id and message_id are not specified. Identifier of the inline message. - /// New caption of the message, 0-1024 characters after entities parsing. - /// Mode for parsing entities in the message caption. See formatting options for more details. - /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. - /// A JSON-serialized object for an inline keyboard. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - public static T EditMessageCaption(this BotClient? api, string inlineMessageId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] InlineKeyboardMarkup? replyMarkup) - { - if (api == null) { throw new ArgumentNullException(nameof(api)); } - if (typeof(T) != typeof(Message) && typeof(T) != typeof(bool)) - { - throw new ArgumentException($"{nameof(T)} must be Telegram.BotAPI.AvailableTypes.Message or bool."); - } - var args = new EditMessageCaptionArgs(inlineMessageId) - { - Caption = caption, - ParseMode = parseMode, - CaptionEntities = captionEntities, - ReplyMarkup = replyMarkup - }; - return api.RPC(MethodNames.EditMessageCaption, args); - } - - /// Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. - /// The bot client. - /// Required if chat_id and message_id are not specified. Identifier of the inline message. - /// New caption of the message, 0-1024 characters after entities parsing. - /// Mode for parsing entities in the message caption. See formatting options for more details. - /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. - /// A JSON-serialized object for an inline keyboard. - /// The cancellation token to cancel operation. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - public static async Task EditMessageCaptionAsync(this BotClient? api, string inlineMessageId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] InlineKeyboardMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) - { - if (api == null) { throw new ArgumentNullException(nameof(api)); } - if (typeof(T) != typeof(Message) && typeof(T) != typeof(bool)) - { - throw new ArgumentException($"{nameof(T)} must be Telegram.BotAPI.AvailableTypes.Message or bool."); - } - var args = new EditMessageCaptionArgs(inlineMessageId) - { - Caption = caption, - ParseMode = parseMode, - CaptionEntities = captionEntities, - ReplyMarkup = replyMarkup - }; - return await api.RPCA(MethodNames.EditMessageCaption, args, cancellationToken).ConfigureAwait(false); - } -} \ No newline at end of file diff --git a/src/Telegram.BotAPI/Updating messages/editMessageMedia.cs b/src/Telegram.BotAPI/Updating messages/editMessageMedia.cs deleted file mode 100644 index d88566d1..00000000 --- a/src/Telegram.BotAPI/Updating messages/editMessageMedia.cs +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Newtonsoft.Json.Linq; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Telegram.BotAPI.AvailableTypes; - -namespace Telegram.BotAPI.UpdatingMessages; - -public static partial class UpdatingMessagesExtensions -{ - /// Use this method to edit animation, audio, document, photo, or video messages. If a message is a part of a message album, then it can be edited only to a photo or a video. Otherwise, message type can be changed arbitrarily. When inline message is edited, new file can't be uploaded. Use previously uploaded file via its file_id or specify a URL. - /// BotClient - /// Parameters. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// or . On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned. - public static Message EditMessageMedia(this BotClient? bot, EditMessageMediaArgs args) - { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - return bot.RPCF(MethodNames.EditMessageMedia, args); - } - /// Use this method to edit animation, audio, document, photo, or video messages. If a message is a part of a message album, then it can be edited only to a photo or a video. Otherwise, message type can be changed arbitrarily. When inline message is edited, new file can't be uploaded. Use previously uploaded file via its file_id or specify a URL. - /// BotClient - /// Parameters. - /// The cancellation token to cancel operation. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// or . On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned. - public static async Task EditMessageMediaAsync(this BotClient? bot, EditMessageMediaArgs args, [Optional] CancellationToken cancellationToken) - { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - return await bot.RPCAF(MethodNames.EditMessageMedia, args, cancellationToken: cancellationToken).ConfigureAwait(false); - } - /// Use this method to edit animation, audio, document, photo, or video messages. If a message is a part of a message album, then it can be edited only to a photo or a video. Otherwise, message type can be changed arbitrarily. When inline message is edited, new file can't be uploaded. Use previously uploaded file via its file_id or specify a URL. - /// BotClient - /// Parameters. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// Thrown when T is not Telegram.BotAPI.AvailableTypes.Message or bool. - /// or . On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned. - public static T EditMessageMedia(this BotClient? bot, EditMessageMediaArgs args) - { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - if (typeof(T) != typeof(Message) && typeof(T) != typeof(bool) && typeof(T) != typeof(JObject) && typeof(T) != typeof(JsonDocument)) - { - throw new ArgumentException($"{nameof(T)} must be a Telegram.BotAPI.AvailableTypes.Message or bool."); - } - return bot.RPCF(MethodNames.EditMessageMedia, args); - } - /// Use this method to edit animation, audio, document, photo, or video messages. If a message is a part of a message album, then it can be edited only to a photo or a video. Otherwise, message type can be changed arbitrarily. When inline message is edited, new file can't be uploaded. Use previously uploaded file via its file_id or specify a URL. - /// BotClient - /// Parameters. - /// The cancellation token to cancel operation. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// Thrown when T is not Telegram.BotAPI.AvailableTypes.Message or bool. - /// or . On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned. - public static async Task EditMessageMediaAsync(this BotClient? bot, EditMessageMediaArgs args, [Optional] CancellationToken cancellationToken) - { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - if (typeof(T) != typeof(Message) && typeof(T) != typeof(bool) && typeof(T) != typeof(JObject) && typeof(T) != typeof(JsonDocument)) - { - throw new ArgumentException($"{nameof(T)} must be a Telegram.BotAPI.AvailableTypes.Message or bool."); - } - return await bot.RPCAF(MethodNames.EditMessageMedia, args, cancellationToken: cancellationToken).ConfigureAwait(false); - } -} \ No newline at end of file diff --git a/src/Telegram.BotAPI/Updating messages/editMessageReplyMarkup.cs b/src/Telegram.BotAPI/Updating messages/editMessageReplyMarkup.cs deleted file mode 100644 index 539575b3..00000000 --- a/src/Telegram.BotAPI/Updating messages/editMessageReplyMarkup.cs +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Newtonsoft.Json.Linq; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Telegram.BotAPI.AvailableTypes; - -namespace Telegram.BotAPI.UpdatingMessages; - -public static partial class UpdatingMessagesExtensions -{ - /// Use this method to edit only the reply markup of messages. - /// BotClient - /// Parameters. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// or . On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. - public static Message EditMessageReplyMarkup(this BotClient? bot, EditMessageReplyMarkup args) - { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - return bot.RPC(MethodNames.EditMessageReplyMarkup, args); - } - /// Use this method to edit only the reply markup of messages. - /// BotClient - /// Parameters. - /// The cancellation token to cancel operation. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// or . On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. - public static async Task EditMessageReplyMarkupAsync(this BotClient? bot, EditMessageReplyMarkup args, [Optional] CancellationToken cancellationToken) - { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - return await bot.RPCA(MethodNames.EditMessageReplyMarkup, args, cancellationToken: cancellationToken).ConfigureAwait(false); - } - /// Use this method to edit only the reply markup of messages. - /// BotClient - /// Parameters. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// Thrown when T is not Telegram.BotAPI.AvailableTypes.Message or bool. - /// or . On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. - public static T EditMessageReplyMarkup(this BotClient? bot, EditMessageReplyMarkup args) - { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - if (typeof(T) != typeof(Message) && typeof(T) != typeof(bool) && typeof(T) != typeof(JObject) && typeof(T) != typeof(JsonDocument)) - { - throw new ArgumentException($"{nameof(T)} must be a Telegram.BotAPI.AvailableTypes.Message or bool."); - } - return bot.RPC(MethodNames.EditMessageReplyMarkup, args); - } - /// Use this method to edit only the reply markup of messages. - /// BotClient - /// Parameters. - /// The cancellation token to cancel operation. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// Thrown when T is not Telegram.BotAPI.AvailableTypes.Message or bool. - /// or . On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. - public static async Task EditMessageReplyMarkupAsync(this BotClient? bot, EditMessageReplyMarkup args, [Optional] CancellationToken cancellationToken) - { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - if (typeof(T) != typeof(Message) && typeof(T) != typeof(bool) && typeof(T) != typeof(JObject) && typeof(T) != typeof(JsonDocument)) - { - throw new ArgumentException($"{nameof(T)} must be a Telegram.BotAPI.AvailableTypes.Message or bool."); - } - return await bot.RPCA(MethodNames.EditMessageReplyMarkup, args, cancellationToken: cancellationToken).ConfigureAwait(false); - } -} diff --git a/src/Telegram.BotAPI/Updating messages/editMessageText.cs b/src/Telegram.BotAPI/Updating messages/editMessageText.cs deleted file mode 100644 index ee96ee75..00000000 --- a/src/Telegram.BotAPI/Updating messages/editMessageText.cs +++ /dev/null @@ -1,397 +0,0 @@ -// Copyright (c) 2023 Quetzal Rivera. -// Licensed under the MIT License, See LICENCE in the project root for license information. - -using Newtonsoft.Json.Linq; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Telegram.BotAPI.AvailableTypes; - -namespace Telegram.BotAPI.UpdatingMessages; - -public static partial class UpdatingMessagesExtensions -{ - /// Use this method to edit text and game messages. - /// BotClient - /// Parameters. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// or . On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. - public static Message EditMessageText(this BotClient? bot, EditMessageTextArgs args) - { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - return bot.RPC(MethodNames.EditMessageText, args); - } - /// Use this method to edit text and game messages. - /// BotClient - /// Parameters. - /// The cancellation token to cancel operation. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// or . On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. - public static async Task EditMessageTextAsync(this BotClient? bot, EditMessageTextArgs args, [Optional] CancellationToken cancellationToken) - { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - return await bot.RPCA(MethodNames.EditMessageText, args, cancellationToken: cancellationToken).ConfigureAwait(false); - } - /// Use this method to edit text and game messages. - /// BotClient - /// Parameters. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// Thrown when T is not Telegram.BotAPI.AvailableTypes.Message or bool. - /// or . On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. - public static T EditMessageText(this BotClient? bot, EditMessageTextArgs args) - { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - if (typeof(T) != typeof(Message) && typeof(T) != typeof(bool) && typeof(T) != typeof(JObject) && typeof(T) != typeof(JsonDocument)) - { - throw new ArgumentException($"{nameof(T)} must be a Telegram.BotAPI.AvailableTypes.Message or bool."); - } - return bot.RPC(MethodNames.EditMessageText, args); - } - - /// Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. - /// BotClient - /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername) - /// Required if inline_message_id is not specified. Identifier of the message to edit - /// New text of the message, 1-4096 characters after entities parsing - /// Mode for parsing entities in the message text. See formatting options for more details. - /// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode - /// Disables link previews for links in this message - /// A JSON-serialized object for an inline keyboard. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - public static Message EditMessageText(this BotClient? bot, long chatId, int messageId, string text, [Optional] string parseMode, [Optional] MessageEntity[] entities, [Optional] bool? disableWebPagePreview, [Optional] InlineKeyboardMarkup replyMarkup) - { - var args = new EditMessageTextArgs(text) - { - ChatId = chatId, - MessageId = messageId, - ParseMode = parseMode, - Entities = entities, - DisableWebPagePreview = disableWebPagePreview, - ReplyMarkup = replyMarkup - }; - return bot.EditMessageText(args); - } - /// Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. - /// BotClient - /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername) - /// Required if inline_message_id is not specified. Identifier of the message to edit - /// New text of the message, 1-4096 characters after entities parsing - /// Mode for parsing entities in the message text. See formatting options for more details. - /// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode - /// Disables link previews for links in this message - /// A JSON-serialized object for an inline keyboard. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - public static Message EditMessageText(this BotClient? bot, string chatId, int messageId, string text, [Optional] string parseMode, [Optional] MessageEntity[] entities, [Optional] bool? disableWebPagePreview, [Optional] InlineKeyboardMarkup replyMarkup) - { - var args = new EditMessageTextArgs(text) - { - ChatId = chatId, - MessageId = messageId, - ParseMode = parseMode, - Entities = entities, - DisableWebPagePreview = disableWebPagePreview, - ReplyMarkup = replyMarkup - }; - return bot.EditMessageText(args); - } - /// Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. - /// BotClient - /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername) - /// Required if inline_message_id is not specified. Identifier of the message to edit - /// New text of the message, 1-4096 characters after entities parsing - /// Mode for parsing entities in the message text. See formatting options for more details. - /// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode - /// Disables link previews for links in this message - /// A JSON-serialized object for an inline keyboard. - /// The cancellation token to cancel operation. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - public static async Task EditMessageTextAsync(this BotClient? bot, long chatId, int messageId, string text, [Optional] string parseMode, [Optional] MessageEntity[] entities, [Optional] bool? disableWebPagePreview, [Optional] InlineKeyboardMarkup replyMarkup, [Optional] CancellationToken cancellationToken) - { - var args = new EditMessageTextArgs(text) - { - ChatId = chatId, - MessageId = messageId, - ParseMode = parseMode, - Entities = entities, - DisableWebPagePreview = disableWebPagePreview, - ReplyMarkup = replyMarkup - }; - return await bot.EditMessageTextAsync(args, cancellationToken).ConfigureAwait(false); - } - /// Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. - /// BotClient - /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername) - /// Required if inline_message_id is not specified. Identifier of the message to edit - /// New text of the message, 1-4096 characters after entities parsing - /// Mode for parsing entities in the message text. See formatting options for more details. - /// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode - /// Disables link previews for links in this message - /// A JSON-serialized object for an inline keyboard. - /// The cancellation token to cancel operation. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - public static async Task EditMessageTextAsync(this BotClient? bot, string chatId, int messageId, string text, [Optional] string parseMode, [Optional] MessageEntity[] entities, [Optional] bool? disableWebPagePreview, [Optional] InlineKeyboardMarkup replyMarkup, [Optional] CancellationToken cancellationToken) - { - var args = new EditMessageTextArgs(text) - { - ChatId = chatId, - MessageId = messageId, - ParseMode = parseMode, - Entities = entities, - DisableWebPagePreview = disableWebPagePreview, - ReplyMarkup = replyMarkup - }; - return await bot.EditMessageTextAsync(args, cancellationToken).ConfigureAwait(false); - } - - /// Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. - /// BotClient - /// Required if chat_id and message_id are not specified. Identifier of the inline message - /// New text of the message, 1-4096 characters after entities parsing - /// Mode for parsing entities in the message text. See formatting options for more details. - /// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode - /// Disables link previews for links in this message - /// A JSON-serialized object for an inline keyboard. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - - public static Message EditMessageText(this BotClient? bot, string inlineMessageId, string text, [Optional] string parseMode, [Optional] MessageEntity[] entities, [Optional] bool? disableWebPagePreview, [Optional] InlineKeyboardMarkup replyMarkup) - { - var args = new EditMessageTextArgs(text) - { - InlineMessageId = inlineMessageId, - ParseMode = parseMode, - Entities = entities, - DisableWebPagePreview = disableWebPagePreview, - ReplyMarkup = replyMarkup - }; - return bot.EditMessageText(args); - } - /// Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. - /// BotClient - /// Required if chat_id and message_id are not specified. Identifier of the inline message - /// New text of the message, 1-4096 characters after entities parsing - /// Mode for parsing entities in the message text. See formatting options for more details. - /// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode - /// Disables link previews for links in this message - /// A JSON-serialized object for an inline keyboard. - /// The cancellation token to cancel operation. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - - public static async Task EditMessageTextAsync(this BotClient? bot, string inlineMessageId, string text, [Optional] string parseMode, [Optional] MessageEntity[] entities, [Optional] bool? disableWebPagePreview, [Optional] InlineKeyboardMarkup replyMarkup, [Optional] CancellationToken cancellationToken) - { - var args = new EditMessageTextArgs(text) - { - InlineMessageId = inlineMessageId, - ParseMode = parseMode, - Entities = entities, - DisableWebPagePreview = disableWebPagePreview, - ReplyMarkup = replyMarkup - }; - return await bot.EditMessageTextAsync(args, cancellationToken).ConfigureAwait(false); - } - - /// Use this method to edit text and game messages. - /// BotClient - /// Parameters. - /// The cancellation token to cancel operation. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// Thrown when T is not Telegram.BotAPI.AvailableTypes.Message or bool. - /// or . On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. - public static async Task EditMessageTextAsync(this BotClient? bot, EditMessageTextArgs args, [Optional] CancellationToken cancellationToken) - { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - if (typeof(T) != typeof(Message) && typeof(T) != typeof(bool) && typeof(T) != typeof(JObject) && typeof(T) != typeof(JsonDocument)) - { - throw new ArgumentException($"{nameof(T)} must be a Telegram.BotAPI.AvailableTypes.Message or bool."); - } - return await bot.RPCA(MethodNames.EditMessageText, args, cancellationToken: cancellationToken).ConfigureAwait(false); - } - - /// Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. - /// BotClient - /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername) - /// Required if inline_message_id is not specified. Identifier of the message to edit - /// New text of the message, 1-4096 characters after entities parsing - /// Mode for parsing entities in the message text. See formatting options for more details. - /// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode - /// Disables link previews for links in this message - /// A JSON-serialized object for an inline keyboard. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// or . On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. - public static T EditMessageText(this BotClient? bot, long chatId, int messageId, string text, [Optional] string parseMode, [Optional] MessageEntity[] entities, [Optional] bool? disableWebPagePreview, [Optional] InlineKeyboardMarkup replyMarkup) - { - var args = new EditMessageTextArgs(text) - { - ChatId = chatId, - MessageId = messageId, - ParseMode = parseMode, - Entities = entities, - DisableWebPagePreview = disableWebPagePreview, - ReplyMarkup = replyMarkup - }; - return bot.EditMessageText(args); - } - /// Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. - /// BotClient - /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername) - /// Required if inline_message_id is not specified. Identifier of the message to edit - /// New text of the message, 1-4096 characters after entities parsing - /// Mode for parsing entities in the message text. See formatting options for more details. - /// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode - /// Disables link previews for links in this message - /// A JSON-serialized object for an inline keyboard. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// or . On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. - public static T EditMessageText(this BotClient? bot, string chatId, int messageId, string text, [Optional] string parseMode, [Optional] MessageEntity[] entities, [Optional] bool? disableWebPagePreview, [Optional] InlineKeyboardMarkup replyMarkup) - { - var args = new EditMessageTextArgs(text) - { - ChatId = chatId, - MessageId = messageId, - ParseMode = parseMode, - Entities = entities, - DisableWebPagePreview = disableWebPagePreview, - ReplyMarkup = replyMarkup - }; - return bot.EditMessageText(args); - } - /// Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. - /// BotClient - /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername) - /// Required if inline_message_id is not specified. Identifier of the message to edit - /// New text of the message, 1-4096 characters after entities parsing - /// Mode for parsing entities in the message text. See formatting options for more details. - /// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode - /// Disables link previews for links in this message - /// A JSON-serialized object for an inline keyboard. - /// The cancellation token to cancel operation. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// or . On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. - public static async Task EditMessageTextAsync(this BotClient? bot, long chatId, int messageId, string text, [Optional] string parseMode, [Optional] MessageEntity[] entities, [Optional] bool? disableWebPagePreview, [Optional] InlineKeyboardMarkup replyMarkup, [Optional] CancellationToken cancellationToken) - { - var args = new EditMessageTextArgs(text) - { - ChatId = chatId, - MessageId = messageId, - ParseMode = parseMode, - Entities = entities, - DisableWebPagePreview = disableWebPagePreview, - ReplyMarkup = replyMarkup - }; - return await bot.EditMessageTextAsync(args, cancellationToken).ConfigureAwait(false); - } - /// Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. - /// BotClient - /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername) - /// Required if inline_message_id is not specified. Identifier of the message to edit - /// New text of the message, 1-4096 characters after entities parsing - /// Mode for parsing entities in the message text. See formatting options for more details. - /// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode - /// Disables link previews for links in this message - /// A JSON-serialized object for an inline keyboard. - /// The cancellation token to cancel operation. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// or . On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. - public static async Task EditMessageTextAsync(this BotClient? bot, string chatId, int messageId, string text, [Optional] string parseMode, [Optional] MessageEntity[] entities, [Optional] bool? disableWebPagePreview, [Optional] InlineKeyboardMarkup replyMarkup, [Optional] CancellationToken cancellationToken) - { - var args = new EditMessageTextArgs(text) - { - ChatId = chatId, - MessageId = messageId, - ParseMode = parseMode, - Entities = entities, - DisableWebPagePreview = disableWebPagePreview, - ReplyMarkup = replyMarkup - }; - return await bot.EditMessageTextAsync(args, cancellationToken).ConfigureAwait(false); - } - - /// Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. - /// BotClient - /// Required if chat_id and message_id are not specified. Identifier of the inline message - /// New text of the message, 1-4096 characters after entities parsing - /// Mode for parsing entities in the message text. See formatting options for more details. - /// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode - /// Disables link previews for links in this message - /// A JSON-serialized object for an inline keyboard. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// or . On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. - public static T EditMessageText(this BotClient? bot, string inlineMessageId, string text, [Optional] string parseMode, [Optional] MessageEntity[] entities, [Optional] bool? disableWebPagePreview, [Optional] InlineKeyboardMarkup replyMarkup) - { - var args = new EditMessageTextArgs(text) - { - InlineMessageId = inlineMessageId, - ParseMode = parseMode, - Entities = entities, - DisableWebPagePreview = disableWebPagePreview, - ReplyMarkup = replyMarkup - }; - return bot.EditMessageText(args); - } - /// Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. - /// BotClient - /// Required if chat_id and message_id are not specified. Identifier of the inline message - /// New text of the message, 1-4096 characters after entities parsing - /// Mode for parsing entities in the message text. See formatting options for more details. - /// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode - /// Disables link previews for links in this message - /// A JSON-serialized object for an inline keyboard. - /// The cancellation token to cancel operation. - /// Thrown when a request to Telegram Bot API got an error response. - /// Thrown when a required parameter is null. - /// or . On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. - public static async Task EditMessageTextAsync(this BotClient? bot, string inlineMessageId, string text, [Optional] string parseMode, [Optional] MessageEntity[] entities, [Optional] bool? disableWebPagePreview, [Optional] InlineKeyboardMarkup replyMarkup, [Optional] CancellationToken cancellationToken) - { - var args = new EditMessageTextArgs(text) - { - InlineMessageId = inlineMessageId, - ParseMode = parseMode, - Entities = entities, - DisableWebPagePreview = disableWebPagePreview, - ReplyMarkup = replyMarkup - }; - return await bot.EditMessageTextAsync(args, cancellationToken).ConfigureAwait(false); - } -} diff --git a/src/Telegram.BotAPI.Examples/.dockerignore b/src/examples/.dockerignore similarity index 100% rename from src/Telegram.BotAPI.Examples/.dockerignore rename to src/examples/.dockerignore diff --git a/src/Telegram.BotAPI.Examples/BotTemplate/BotTemplateSample.csproj b/src/examples/BotTemplate/BotTemplateSample.csproj similarity index 58% rename from src/Telegram.BotAPI.Examples/BotTemplate/BotTemplateSample.csproj rename to src/examples/BotTemplate/BotTemplateSample.csproj index a3c2264a..9fa93a52 100644 --- a/src/Telegram.BotAPI.Examples/BotTemplate/BotTemplateSample.csproj +++ b/src/examples/BotTemplate/BotTemplateSample.csproj @@ -8,7 +8,8 @@ - + + diff --git a/src/examples/BotTemplate/MyBot.cs b/src/examples/BotTemplate/MyBot.cs new file mode 100644 index 00000000..a96254fe --- /dev/null +++ b/src/examples/BotTemplate/MyBot.cs @@ -0,0 +1,88 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System; +using System.Linq; +using System.Text.RegularExpressions; +using Telegram.BotAPI; +using Telegram.BotAPI.AvailableMethods; +using Telegram.BotAPI.AvailableTypes; +using Telegram.BotAPI.Extensions; +using Telegram.BotAPI.GettingUpdates; + +namespace BotTemplateSample +{ + public sealed class MyBot : SimpleTelegramBotBase + { + public static readonly TelegramBotClient Bot = new(""); + public static readonly User Me = Bot.GetMe(); + + public override void OnUpdate(Update update) + { + Console.WriteLine("New update with id: {0}. Type: {1}", update?.UpdateId, update.GetUpdateType()); + base.OnUpdate(update); + } + + protected override void OnMessage(Message message) + { + // Ignore user 777000 (Telegram) + if (message?.From.Id == TelegramConstants.TelegramId) + { + return; + } + + Console.WriteLine("New message from chat id: {0}", message.Chat.Id); + Console.WriteLine("Message Text: {0}", message.Text ?? "|:O"); + + if (message.Chat.Type == ChatType.Private) // Private Chats + { + // Make something + } + else // Group chats + { + + } + // Check if the message contains a command + if (message.Entities.Any(e => e.Type == "bot_command")) + { + // If the command includes a mention, you should verify that it is for your bot, otherwise you will need to ignore the command. + var pattern = string.Format(@"^\/(?\w*)(?:|@{0})(?:$|\s(?.*))", Me.Username); + var match = Regex.Match(message.Text, pattern, RegexOptions.IgnoreCase); + if (match.Success) + { + var command = match.Groups.Values.Single(v => v.Name == "COMMAND").Value; // Get command name + var @params = match.Groups.Values.SingleOrDefault(v => v.Name == "PARAMETERS")?.Value; + + Console.WriteLine("New command: {0}", command); + this.OnCommand(message, command, @params); + } + } + } + + protected override void OnCommand(Message message, string cmd, string parameters) + { + var args = parameters.Split(' ', StringSplitOptions.RemoveEmptyEntries); + Console.WriteLine("Params: {0}", args.Length); + switch (cmd) + { + case "hello": + var hello = string.Format("Hello World, {0}!", message.From.FirstName); + Bot.SendMessage(message.Chat.Id, hello); + break; + } + } + + protected override void OnBotException(BotRequestException exp) + { + Console.WriteLine("New BotException: {0}", exp?.Message); + Console.WriteLine("Error Code: {0}", exp.ErrorCode); + Console.WriteLine(); + } + + protected override void OnException(Exception exp) + { + Console.WriteLine("New Exception: {0}", exp?.Message); + Console.WriteLine(); + } + } +} diff --git a/src/Telegram.BotAPI.Examples/BotTemplate/Program.cs b/src/examples/BotTemplate/Program.cs similarity index 95% rename from src/Telegram.BotAPI.Examples/BotTemplate/Program.cs rename to src/examples/BotTemplate/Program.cs index 6a5cda8f..b1f3e659 100644 --- a/src/Telegram.BotAPI.Examples/BotTemplate/Program.cs +++ b/src/examples/BotTemplate/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System; diff --git a/src/Telegram.BotAPI.Examples/BotTemplate/readme.md b/src/examples/BotTemplate/readme.md similarity index 97% rename from src/Telegram.BotAPI.Examples/BotTemplate/readme.md rename to src/examples/BotTemplate/readme.md index 11ee68c7..07dc3f0d 100644 --- a/src/Telegram.BotAPI.Examples/BotTemplate/readme.md +++ b/src/examples/BotTemplate/readme.md @@ -36,7 +36,7 @@ namespace BotTemplateSample } public sealed class MyBot : TelegramBot { - public static BotClient Bot = new BotClient(""); + public static TelegramBotClient Bot = new TelegramBotClient(""); public static User Me = Bot.GetMe(); public static void StartPolling() { diff --git a/src/Telegram.BotAPI.Examples/Callback query button 01/Callback query button 01.csproj b/src/examples/Callback query button 01/Callback query button 01.csproj similarity index 73% rename from src/Telegram.BotAPI.Examples/Callback query button 01/Callback query button 01.csproj rename to src/examples/Callback query button 01/Callback query button 01.csproj index fce2711a..3ec6a984 100644 --- a/src/Telegram.BotAPI.Examples/Callback query button 01/Callback query button 01.csproj +++ b/src/examples/Callback query button 01/Callback query button 01.csproj @@ -7,7 +7,7 @@ - + diff --git a/src/examples/Callback query button 01/Program.cs b/src/examples/Callback query button 01/Program.cs new file mode 100644 index 00000000..66c800c6 --- /dev/null +++ b/src/examples/Callback query button 01/Program.cs @@ -0,0 +1,65 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System; +using System.Linq; +using Telegram.BotAPI; +using Telegram.BotAPI.AvailableMethods; +using Telegram.BotAPI.AvailableTypes; +using Telegram.BotAPI.GettingUpdates; +using Telegram.BotAPI.UpdatingMessages; + +namespace CallbackQueryButton01 +{ + class Program + { + static void Main() + { + Console.WriteLine("Start!"); + + var bot = new TelegramBotClient(""); + bot.SetMyCommands(new BotCommand("callback", "new callback")); + + // Long Polling + var updates = bot.GetUpdates(); + while (true) + { + if (updates.Length > 0) + { + foreach (var update in updates) + { + if (update.Message != null) + { + var message = update.Message; + if (message.Text.Contains("/callback")) + { + var replyMarkup = new InlineKeyboardMarkup + { + InlineKeyboard = new InlineKeyboardButton[][]{ + new InlineKeyboardButton[] { + new("Callback") { + CallbackData = "callback_data" + } + } + } + }; + bot.SendMessage(message.Chat.Id, "Message with callback data", replyMarkup: replyMarkup); + } + } + else if (update.CallbackQuery != null) + { + var query = update.CallbackQuery; + bot.AnswerCallbackQuery(query.Id, "HELLO"); + bot.EditMessageText(query.Message.Chat.Id, query.Message.MessageId, $"Click!\n\n{query.Data}"); + } + } + updates = updates = bot.GetUpdates(offset: updates.Max(u => u.UpdateId) + 1); + } + else + { + updates = bot.GetUpdates(); + } + } + } + } +} diff --git a/src/Telegram.BotAPI.Examples/Callback query button 01/readme.md b/src/examples/Callback query button 01/readme.md similarity index 97% rename from src/Telegram.BotAPI.Examples/Callback query button 01/readme.md rename to src/examples/Callback query button 01/readme.md index bd9c7b8b..a2820c31 100644 --- a/src/Telegram.BotAPI.Examples/Callback query button 01/readme.md +++ b/src/examples/Callback query button 01/readme.md @@ -26,7 +26,7 @@ namespace CallbackQueryButton01 static void Main() { Console.WriteLine("Start!"); - var bot = new BotClient(""); + var bot = new TelegramBotClient(""); bot.SetMyCommands(new BotCommand("callback", "new callback")); var updates = bot.GetUpdates(); while (true) diff --git a/src/Telegram.BotAPI.Examples/Examples.sln b/src/examples/Examples.sln similarity index 98% rename from src/Telegram.BotAPI.Examples/Examples.sln rename to src/examples/Examples.sln index 7299e50b..14100b81 100644 --- a/src/Telegram.BotAPI.Examples/Examples.sln +++ b/src/examples/Examples.sln @@ -21,7 +21,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Examples", "Examples", "{7A EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Library", "Library", "{ADD476C3-7C77-421E-8A5F-F5DC41886727}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Telegram.BotAPI", "..\Telegram.BotAPI\Telegram.BotAPI.csproj", "{7885DD73-1782-4D0E-826E-C60C27C7648D}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Telegram.BotAPI", "..\library\Telegram.BotAPI\Telegram.BotAPI.csproj", "{7885DD73-1782-4D0E-826E-C60C27C7648D}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HelloBotNET.AppService", "HelloBotNET.AppService\HelloBotNET.AppService.csproj", "{40F07F65-6DF5-48D2-9C11-0D970BFA31A0}" EndProject diff --git a/src/Telegram.BotAPI.Examples/Hello World/Hello World.csproj b/src/examples/Hello World/Hello World.csproj similarity index 73% rename from src/Telegram.BotAPI.Examples/Hello World/Hello World.csproj rename to src/examples/Hello World/Hello World.csproj index 5be3b9f4..1734569b 100644 --- a/src/Telegram.BotAPI.Examples/Hello World/Hello World.csproj +++ b/src/examples/Hello World/Hello World.csproj @@ -7,7 +7,7 @@ - + diff --git a/src/Telegram.BotAPI.Examples/Hello World/Program.cs b/src/examples/Hello World/Program.cs similarity index 85% rename from src/Telegram.BotAPI.Examples/Hello World/Program.cs rename to src/examples/Hello World/Program.cs index c96ebcda..8d3c446e 100644 --- a/src/Telegram.BotAPI.Examples/Hello World/Program.cs +++ b/src/examples/Hello World/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System; @@ -15,7 +15,7 @@ static void Main() { Console.WriteLine("Start!"); - var bot = new BotClient(""); + var bot = new TelegramBotClient(""); // Long POlling var updates = bot.GetUpdates(); @@ -25,7 +25,7 @@ static void Main() { foreach (var update in updates) { - if (update.Type == UpdateType.Message) + if (update.Message != null) { var message = update.Message; //bot.SendChatAction(message.Chat.Id, ChatAction.Typing); diff --git a/src/Telegram.BotAPI.Examples/Hello World/readme.md b/src/examples/Hello World/readme.md similarity index 95% rename from src/Telegram.BotAPI.Examples/Hello World/readme.md rename to src/examples/Hello World/readme.md index 62293625..8675ddb4 100644 --- a/src/Telegram.BotAPI.Examples/Hello World/readme.md +++ b/src/examples/Hello World/readme.md @@ -23,7 +23,7 @@ namespace HelloWorld static void Main() { Console.WriteLine("Start!"); - var bot = new BotClient(""); + var bot = new TelegramBotClient(""); var updates = bot.GetUpdates(); while (true) { diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/HelloBotNET.AppService.csproj b/src/examples/HelloBotNET.AppService/HelloBotNET.AppService.csproj similarity index 71% rename from src/Telegram.BotAPI.Examples/HelloBotNET.AppService/HelloBotNET.AppService.csproj rename to src/examples/HelloBotNET.AppService/HelloBotNET.AppService.csproj index f36a7c26..a649adcc 100644 --- a/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/HelloBotNET.AppService.csproj +++ b/src/examples/HelloBotNET.AppService/HelloBotNET.AppService.csproj @@ -1,7 +1,7 @@ - net6.0 + net8.0 enable enable dotnet-HelloBotNET-51BA3BFF-ACF3-4D96-B57C-8CFDD2B87F9E @@ -14,6 +14,7 @@ - + + diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Program.cs b/src/examples/HelloBotNET.AppService/Program.cs similarity index 71% rename from src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Program.cs rename to src/examples/HelloBotNET.AppService/Program.cs index eff1eeaf..37ccfe4f 100644 --- a/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Program.cs +++ b/src/examples/HelloBotNET.AppService/Program.cs @@ -1,17 +1,15 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using HelloBotNET.AppService; using HelloBotNET.AppService.Services; +using Telegram.BotAPI; IHost host = Host.CreateDefaultBuilder(args) .ConfigureServices((context, services) => { - // Add bot properties service. - services.AddSingleton(); - // Add bot service. - services.AddScoped(); + services.AddSingleton(); // Add long polling service services.AddHostedService(); diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Properties/launchSettings.json b/src/examples/HelloBotNET.AppService/Properties/launchSettings.json similarity index 100% rename from src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Properties/launchSettings.json rename to src/examples/HelloBotNET.AppService/Properties/launchSettings.json diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Properties/serviceDependencies.json b/src/examples/HelloBotNET.AppService/Properties/serviceDependencies.json similarity index 100% rename from src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Properties/serviceDependencies.json rename to src/examples/HelloBotNET.AppService/Properties/serviceDependencies.json diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Properties/serviceDependencies.local.json b/src/examples/HelloBotNET.AppService/Properties/serviceDependencies.local.json similarity index 100% rename from src/Telegram.BotAPI.Examples/HelloBotNET.AppService/Properties/serviceDependencies.local.json rename to src/examples/HelloBotNET.AppService/Properties/serviceDependencies.local.json diff --git a/src/examples/HelloBotNET.AppService/Services/HelloBot.CommandHandler.cs b/src/examples/HelloBotNET.AppService/Services/HelloBot.CommandHandler.cs new file mode 100644 index 00000000..b64d018c --- /dev/null +++ b/src/examples/HelloBotNET.AppService/Services/HelloBot.CommandHandler.cs @@ -0,0 +1,45 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Telegram.BotAPI.AvailableMethods; +using Telegram.BotAPI.AvailableTypes; +using Telegram.BotAPI.Extensions; + +namespace HelloBotNET.AppService.Services; + +/// +/// It contains the main functionality of the telegram bot.
+/// The application creates a new instance of this class to process each update received. +///
+public partial class HelloBot : SimpleTelegramBotBase +{ + protected override void OnCommand(Message message, string commandName, string commandParameters) + { + var args = commandParameters.Split(' '); +#if DEBUG + this.logger.LogInformation("Params: {ArgsLenght}", args.Length); +#endif + + switch (commandName) + { + case "hello": // Reply to /hello command + var hello = string.Format("Hello World, {0}!", message.From!.FirstName); + this.Client.SendMessage(message.Chat.Id, hello); + break; + /* + case "command1": + // ... + break; + case "command2": + // ... + break; + */ + default: + if (message.Chat.Type == ChatType.Private) + { + this.Client.SendMessage(message.Chat.Id, "Unrecognized command."); + } + break; + } + } +} diff --git a/src/examples/HelloBotNET.AppService/Services/HelloBot.ErrorHandler.cs b/src/examples/HelloBotNET.AppService/Services/HelloBot.ErrorHandler.cs new file mode 100644 index 00000000..21984139 --- /dev/null +++ b/src/examples/HelloBotNET.AppService/Services/HelloBot.ErrorHandler.cs @@ -0,0 +1,24 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Telegram.BotAPI; +using Telegram.BotAPI.Extensions; + +namespace HelloBotNET.AppService.Services; + +/// +/// It contains the main functionality of the telegram bot.
+/// The application creates a new instance of this class to process each update received. +///
+public partial class HelloBot : SimpleTelegramBotBase +{ + protected override void OnBotException(BotRequestException exp) + { + this.logger.LogError("BotRequestException: {Message}", exp.Message); + } + + protected override void OnException(Exception exp) + { + this.logger.LogError("Exception: {Message}", exp.Message); + } +} diff --git a/src/examples/HelloBotNET.AppService/Services/HelloBot.MessageHandler.cs b/src/examples/HelloBotNET.AppService/Services/HelloBot.MessageHandler.cs new file mode 100644 index 00000000..fefb1587 --- /dev/null +++ b/src/examples/HelloBotNET.AppService/Services/HelloBot.MessageHandler.cs @@ -0,0 +1,33 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Telegram.BotAPI; +using Telegram.BotAPI.AvailableTypes; +using Telegram.BotAPI.Extensions; + +namespace HelloBotNET.AppService.Services; + +/// +/// It contains the main functionality of the telegram bot.
+/// The application creates a new instance of this class to process each update received. +///
+public partial class HelloBot : SimpleTelegramBotBase +{ + protected override void OnMessage(Message message) + { + // Ignore user 777000 (Telegram) + if (message!.From?.Id == TelegramConstants.TelegramId) + { + return; + } + + var hasText = !string.IsNullOrEmpty(message.Text); // True if message has text; + +#if DEBUG + this.logger.LogInformation("New message from chat id: {ChatId}", message!.Chat.Id); + this.logger.LogInformation("Message: {MessageContent}", hasText ? message.Text : "No text"); +#endif + + base.OnMessage(message); + } +} diff --git a/src/examples/HelloBotNET.AppService/Services/HelloBot.UpdateHandler.cs b/src/examples/HelloBotNET.AppService/Services/HelloBot.UpdateHandler.cs new file mode 100644 index 00000000..e9e9a2d3 --- /dev/null +++ b/src/examples/HelloBotNET.AppService/Services/HelloBot.UpdateHandler.cs @@ -0,0 +1,23 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Telegram.BotAPI.Extensions; +using Telegram.BotAPI.GettingUpdates; + +namespace HelloBotNET.AppService.Services; + +/// +/// It contains the main functionality of the telegram bot.
+/// The application creates a new instance of this class to process each update received. +///
+public partial class HelloBot : SimpleTelegramBotBase +{ + public override void OnUpdate(Update update) + { +#if DEBUG + this.logger.LogInformation("New update with id: {UpdateId}. Type: {UpdateType}", update.UpdateId, update.GetUpdateType()); +#endif + + base.OnUpdate(update); + } +} diff --git a/src/examples/HelloBotNET.AppService/Services/HelloBot.cs b/src/examples/HelloBotNET.AppService/Services/HelloBot.cs new file mode 100644 index 00000000..c7e848e4 --- /dev/null +++ b/src/examples/HelloBotNET.AppService/Services/HelloBot.cs @@ -0,0 +1,30 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Telegram.BotAPI; +using Telegram.BotAPI.AvailableMethods; +using Telegram.BotAPI.Extensions; + +namespace HelloBotNET.AppService.Services; + +/// +/// It contains the main functionality of the telegram bot.
+/// The application creates a new instance of this class to process each update received. +///
+public partial class HelloBot : SimpleTelegramBotBase +{ + private readonly ILogger logger; + public ITelegramBotClient Client { get; } + + public HelloBot(ILogger logger, IConfiguration configuration) + { + this.logger = logger; + + var botToken = configuration.GetValue("Telegram:BotToken"); + this.Client = new TelegramBotClient(botToken); + + var myUsername = this.Client.GetMe().Username!; + // This will provide a better command filtering. + this.SetCommandExtractor(myUsername, true); + } +} diff --git a/src/examples/HelloBotNET.AppService/Worker.cs b/src/examples/HelloBotNET.AppService/Worker.cs new file mode 100644 index 00000000..ad9bb4d6 --- /dev/null +++ b/src/examples/HelloBotNET.AppService/Worker.cs @@ -0,0 +1,49 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using HelloBotNET.AppService.Services; +using Telegram.BotAPI; +using Telegram.BotAPI.GettingUpdates; + +namespace HelloBotNET.AppService +{ + public class Worker(ILogger logger, HelloBot bot) : BackgroundService + { + private readonly ILogger logger = logger; + private readonly HelloBot bot = bot; + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + this.logger.LogInformation("Worker running at: {Time}", DateTimeOffset.Now); + + var client = this.bot.Client; + + // Long Polling + var updates = await client.GetUpdatesAsync(cancellationToken: stoppingToken).ConfigureAwait(false); + while (!stoppingToken.IsCancellationRequested) + { + if (updates.Length != 0) + { + Parallel.ForEach(updates, this.ProcessUpdate); + + updates = await client.GetUpdatesAsync(updates[^1].UpdateId + 1, cancellationToken: stoppingToken).ConfigureAwait(false); + } + else + { + updates = await client.GetUpdatesAsync(cancellationToken: stoppingToken).ConfigureAwait(false); + } + } + } + + private void ProcessUpdate(Update update) + { + this.bot.OnUpdate(update); + } + + public override Task StopAsync(CancellationToken cancellationToken) + { + this.logger.LogInformation("Worker stopping at: {Time}", DateTimeOffset.Now); + return base.StopAsync(cancellationToken); + } + } +} diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/appsettings.Development.json b/src/examples/HelloBotNET.AppService/appsettings.Development.json similarity index 100% rename from src/Telegram.BotAPI.Examples/HelloBotNET.AppService/appsettings.Development.json rename to src/examples/HelloBotNET.AppService/appsettings.Development.json diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/appsettings.json b/src/examples/HelloBotNET.AppService/appsettings.json similarity index 100% rename from src/Telegram.BotAPI.Examples/HelloBotNET.AppService/appsettings.json rename to src/examples/HelloBotNET.AppService/appsettings.json diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.AppService/readme.md b/src/examples/HelloBotNET.AppService/readme.md similarity index 100% rename from src/Telegram.BotAPI.Examples/HelloBotNET.AppService/readme.md rename to src/examples/HelloBotNET.AppService/readme.md diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Controllers/BotController.cs b/src/examples/HelloBotNET.Webhook/Controllers/BotController.cs similarity index 64% rename from src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Controllers/BotController.cs rename to src/examples/HelloBotNET.Webhook/Controllers/BotController.cs index 125811ea..e1a78176 100644 --- a/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Controllers/BotController.cs +++ b/src/examples/HelloBotNET.Webhook/Controllers/BotController.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using HelloBotNET.Webhook.Services; @@ -11,35 +11,35 @@ namespace HelloBotNET.Webhook.Controllers [Route("[controller]")] public class BotController : ControllerBase { - private readonly IConfiguration _configuration; - private readonly ILogger _logger; - private readonly HelloBot _bot; + private readonly IConfiguration configuration; + private readonly ILogger logger; + private readonly HelloBot bot; public BotController(ILogger logger, IConfiguration configuration, HelloBot bot) : base() { - this._logger = logger; - this._configuration = configuration; - this._bot = bot; + this.logger = logger; + this.configuration = configuration; + this.bot = bot; } [HttpPost] public async Task PostAsync([FromHeader(Name = "X-Telegram-Bot-Api-Secret-Token")] string webhookToken, [FromBody] Update update, CancellationToken cancellationToken) { - if (this._configuration["Telegram:WebhookToken"] != webhookToken) + if (this.configuration["Telegram:WebhookToken"] != webhookToken) { #if DEBUG - this._logger.LogWarning("Failed access"); + this.logger.LogWarning("Failed access"); #endif this.Unauthorized(); } if (update == default) { #if DEBUG - this._logger.LogWarning("Invalid update detected"); + this.logger.LogWarning("Invalid update detected"); #endif return this.BadRequest(); } - this._bot.OnUpdate(update); + this.bot.OnUpdate(update); return await Task.FromResult(this.Ok()); } diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Extensions/ApplicationBuilderExtensions.cs b/src/examples/HelloBotNET.Webhook/Extensions/ApplicationBuilderExtensions.cs similarity index 81% rename from src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Extensions/ApplicationBuilderExtensions.cs rename to src/examples/HelloBotNET.Webhook/Extensions/ApplicationBuilderExtensions.cs index 3c548e3f..04d8f54f 100644 --- a/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Extensions/ApplicationBuilderExtensions.cs +++ b/src/examples/HelloBotNET.Webhook/Extensions/ApplicationBuilderExtensions.cs @@ -1,9 +1,10 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Telegram.BotAPI.AvailableTypes; using Telegram.BotAPI.AvailableMethods; using Telegram.BotAPI.GettingUpdates; +using HelloBotNET.Webhook.Services; namespace HelloBotNET.Webhook.Extensions; @@ -26,22 +27,22 @@ public static IApplicationBuilder UseTelegramWebhook(this IApplicationBuilder ap } var configuration = app.ApplicationServices.GetRequiredService(); - var bot = app.ApplicationServices.GetRequiredService(); + var bot = app.ApplicationServices.GetRequiredService(); var webhookToken = configuration["Telegram:WebhookToken"]; // ENV: Telegram__WebhookToken, JSON: "Telegram:WebhookToken" var webhookUrl = configuration["Telegram:WebhookUrl"]; // ENV: Telegram__WebhookUrl, JSON: "Telegram:WebhookUrl" // Delete my old commands - bot.Api.DeleteMyCommands(); + bot.Client.DeleteMyCommands(); // Set my commands - bot.Api.SetMyCommands( + bot.Client.SetMyCommands( new BotCommand("hello", "Hello world!")); // Delete webhook - bot.Api.DeleteWebhook(); + bot.Client.DeleteWebhook(); // Set webhook - bot.Api.SetWebhook(webhookUrl + "/bot", secretToken: webhookToken); + bot.Client.SetWebhook(webhookUrl + "/bot", secretToken: webhookToken); return app; } diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/HelloBotNET.Webhook.csproj b/src/examples/HelloBotNET.Webhook/HelloBotNET.Webhook.csproj similarity index 64% rename from src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/HelloBotNET.Webhook.csproj rename to src/examples/HelloBotNET.Webhook/HelloBotNET.Webhook.csproj index 892a3f34..d548107f 100644 --- a/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/HelloBotNET.Webhook.csproj +++ b/src/examples/HelloBotNET.Webhook/HelloBotNET.Webhook.csproj @@ -9,7 +9,8 @@ - + + diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Program.cs b/src/examples/HelloBotNET.Webhook/Program.cs similarity index 70% rename from src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Program.cs rename to src/examples/HelloBotNET.Webhook/Program.cs index 9ea3ce7a..df322830 100644 --- a/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Program.cs +++ b/src/examples/HelloBotNET.Webhook/Program.cs @@ -1,18 +1,14 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. -using HelloBotNET.Webhook; using HelloBotNET.Webhook.Extensions; using HelloBotNET.Webhook.Services; var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); -// Add bot properties service. -builder.Services.AddSingleton(); - // Add bot service. -builder.Services.AddScoped(); +builder.Services.AddSingleton(); var app = builder.Build(); diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Properties/launchSettings.json b/src/examples/HelloBotNET.Webhook/Properties/launchSettings.json similarity index 100% rename from src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Properties/launchSettings.json rename to src/examples/HelloBotNET.Webhook/Properties/launchSettings.json diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Services/HelloBot.CommandHandler.cs b/src/examples/HelloBotNET.Webhook/Services/HelloBot.CommandHandler.cs similarity index 76% rename from src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Services/HelloBot.CommandHandler.cs rename to src/examples/HelloBotNET.Webhook/Services/HelloBot.CommandHandler.cs index f54e6932..a4464345 100644 --- a/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Services/HelloBot.CommandHandler.cs +++ b/src/examples/HelloBotNET.Webhook/Services/HelloBot.CommandHandler.cs @@ -1,9 +1,9 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. -using Telegram.BotAPI; using Telegram.BotAPI.AvailableMethods; using Telegram.BotAPI.AvailableTypes; +using Telegram.BotAPI.Extensions; namespace HelloBotNET.Webhook.Services { @@ -11,20 +11,20 @@ namespace HelloBotNET.Webhook.Services /// It contains the main functionality of the telegram bot.
/// The application creates a new instance of this class to process each update received. /// - public partial class HelloBot : TelegramBotBase + public partial class HelloBot : SimpleTelegramBotBase { protected override void OnCommand(Message message, string commandName, string commandParameters) { var args = commandParameters.Split(' '); #if DEBUG - this._logger.LogInformation("Params: {0}", args.Length); + this.logger.LogInformation("Params: {ArgsLenght}", args.Length); #endif switch (commandName) { case "hello": // Reply to /hello command var hello = string.Format("Hello World, {0}!", message.From!.FirstName); - this.Api.SendMessage(message.Chat.Id, hello); + this.Client.SendMessage(message.Chat.Id, hello); break; /* case "command1": @@ -37,7 +37,7 @@ protected override void OnCommand(Message message, string commandName, string co default: if (message.Chat.Type == ChatType.Private) { - this.Api.SendMessage(message.Chat.Id, "Unrecognized command."); + this.Client.SendMessage(message.Chat.Id, "Unrecognized command."); } break; } diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Services/HelloBot.ErrorHandler.cs b/src/examples/HelloBotNET.Webhook/Services/HelloBot.ErrorHandler.cs similarity index 65% rename from src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Services/HelloBot.ErrorHandler.cs rename to src/examples/HelloBotNET.Webhook/Services/HelloBot.ErrorHandler.cs index 315e517f..45a9e445 100644 --- a/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Services/HelloBot.ErrorHandler.cs +++ b/src/examples/HelloBotNET.Webhook/Services/HelloBot.ErrorHandler.cs @@ -1,7 +1,8 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Telegram.BotAPI; +using Telegram.BotAPI.Extensions; namespace HelloBotNET.Webhook.Services { @@ -9,16 +10,16 @@ namespace HelloBotNET.Webhook.Services /// It contains the main functionality of the telegram bot.
/// The application creates a new instance of this class to process each update received. /// - public partial class HelloBot : TelegramBotBase + public partial class HelloBot : SimpleTelegramBotBase { protected override void OnBotException(BotRequestException exp) { - this._logger.LogError("BotRequestException: {Message}", exp.Message); + this.logger.LogError("BotRequestException: {Message}", exp.Message); } protected override void OnException(Exception exp) { - this._logger.LogError("Exception: {Message}", exp.Message); + this.logger.LogError("Exception: {Message}", exp.Message); } } } diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Services/HelloBot.MessageHandler.cs b/src/examples/HelloBotNET.Webhook/Services/HelloBot.MessageHandler.cs similarity index 63% rename from src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Services/HelloBot.MessageHandler.cs rename to src/examples/HelloBotNET.Webhook/Services/HelloBot.MessageHandler.cs index 2f6a6c85..daa2bb79 100644 --- a/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Services/HelloBot.MessageHandler.cs +++ b/src/examples/HelloBotNET.Webhook/Services/HelloBot.MessageHandler.cs @@ -1,8 +1,9 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Telegram.BotAPI; using Telegram.BotAPI.AvailableTypes; +using Telegram.BotAPI.Extensions; namespace HelloBotNET.Webhook.Services { @@ -10,12 +11,12 @@ namespace HelloBotNET.Webhook.Services /// It contains the main functionality of the telegram bot.
/// The application creates a new instance of this class to process each update received. /// - public partial class HelloBot : TelegramBotBase + public partial class HelloBot : SimpleTelegramBotBase { protected override void OnMessage(Message message) { // Ignore user 777000 (Telegram) - if (message!.From?.Id == TelegramConstants.TelegramId) + if (message.From?.Id == TelegramConstants.TelegramId) { return; } @@ -23,8 +24,8 @@ protected override void OnMessage(Message message) var hasText = !string.IsNullOrEmpty(message.Text); // True if message has text; #if DEBUG - this._logger.LogInformation("New message from chat id: {ChatId}", message!.Chat.Id); - this._logger.LogInformation("Message: {MessageContent}", hasText ? message.Text : "No text"); + this.logger.LogInformation("New message from chat id: {ChatId}", message!.Chat.Id); + this.logger.LogInformation("Message: {MessageContent}", hasText ? message.Text : "No text"); #endif base.OnMessage(message); diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Services/HelloBot.UpdateHandler.cs b/src/examples/HelloBotNET.Webhook/Services/HelloBot.UpdateHandler.cs similarity index 65% rename from src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Services/HelloBot.UpdateHandler.cs rename to src/examples/HelloBotNET.Webhook/Services/HelloBot.UpdateHandler.cs index 3774925f..ecdf0ced 100644 --- a/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/Services/HelloBot.UpdateHandler.cs +++ b/src/examples/HelloBotNET.Webhook/Services/HelloBot.UpdateHandler.cs @@ -1,7 +1,8 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Telegram.BotAPI; +using Telegram.BotAPI.Extensions; using Telegram.BotAPI.GettingUpdates; namespace HelloBotNET.Webhook.Services @@ -10,12 +11,12 @@ namespace HelloBotNET.Webhook.Services /// It contains the main functionality of the telegram bot.
/// The application creates a new instance of this class to process each update received. /// - public partial class HelloBot : TelegramBotBase + public partial class HelloBot : SimpleTelegramBotBase { public override void OnUpdate(Update update) { #if DEBUG - this._logger.LogInformation("New update with id: {0}. Type: {1}", update?.UpdateId, update?.Type.ToString("F")); + this.logger.LogInformation("New update with id: {UpdateId}. Type: {UpdateType}", update.UpdateId, update.GetUpdateType()); #endif base.OnUpdate(update); diff --git a/src/examples/HelloBotNET.Webhook/Services/HelloBot.cs b/src/examples/HelloBotNET.Webhook/Services/HelloBot.cs new file mode 100644 index 00000000..9dc07d32 --- /dev/null +++ b/src/examples/HelloBotNET.Webhook/Services/HelloBot.cs @@ -0,0 +1,31 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Telegram.BotAPI; +using Telegram.BotAPI.AvailableMethods; +using Telegram.BotAPI.Extensions; + +namespace HelloBotNET.Webhook.Services +{ + /// + /// It contains the main functionality of the telegram bot.
+ /// The application creates a new instance of this class to process each update received. + ///
+ public partial class HelloBot : SimpleTelegramBotBase + { + private readonly ILogger logger; + public ITelegramBotClient Client { get; } + + public HelloBot(ILogger logger, IConfiguration configuration) + { + this.logger = logger; + + var botToken = configuration.GetValue("Telegram:BotToken"); + this.Client = new TelegramBotClient(botToken); + + var myUsername = this.Client.GetMe().Username!; + // This will provide a better command filtering. + this.SetCommandExtractor(myUsername, true); + } + } +} diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/appsettings.Development.json b/src/examples/HelloBotNET.Webhook/appsettings.Development.json similarity index 100% rename from src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/appsettings.Development.json rename to src/examples/HelloBotNET.Webhook/appsettings.Development.json diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/appsettings.json b/src/examples/HelloBotNET.Webhook/appsettings.json similarity index 100% rename from src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/appsettings.json rename to src/examples/HelloBotNET.Webhook/appsettings.json diff --git a/src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/readme.md b/src/examples/HelloBotNET.Webhook/readme.md similarity index 100% rename from src/Telegram.BotAPI.Examples/HelloBotNET.Webhook/readme.md rename to src/examples/HelloBotNET.Webhook/readme.md diff --git a/src/Telegram.BotAPI.Examples/Poll Quiz 01/Poll Quiz 01.csproj b/src/examples/Poll Quiz 01/Poll Quiz 01.csproj similarity index 73% rename from src/Telegram.BotAPI.Examples/Poll Quiz 01/Poll Quiz 01.csproj rename to src/examples/Poll Quiz 01/Poll Quiz 01.csproj index 4a49d2c2..96eaabd6 100644 --- a/src/Telegram.BotAPI.Examples/Poll Quiz 01/Poll Quiz 01.csproj +++ b/src/examples/Poll Quiz 01/Poll Quiz 01.csproj @@ -7,7 +7,7 @@ - + diff --git a/src/Telegram.BotAPI.Examples/Poll Quiz 01/Program.cs b/src/examples/Poll Quiz 01/Program.cs similarity index 61% rename from src/Telegram.BotAPI.Examples/Poll Quiz 01/Program.cs rename to src/examples/Poll Quiz 01/Program.cs index 94cf8c56..36c24076 100644 --- a/src/Telegram.BotAPI.Examples/Poll Quiz 01/Program.cs +++ b/src/examples/Poll Quiz 01/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System; @@ -16,7 +16,7 @@ static void Main() { Console.WriteLine("Start!"); - var bot = new BotClient(""); + var bot = new TelegramBotClient(""); bot.SetMyCommands(new BotCommand("quiz", "New quiz")); // Long Polling @@ -27,22 +27,20 @@ static void Main() { foreach (var update in updates) { - switch (update.Type) + if (update.Message != null) { - case UpdateType.Message: - if (update.Message.Text.Contains("/quiz")) - { - bot.SendPoll( - new SendPollArgs( - update.Message.Chat.Id, - "¿5 + 5?", - new string[] { "56", "7", "10", "-4" }) - { - Type = "quiz", - CorrectOptionId = 2 - }); - } - break; + if (update.Message.Text.Contains("/quiz")) + { + bot.SendPoll( + new SendPollArgs( + update.Message.Chat.Id, + "¿5 + 5?", + new string[] { "56", "7", "10", "-4" }) + { + Type = "quiz", + CorrectOptionId = 2 + }); + } } } updates = bot.GetUpdates(offset: updates.Max(u => u.UpdateId) + 1); diff --git a/src/Telegram.BotAPI.Examples/Poll Quiz 01/readme.md b/src/examples/Poll Quiz 01/readme.md similarity index 96% rename from src/Telegram.BotAPI.Examples/Poll Quiz 01/readme.md rename to src/examples/Poll Quiz 01/readme.md index 76c2d355..3742a130 100644 --- a/src/Telegram.BotAPI.Examples/Poll Quiz 01/readme.md +++ b/src/examples/Poll Quiz 01/readme.md @@ -24,7 +24,7 @@ namespace Poll_Quiz_01 static void Main() { Console.WriteLine("Start!"); - var bot = new BotClient(""); + var bot = new TelegramBotClient(""); bot.SetMyCommands(new BotCommand("quiz", "New quiz")); var updates = bot.GetUpdates(); while (true) diff --git a/src/examples/ReplyKeyboardMarkup 01/Program.cs b/src/examples/ReplyKeyboardMarkup 01/Program.cs new file mode 100644 index 00000000..522c0707 --- /dev/null +++ b/src/examples/ReplyKeyboardMarkup 01/Program.cs @@ -0,0 +1,55 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System; +using System.Linq; +using Telegram.BotAPI; +using Telegram.BotAPI.AvailableMethods; +using Telegram.BotAPI.AvailableTypes; +using Telegram.BotAPI.GettingUpdates; + +Console.WriteLine("Start!"); + +var client = new TelegramBotClient(""); +client.SetMyCommands(new BotCommand("reply", "ReplyMarkup"), new BotCommand("del", "Delete")); + +// Long Polling +var updates = client.GetUpdates(); +while (true) +{ + if (updates.Length > 0) + { + foreach (var update in updates) + { + if (update.Message != null) + { + if (update.Message.Text.Contains("/reply")) + { + var keyboard = new ReplyKeyboardMarkup + { + Keyboard = new KeyboardButton[][] { + new KeyboardButton[] { + new("Button 1"), //column 1 row 1 + new("Button 2") //column 1 row 2 + },// column 1 + new KeyboardButton[] { + new("Button 3") //col 2 row 1 + } // column 2 + }, + ResizeKeyboard = true + }; ; + client.SendMessage(update.Message.Chat.Id, "new keyboard", replyMarkup: keyboard); + } + if (update.Message.Text.Contains("/del")) + { + client.SendMessage(update.Message.Chat.Id, "remove reply keyboard", replyMarkup: new ReplyKeyboardRemove()); + } + } + } + updates = client.GetUpdates(offset: updates.Max(u => u.UpdateId) + 1); + } + else + { + updates = client.GetUpdates(); + } +} diff --git a/src/Telegram.BotAPI.Examples/ReplyKeyboardMarkup 01/ReplyKeyboardMarkup 01.csproj b/src/examples/ReplyKeyboardMarkup 01/ReplyKeyboardMarkup 01.csproj similarity index 74% rename from src/Telegram.BotAPI.Examples/ReplyKeyboardMarkup 01/ReplyKeyboardMarkup 01.csproj rename to src/examples/ReplyKeyboardMarkup 01/ReplyKeyboardMarkup 01.csproj index 6cb449a2..59e823e8 100644 --- a/src/Telegram.BotAPI.Examples/ReplyKeyboardMarkup 01/ReplyKeyboardMarkup 01.csproj +++ b/src/examples/ReplyKeyboardMarkup 01/ReplyKeyboardMarkup 01.csproj @@ -7,7 +7,7 @@ - + diff --git a/src/Telegram.BotAPI.Examples/ReplyKeyboardMarkup 01/readme.md b/src/examples/ReplyKeyboardMarkup 01/readme.md similarity index 97% rename from src/Telegram.BotAPI.Examples/ReplyKeyboardMarkup 01/readme.md rename to src/examples/ReplyKeyboardMarkup 01/readme.md index b02e5d20..540192e0 100644 --- a/src/Telegram.BotAPI.Examples/ReplyKeyboardMarkup 01/readme.md +++ b/src/examples/ReplyKeyboardMarkup 01/readme.md @@ -24,7 +24,7 @@ namespace ReplyKeyboardMarkup_01 static void Main() { Console.WriteLine("Start!"); - var bot = new BotClient(""); + var bot = new TelegramBotClient(""); var updates = bot.GetUpdates(); bot.SetMyCommands(new BotCommand("reply", "ReplyMarkup"), new BotCommand("del", "Delete")); while (true) diff --git a/src/Telegram.BotAPI.Examples/Telegram Calendar/Calendar.cs b/src/examples/Telegram Calendar/Calendar.cs similarity index 63% rename from src/Telegram.BotAPI.Examples/Telegram Calendar/Calendar.cs rename to src/examples/Telegram Calendar/Calendar.cs index 67dfe9d6..a3b44783 100644 --- a/src/Telegram.BotAPI.Examples/Telegram Calendar/Calendar.cs +++ b/src/examples/Telegram Calendar/Calendar.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System; @@ -12,9 +12,12 @@ public static IKB[][] New(DateTime dateTime) { var year = dateTime.Year; var keyboard = new IKB[6][]; - keyboard[0] = new IKB[1]{ - IKB.SetCallbackData($"{year}", $"Year {year}") - }; + keyboard[0] = [ + new($"{year}") + { + CallbackData = $"Year {year}" + } + ]; for (int i = 1, n = 0; i < 5; i++) { keyboard[i] = new IKB[3]; @@ -27,10 +30,10 @@ public static IKB[][] New(DateTime dateTime) }; } } - keyboard[5] = new IKB[2]{ - IKB.SetCallbackData($"{year - 1}",$"year {year - 1}"), - IKB.SetCallbackData($"{year + 1}",$"year {year + 1}") - }; + keyboard[5] = [ + new($"{year - 1}") { CallbackData = $"year {year - 1}"}, + new($"{year + 1}") { CallbackData = $"year {year + 1}"} + ]; return keyboard; } @@ -40,13 +43,13 @@ public static IKB[][] New(Month mon) var pos = 0; calendar[0] = new IKB[1] { - IKB.SetCallbackData($"{mon.Name} {mon.Year}", $"year {mon.Year}") + new IKB($"{mon.Name} {mon.Year}") { CallbackData = $"year {mon.Year}"} }; var days = new[] { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; calendar[1] = new IKB[7]; for (int i = 0; i < 7; i++) { - calendar[1][i] = IKB.SetCallbackData(days[i], $"{((DayOfWeek)i)}"); + calendar[1][i] = new IKB(days[i]) { CallbackData = $"{((DayOfWeek)i)}" }; } for (int i = 2; i < mon.Weeks + 2; i++) { @@ -57,17 +60,17 @@ public static IKB[][] New(Month mon) { if ((int)mon.Days[pos].Name == j) { - calendar[i][j] = IKB.SetCallbackData($"{mon.Days[pos].Number}", $"{mon.Days[pos].Name}, {mon.Name} {mon.Days[pos].Number}"); + calendar[i][j] = new IKB($"{mon.Days[pos].Number}") { CallbackData = $"{mon.Days[pos].Name}, {mon.Name} {mon.Days[pos].Number}" }; pos++; } else { - calendar[i][j] = IKB.SetCallbackData("*", "Empty day"); + calendar[i][j] = new IKB("*") { CallbackData = "Empty day" }; } } else { - calendar[i][j] = IKB.SetCallbackData("*", "Empty day"); + calendar[i][j] = new IKB("*") { CallbackData = "Empty day" }; } } } @@ -76,15 +79,15 @@ public static IKB[][] New(Month mon) var nextmonth = mon.Name == MonthName.December ? MonthName.January : mon.Name + 1; var previousyear = previousmonth == MonthName.December ? mon.Year - 1 : mon.Year; var nextyear = nextmonth == MonthName.January ? mon.Year + 1 : mon.Year; - calendar[^1][0] = IKB.SetCallbackData($"{previousmonth}", $"month {previousyear} {((ushort)previousmonth)}"); - calendar[^1][1] = IKB.SetCallbackData($"{nextmonth}", $"month {nextyear} {((ushort)nextmonth)}"); + calendar[^1][0] = new IKB($"{previousmonth}") { CallbackData = $"month {previousyear} {(ushort)previousmonth}" }; + calendar[^1][1] = new IKB($"{nextmonth}") { CallbackData = $"month {nextyear} {(ushort)nextmonth}" }; return calendar; } public static IKB[][] New(uint year) { var keyboard = new IKB[6][]; keyboard[0] = new IKB[1]{ - IKB.SetCallbackData($"{year}", $"Year {year}") + new IKB($"{year}") { CallbackData = $"Year {year}" } }; for (int i = 1, n = 0; i < 5; i++) { @@ -98,10 +101,10 @@ public static IKB[][] New(uint year) }; } } - keyboard[5] = new IKB[2]{ - IKB.SetCallbackData($"{year - 1}",$"year {year - 1}"), - IKB.SetCallbackData($"{year + 1}",$"year {year + 1}") - }; + keyboard[5] = [ + new($"{year - 1}") { CallbackData = $"year {year - 1}"}, + new($"{year + 1}") { CallbackData = $"year {year + 1}" } + ]; return keyboard; } } diff --git a/src/Telegram.BotAPI.Examples/Telegram Calendar/CalendarBot.cs b/src/examples/Telegram Calendar/CalendarBot.cs similarity index 64% rename from src/Telegram.BotAPI.Examples/Telegram Calendar/CalendarBot.cs rename to src/examples/Telegram Calendar/CalendarBot.cs index 6d0e5ad7..0af6d9e9 100644 --- a/src/Telegram.BotAPI.Examples/Telegram Calendar/CalendarBot.cs +++ b/src/examples/Telegram Calendar/CalendarBot.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System; @@ -6,13 +6,14 @@ using Telegram.BotAPI.AvailableMethods; using Telegram.BotAPI.AvailableMethods.FormattingOptions; using Telegram.BotAPI.AvailableTypes; +using Telegram.BotAPI.Extensions; using Telegram.BotAPI.UpdatingMessages; namespace TelegramCalendar { - public sealed class CalendarBot : TelegramBotBase + public sealed class CalendarBot : SimpleTelegramBotBase { - public static readonly BotClient Api = new(""); + public TelegramBotClient Client { get; } = new(""); protected override void OnMessage(Message message) { @@ -25,7 +26,7 @@ protected override void OnMessage(Message message) { InlineKeyboard = Calendar.New(DateTime.Now) }; - Api.SendMessage(message.Chat.Id, "🗓 Telegram Bot Calendar 🗓", parseMode: ParseMode.HTML, replyMarkup: rm); + Client.SendMessage(message.Chat.Id, "🗓 Telegram Bot Calendar 🗓", parseMode: ParseMode.HTML, replyMarkup: rm); } } } @@ -41,31 +42,17 @@ protected override void OnCallbackQuery(CallbackQuery query) { InlineKeyboard = Calendar.New(month) }; - Api.EditMessageReplyMarkup(new EditMessageReplyMarkup - { - ChatId = query.Message.Chat.Id, - MessageId = query.Message.MessageId, - ReplyMarkup = mkeyboard - }); + Client.EditMessageReplyMarkup(query.Message.Chat.Id, query.Message.MessageId, mkeyboard); break; case "year": var ykeyboard = new InlineKeyboardMarkup { InlineKeyboard = Calendar.New(uint.Parse(cbargs[1])) }; - Api.EditMessageReplyMarkup(new EditMessageReplyMarkup - { - ChatId = query.Message.Chat.Id, - MessageId = query.Message.MessageId, - ReplyMarkup = ykeyboard - }); + Client.EditMessageReplyMarkup(query.Message.Chat.Id, query.Message.MessageId, ykeyboard); break; default: - Api.AnswerCallbackQuery(new AnswerCallbackQueryArgs(query.Id) - { - Text = query.Data, - ShowAlert = true - }); + Client.AnswerCallbackQuery(query.Id, query.Data, true); break; } } diff --git a/src/Telegram.BotAPI.Examples/Telegram Calendar/Models/Day.cs b/src/examples/Telegram Calendar/Models/Day.cs similarity index 89% rename from src/Telegram.BotAPI.Examples/Telegram Calendar/Models/Day.cs rename to src/examples/Telegram Calendar/Models/Day.cs index e3c68467..35f2fb38 100644 --- a/src/Telegram.BotAPI.Examples/Telegram Calendar/Models/Day.cs +++ b/src/examples/Telegram Calendar/Models/Day.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System; diff --git a/src/Telegram.BotAPI.Examples/Telegram Calendar/Models/Month.cs b/src/examples/Telegram Calendar/Models/Month.cs similarity index 97% rename from src/Telegram.BotAPI.Examples/Telegram Calendar/Models/Month.cs rename to src/examples/Telegram Calendar/Models/Month.cs index 31dc5d3f..5ac31c23 100644 --- a/src/Telegram.BotAPI.Examples/Telegram Calendar/Models/Month.cs +++ b/src/examples/Telegram Calendar/Models/Month.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System; diff --git a/src/Telegram.BotAPI.Examples/Telegram Calendar/Models/MonthName.cs b/src/examples/Telegram Calendar/Models/MonthName.cs similarity index 87% rename from src/Telegram.BotAPI.Examples/Telegram Calendar/Models/MonthName.cs rename to src/examples/Telegram Calendar/Models/MonthName.cs index e4dc47b3..9880798b 100644 --- a/src/Telegram.BotAPI.Examples/Telegram Calendar/Models/MonthName.cs +++ b/src/examples/Telegram Calendar/Models/MonthName.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace TelegramCalendar diff --git a/src/Telegram.BotAPI.Examples/Telegram Calendar/Program.cs b/src/examples/Telegram Calendar/Program.cs similarity index 56% rename from src/Telegram.BotAPI.Examples/Telegram Calendar/Program.cs rename to src/examples/Telegram Calendar/Program.cs index 2225e83a..55c1a7ac 100644 --- a/src/Telegram.BotAPI.Examples/Telegram Calendar/Program.cs +++ b/src/examples/Telegram Calendar/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System; @@ -14,27 +14,26 @@ class Program static void Main() { Console.WriteLine("Start!"); - CalendarBot.Api.SetMyCommands(new BotCommand("calendar", "Telegram Calendar")); + var bot = new CalendarBot(); + bot.Client.SetMyCommands(new BotCommand("calendar", "Telegram Calendar")); // Long Polling - var updates = CalendarBot.Api.GetUpdates(allowedUpdates: new[] { AllowedUpdate.Message, AllowedUpdate.CallbackQuery }); + var updates = bot.Client.GetUpdates(allowedUpdates: new[] { AllowedUpdate.Message, AllowedUpdate.CallbackQuery }); while (true) { if (updates.Length > 0) { foreach (var update in updates) { - var bot = new CalendarBot(); bot.OnUpdate(update); } - updates = CalendarBot.Api.GetUpdates(offset: updates.Max(u => u.UpdateId) + 1); + updates = bot.Client.GetUpdates(offset: updates.Max(u => u.UpdateId) + 1); } else { - updates = CalendarBot.Api.GetUpdates(); + updates = bot.Client.GetUpdates(); } } } - } } diff --git a/src/examples/Telegram Calendar/Telegram Calendar.csproj b/src/examples/Telegram Calendar/Telegram Calendar.csproj new file mode 100644 index 00000000..21b262f6 --- /dev/null +++ b/src/examples/Telegram Calendar/Telegram Calendar.csproj @@ -0,0 +1,14 @@ + + + + Exe + net8.0 + TelegramCalendar + + + + + + + + diff --git a/src/Telegram.BotAPI.Examples/Telegram Calendar/readme.md b/src/examples/Telegram Calendar/readme.md similarity index 99% rename from src/Telegram.BotAPI.Examples/Telegram Calendar/readme.md rename to src/examples/Telegram Calendar/readme.md index 7fe102b1..63b7c64d 100644 --- a/src/Telegram.BotAPI.Examples/Telegram Calendar/readme.md +++ b/src/examples/Telegram Calendar/readme.md @@ -24,7 +24,7 @@ namespace TelegramCalendar { class Program { - private static BotClient bot = new BotClient(""); + private static TelegramBotClient bot = new TelegramBotClient(""); static void Main() { Console.WriteLine("Start!"); diff --git a/src/Telegram.BotAPI.Examples/readme.md b/src/examples/readme.md similarity index 81% rename from src/Telegram.BotAPI.Examples/readme.md rename to src/examples/readme.md index 86b69d40..972eb106 100644 --- a/src/Telegram.BotAPI.Examples/readme.md +++ b/src/examples/readme.md @@ -1,7 +1,7 @@ # Telegram.BotAPI NET Examples [![NuGet version (Telegram.BotAPI)](https://img.shields.io/nuget/v/Telegram.BotAPI.svg?style=flat-square)](https://www.nuget.org/packages/Telegram.BotAPI/) -[![Compatible with Bot API v6.9](https://img.shields.io/badge/Bot%20API%20version-v6.9-blue?style=flat-square)](https://core.telegram.org/bots/api#september-22-2023) +[![Compatible with Bot API v7.0](https://img.shields.io/badge/Bot%20API%20version-v7.0-blue?style=flat-square)](https://core.telegram.org/bots/api#december-29-2023) ## Sample list diff --git a/src/Telegram.BotAPI.Experimental/Abstractions/TelegramChat.cs b/src/library/Telegram.BotAPI.Experimental/Abstractions/TelegramChat.cs similarity index 95% rename from src/Telegram.BotAPI.Experimental/Abstractions/TelegramChat.cs rename to src/library/Telegram.BotAPI.Experimental/Abstractions/TelegramChat.cs index 527ccf22..ee49807a 100644 --- a/src/Telegram.BotAPI.Experimental/Abstractions/TelegramChat.cs +++ b/src/library/Telegram.BotAPI.Experimental/Abstractions/TelegramChat.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.ComponentModel.DataAnnotations; diff --git a/src/Telegram.BotAPI.Experimental/Abstractions/TelegramUser.cs b/src/library/Telegram.BotAPI.Experimental/Abstractions/TelegramUser.cs similarity index 95% rename from src/Telegram.BotAPI.Experimental/Abstractions/TelegramUser.cs rename to src/library/Telegram.BotAPI.Experimental/Abstractions/TelegramUser.cs index 6bfae2e7..abb7cee5 100644 --- a/src/Telegram.BotAPI.Experimental/Abstractions/TelegramUser.cs +++ b/src/library/Telegram.BotAPI.Experimental/Abstractions/TelegramUser.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.ComponentModel.DataAnnotations; diff --git a/src/Telegram.BotAPI.Experimental/Enums/MessageType.cs b/src/library/Telegram.BotAPI.Experimental/Enums/MessageType.cs similarity index 96% rename from src/Telegram.BotAPI.Experimental/Enums/MessageType.cs rename to src/library/Telegram.BotAPI.Experimental/Enums/MessageType.cs index 11d105f5..9be0a323 100644 --- a/src/Telegram.BotAPI.Experimental/Enums/MessageType.cs +++ b/src/library/Telegram.BotAPI.Experimental/Enums/MessageType.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI.AvailableTypes; diff --git a/src/Telegram.BotAPI.Experimental/Extensions/ChatMemberExtensions.cs b/src/library/Telegram.BotAPI.Experimental/Extensions/ChatMemberExtensions.cs similarity index 96% rename from src/Telegram.BotAPI.Experimental/Extensions/ChatMemberExtensions.cs rename to src/library/Telegram.BotAPI.Experimental/Extensions/ChatMemberExtensions.cs index ad0b471e..7ffd9fed 100644 --- a/src/Telegram.BotAPI.Experimental/Extensions/ChatMemberExtensions.cs +++ b/src/library/Telegram.BotAPI.Experimental/Extensions/ChatMemberExtensions.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI.AvailableTypes; diff --git a/src/Telegram.BotAPI.Experimental/Extensions/MessageExtensions.cs b/src/library/Telegram.BotAPI.Experimental/Extensions/MessageExtensions.cs similarity index 95% rename from src/Telegram.BotAPI.Experimental/Extensions/MessageExtensions.cs rename to src/library/Telegram.BotAPI.Experimental/Extensions/MessageExtensions.cs index 8ce0815a..a77ea0d0 100644 --- a/src/Telegram.BotAPI.Experimental/Extensions/MessageExtensions.cs +++ b/src/library/Telegram.BotAPI.Experimental/Extensions/MessageExtensions.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System; @@ -33,7 +33,7 @@ public static DateTime GetEditDatetime(this Message message) /// A object. public static DateTime GetForwardDatetime(this Message message) { - var forwardDate = Convert.ToDouble(message.ForwardDate); + var forwardDate = Convert.ToDouble(message.ForwardOrigin?.Date ?? 0); return DateTime.UnixEpoch.AddSeconds(forwardDate); } diff --git a/src/Telegram.BotAPI.Experimental/Extensions/Methods/deleteMessage.cs b/src/library/Telegram.BotAPI.Experimental/Extensions/Methods/deleteMessage.cs similarity index 91% rename from src/Telegram.BotAPI.Experimental/Extensions/Methods/deleteMessage.cs rename to src/library/Telegram.BotAPI.Experimental/Extensions/Methods/deleteMessage.cs index a29499fd..ade858e3 100644 --- a/src/Telegram.BotAPI.Experimental/Extensions/Methods/deleteMessage.cs +++ b/src/library/Telegram.BotAPI.Experimental/Extensions/Methods/deleteMessage.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System; @@ -23,7 +23,7 @@ public static partial class UpdatingMessagesExtensions /// True on success. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool DeleteMessages(this BotClient? api, Message message) + public static bool DeleteMessages(this ITelegramBotClient api, Message message) { if (api == null) { @@ -49,7 +49,7 @@ public static bool DeleteMessages(this BotClient? api, Message message) /// True on success. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task DeleteMessagesAsync(this BotClient? api, Message message, [Optional] CancellationToken cancellationToken) + public static async Task DeleteMessagesAsync(this ITelegramBotClient api, Message message, CancellationToken cancellationToken = default) { if (api == null) { diff --git a/src/Telegram.BotAPI.Experimental/Extensions/StringExtensions.cs b/src/library/Telegram.BotAPI.Experimental/Extensions/StringExtensions.cs similarity index 98% rename from src/Telegram.BotAPI.Experimental/Extensions/StringExtensions.cs rename to src/library/Telegram.BotAPI.Experimental/Extensions/StringExtensions.cs index e8169afd..0974ae70 100644 --- a/src/Telegram.BotAPI.Experimental/Extensions/StringExtensions.cs +++ b/src/library/Telegram.BotAPI.Experimental/Extensions/StringExtensions.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Telegram.BotAPI.AvailableMethods.FormattingOptions; diff --git a/src/Telegram.BotAPI.Experimental/Extensions/TelegramChatExtensions.cs b/src/library/Telegram.BotAPI.Experimental/Extensions/TelegramChatExtensions.cs similarity index 97% rename from src/Telegram.BotAPI.Experimental/Extensions/TelegramChatExtensions.cs rename to src/library/Telegram.BotAPI.Experimental/Extensions/TelegramChatExtensions.cs index dbdffeb7..bab2cb97 100644 --- a/src/Telegram.BotAPI.Experimental/Extensions/TelegramChatExtensions.cs +++ b/src/library/Telegram.BotAPI.Experimental/Extensions/TelegramChatExtensions.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Telegram.BotAPI.AvailableTypes; diff --git a/src/Telegram.BotAPI.Experimental/Extensions/TelegramUserExtensions.cs b/src/library/Telegram.BotAPI.Experimental/Extensions/TelegramUserExtensions.cs similarity index 98% rename from src/Telegram.BotAPI.Experimental/Extensions/TelegramUserExtensions.cs rename to src/library/Telegram.BotAPI.Experimental/Extensions/TelegramUserExtensions.cs index 285cce1d..286cba76 100644 --- a/src/Telegram.BotAPI.Experimental/Extensions/TelegramUserExtensions.cs +++ b/src/library/Telegram.BotAPI.Experimental/Extensions/TelegramUserExtensions.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Telegram.BotAPI.AvailableTypes; diff --git a/src/Telegram.BotAPI.Experimental/Telegram.BotAPI.Experimental.csproj b/src/library/Telegram.BotAPI.Experimental/Telegram.BotAPI.Experimental.csproj similarity index 71% rename from src/Telegram.BotAPI.Experimental/Telegram.BotAPI.Experimental.csproj rename to src/library/Telegram.BotAPI.Experimental/Telegram.BotAPI.Experimental.csproj index c0d83537..76f84d05 100644 --- a/src/Telegram.BotAPI.Experimental/Telegram.BotAPI.Experimental.csproj +++ b/src/library/Telegram.BotAPI.Experimental/Telegram.BotAPI.Experimental.csproj @@ -2,13 +2,6 @@ net6.0 - enable - False - False - en - 0.1 - 0.1 - false diff --git a/src/library/Telegram.BotAPI.Extensions/BotCommandExtractor.cs b/src/library/Telegram.BotAPI.Extensions/BotCommandExtractor.cs new file mode 100644 index 00000000..635ce6ac --- /dev/null +++ b/src/library/Telegram.BotAPI.Extensions/BotCommandExtractor.cs @@ -0,0 +1,48 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System.Globalization; +using System.Text.RegularExpressions; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.Extensions; + +/// +/// Defines a method to extract commands from a message using regex. +/// +sealed class BotCommandExtractor : IBotCommandExtractor +{ + private const string COMMAND_EXTRACT_PATTERN = @"^\/(?\w*)(?:|@{0})(?:$|\s(?.*))"; + private readonly Regex cmdRegex; + + /// + /// Initializes a new instance of the class. + /// + /// The bot's username. + /// Set true to use regex compiled option. + public BotCommandExtractor(string username, bool useRegexCompiled) + { + var pattern = string.Format(CultureInfo.InvariantCulture, COMMAND_EXTRACT_PATTERN, username); + var options = RegexOptions.IgnoreCase; + if (useRegexCompiled) + { + options |= RegexOptions.Compiled; + } + this.cmdRegex = new Regex(pattern, options); + } + + /// + public bool HasCommand(Message message) + { + return !string.IsNullOrEmpty(message.Text) && this.cmdRegex.IsMatch(message.Text); + } + + /// + public (string commandName, string args) ExtractCommand(Message message) + { + var match = this.cmdRegex.Match(message.Text); + var name = match.Groups["cmd"].Value; + var args = match.Groups["params"].Value; + return (name, args); + } +} diff --git a/src/library/Telegram.BotAPI.Extensions/ContextTelegramBotBase.cs b/src/library/Telegram.BotAPI.Extensions/ContextTelegramBotBase.cs new file mode 100644 index 00000000..623b822b --- /dev/null +++ b/src/library/Telegram.BotAPI.Extensions/ContextTelegramBotBase.cs @@ -0,0 +1,580 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Telegram.BotAPI.AvailableTypes; +using Telegram.BotAPI.Extensions; +using Telegram.BotAPI.GettingUpdates; +using Telegram.BotAPI.InlineMode; +using Telegram.BotAPI.Payments; + +namespace Telegram.BotAPI.Extensions; + +/// +/// Represents a Telegram Bot. +/// +public abstract class ContextTelegramBotBase : ContextTelegramBotBase> +{ + /// + /// Creates a new context for the current update. + /// + /// The current update. + /// A new context instance. + protected override IDictionary CreateContext(Update update) => this.CreateContextAsync(update).GetAwaiter().GetResult(); + /// + /// Creates a new context for the current update. + /// + /// The current update. + /// A new context instance. + protected override Task> CreateContextAsync(Update update) => Task.FromResult>(new Dictionary()); +} + +/// +/// Represents a Telegram Bot. +/// +/// The type of the bot context. +public abstract class ContextTelegramBotBase : TelegramBotSharedMethodsBase, ITelegramBot + where TBotContext : class +{ + /// + /// Creates a new context for the current update. + /// + /// The current update. + /// A new context instance. + protected virtual TBotContext CreateContext(Update update) => this.CreateContextAsync(update).GetAwaiter().GetResult(); + /// + /// Creates a new context for the current update. + /// + /// The current update. + /// A new context instance. + protected virtual Task CreateContextAsync(Update update) + { + throw new NotImplementedException(); + } + + #region Handlers + /// + public virtual void OnUpdate(Update update) + { + TBotContext? context = null; + try + { + context = this.CreateContext(update); + if (update.Message != null) + { + this.OnMessageAsync(context, update.Message); + } + else if (update.EditedMessage != null) + { + this.OnEditedMessageAsync(context, update.EditedMessage); + } + else if (update.ChannelPost != null) + { + this.OnChannelPostAsync(context, update.ChannelPost); + } + else if (update.EditedChannelPost != null) + { + this.OnEditedChannelPostAsync(context, update.EditedChannelPost); + } + else if (update.MessageReaction != null) + { + this.OnMessageReactionAsync(context, update.MessageReaction); + } + else if (update.MessageReactionCount != null) + { + this.OnMessageReactionCountAsync(context, update.MessageReactionCount); + } + else if (update.InlineQuery != null) + { + this.OnInlineQueryAsync(context, update.InlineQuery); + } + else if (update.ChosenInlineResult != null) + { + this.OnChosenInlineResultAsync(context, update.ChosenInlineResult); + } + else if (update.CallbackQuery != null) + { + this.OnCallbackQueryAsync(context, update.CallbackQuery); + } + else if (update.ShippingQuery != null) + { + this.OnShippingQueryAsync(context, update.ShippingQuery); + } + else if (update.PreCheckoutQuery != null) + { + this.OnPreCheckoutQueryAsync(context, update.PreCheckoutQuery); + } + else if (update.Poll != null) + { + this.OnPollAsync(context, update.Poll); + } + else if (update.PollAnswer != null) + { + this.OnPollAnswerAsync(context, update.PollAnswer); + } + else if (update.MyChatMember != null) + { + this.OnMyChatMemberAsync(context, update.MyChatMember); + } + else if (update.ChatMember != null) + { + this.OnChatMemberAsync(context, update.ChatMember); + } + else if (update.ChatJoinRequest != null) + { + this.OnChatJoinRequestAsync(context, update.ChatJoinRequest); + } + else if (update.ChatBoost != null) + { + this.OnChatBoostAsync(context, update.ChatBoost); + } + else if (update.RemovedChatBoost != null) + { + this.OnRemovedChatBoostAsync(context, update.RemovedChatBoost); + } + } + catch (BotRequestException exp) + { + this.OnBotExceptionAsync(context, exp); + } + catch (Exception exp) + { + this.OnExceptionAsync(context, exp); + } + } + /// + public virtual async Task OnUpdateAsync(Update update, CancellationToken cancellationToken = default) + { + TBotContext? context = null; + try + { + context = await this.CreateContextAsync(update).ConfigureAwait(false); + if (update.Message != null) + { + await this.OnMessageAsync(context, update.Message, cancellationToken).ConfigureAwait(false); + } + else if (update.EditedMessage != null) + { + await this.OnEditedMessageAsync(context, update.EditedMessage, cancellationToken).ConfigureAwait(false); + } + else if (update.ChannelPost != null) + { + await this.OnChannelPostAsync(context, update.ChannelPost, cancellationToken).ConfigureAwait(false); + } + else if (update.EditedChannelPost != null) + { + await this.OnEditedChannelPostAsync(context, update.EditedChannelPost, cancellationToken).ConfigureAwait(false); + } + else if (update.MessageReaction != null) + { + await this.OnMessageReactionAsync(context, update.MessageReaction, cancellationToken).ConfigureAwait(false); + } + else if (update.MessageReactionCount != null) + { + await this.OnMessageReactionCountAsync(context, update.MessageReactionCount, cancellationToken).ConfigureAwait(false); + } + else if (update.InlineQuery != null) + { + await this.OnInlineQueryAsync(context, update.InlineQuery, cancellationToken).ConfigureAwait(false); + } + else if (update.ChosenInlineResult != null) + { + await this.OnChosenInlineResultAsync(context, update.ChosenInlineResult, cancellationToken).ConfigureAwait(false); + } + else if (update.CallbackQuery != null) + { + await this.OnCallbackQueryAsync(context, update.CallbackQuery, cancellationToken).ConfigureAwait(false); + } + else if (update.ShippingQuery != null) + { + await this.OnShippingQueryAsync(context, update.ShippingQuery, cancellationToken).ConfigureAwait(false); + } + else if (update.PreCheckoutQuery != null) + { + await this.OnPreCheckoutQueryAsync(context, update.PreCheckoutQuery, cancellationToken).ConfigureAwait(false); + } + else if (update.Poll != null) + { + await this.OnPollAsync(context, update.Poll, cancellationToken).ConfigureAwait(false); + } + else if (update.PollAnswer != null) + { + await this.OnPollAnswerAsync(context, update.PollAnswer, cancellationToken).ConfigureAwait(false); + } + else if (update.MyChatMember != null) + { + await this.OnMyChatMemberAsync(context, update.MyChatMember, cancellationToken).ConfigureAwait(false); + } + else if (update.ChatMember != null) + { + await this.OnChatMemberAsync(context, update.ChatMember, cancellationToken).ConfigureAwait(false); + } + else if (update.ChatJoinRequest != null) + { + await this.OnChatJoinRequestAsync(context, update.ChatJoinRequest, cancellationToken).ConfigureAwait(false); + } + else if (update.ChatBoost != null) + { + await this.OnChatBoostAsync(context, update.ChatBoost, cancellationToken).ConfigureAwait(false); + } + else if (update.RemovedChatBoost != null) + { + await this.OnRemovedChatBoostAsync(context, update.RemovedChatBoost, cancellationToken).ConfigureAwait(false); + } + } + catch (BotRequestException exp) + { + await this.OnBotExceptionAsync(context, exp, cancellationToken).ConfigureAwait(false); + } + catch (Exception exp) + { + await this.OnExceptionAsync(context, exp, cancellationToken).ConfigureAwait(false); + } + } + /// + /// Handles a message update. + /// + /// Bot context. + /// Message. + protected virtual void OnMessage(TBotContext context, Message message) + { + if (this.CommandExtractor is null) + { + if (message.Entities?.Any(e => e.Type == "bot_command") ?? false) + { + var textParts = message.Text!.Split([' '], StringSplitOptions.RemoveEmptyEntries); + var commandName = textParts.First().TrimStart('/').Split('@').First(); + var args = string.Join(" ", textParts.Skip(1)); + this.OnCommand(context, message, commandName, args); + } + } + else + { + if (this.CommandExtractor.HasCommand(message)) + { + var (commandName, args) = this.CommandExtractor.ExtractCommand(message); + this.OnCommand(context, message, commandName, args); + } + } + } + /// + /// Handles a message update. + /// + /// Bot context. + /// Message. + /// Cancellation token + protected virtual Task OnMessageAsync(TBotContext context, Message message, CancellationToken cancellationToken = default) + { + if (this.CommandExtractor is null) + { + if (message.Entities?.Any(e => e.Type == "bot_command") ?? false) + { + var textParts = message.Text!.Split([' '], StringSplitOptions.RemoveEmptyEntries); + var commandName = textParts.First().TrimStart('/').Split('@').First(); + var args = string.Join(" ", textParts.Skip(1)); + return this.OnCommandAsync(context, message, commandName, args, cancellationToken); + } + } + else + { + if (this.CommandExtractor.HasCommand(message)) + { + var (commandName, args) = this.CommandExtractor.ExtractCommand(message); + return this.OnCommandAsync(context, message, commandName, args, cancellationToken); + } + } + + return Task.CompletedTask; + } + /// + /// Handles an edited message update. + /// + /// Bot context. + /// The edited message. + protected virtual void OnEditedMessage(TBotContext context, Message message) => this.OnEditedMessageAsync(context, message).Wait(); + /// + /// Handles an edited message update. + /// + /// Bot context. + /// The edited message. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnEditedMessageAsync(TBotContext context, Message message, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a channel post update. + /// + /// Bot context. + /// The channel post. + protected virtual void OnChannelPost(TBotContext context, Message message) => this.OnChannelPostAsync(context, message).Wait(); + /// + /// Handles a channel post update. + /// + /// Bot context. + /// The channel post. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnChannelPostAsync(TBotContext context, Message message, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles an edited channel post update. + /// + /// Bot context. + /// The edited channel post. + protected virtual void OnEditedChannelPost(TBotContext context, Message message) => this.OnEditedChannelPostAsync(context, message).Wait(); + /// + /// Handles an edited channel post update. + /// + /// Bot context. + /// The edited channel post. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnEditedChannelPostAsync(TBotContext context, Message message, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a message reaction update. + /// + /// Bot context. + /// The message reaction. + protected virtual void OnMessageReaction(TBotContext context, MessageReactionUpdated messageReaction) => this.OnMessageReactionAsync(context, messageReaction).Wait(); + /// + /// Handles a message reaction update. + /// + /// Bot context. + /// The message reaction. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnMessageReactionAsync(TBotContext context, MessageReactionUpdated messageReaction, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a message reaction count update. + /// + /// Bot context. + /// The message reaction count. + /// A representing the asynchronous operation. + protected virtual void OnMessageReactionCount(TBotContext context, MessageReactionCountUpdated messageReactionCount) => this.OnMessageReactionCountAsync(context, messageReactionCount).Wait(); + /// + /// Handles a message reaction count update. + /// + /// Bot context. + /// The message reaction count. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnMessageReactionCountAsync(TBotContext context, MessageReactionCountUpdated messageReactionCount, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles an inline query update. + /// + /// Bot context. + /// The inline query. + protected virtual void OnInlineQuery(TBotContext context, InlineQuery inlineQuery) => this.OnInlineQueryAsync(context, inlineQuery).Wait(); + /// + /// Handles an inline query update. + /// + /// Bot context. + /// The inline query. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnInlineQueryAsync(TBotContext context, InlineQuery inlineQuery, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a chosen inline result update. + /// + /// Bot context. + /// The chosen inline result. + /// A representing the asynchronous operation. + protected virtual void OnChosenInlineResult(TBotContext context, ChosenInlineResult chosenInlineResult) => this.OnChosenInlineResultAsync(context, chosenInlineResult).Wait(); + /// + /// Handles a chosen inline result update. + /// + /// Bot context. + /// The chosen inline result. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnChosenInlineResultAsync(TBotContext context, ChosenInlineResult chosenInlineResult, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a callback query update. + /// + /// Bot context. + /// The callback query. + protected virtual void OnCallbackQuery(TBotContext context, CallbackQuery callbackQuery) => this.OnCallbackQueryAsync(context, callbackQuery).Wait(); + /// + /// Handles a callback query update. + /// + /// Bot context. + /// The callback query. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnCallbackQueryAsync(TBotContext context, CallbackQuery callbackQuery, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a shipping query update. + /// + /// Bot context. + /// The shipping query. + protected virtual void OnShippingQuery(TBotContext context, ShippingQuery shippingQuery) => this.OnShippingQueryAsync(context, shippingQuery).Wait(); + /// + /// Handles a shipping query update. + /// + /// Bot context. + /// The shipping query. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnShippingQueryAsync(TBotContext context, ShippingQuery shippingQuery, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a pre-checkout query update. + /// + /// Bot context. + /// The pre-checkout query. + protected virtual void OnPreCheckoutQuery(TBotContext context, PreCheckoutQuery preCheckoutQuery) => this.OnPreCheckoutQueryAsync(context, preCheckoutQuery).Wait(); + /// + /// Handles a pre-checkout query update. + /// + /// Bot context. + /// The pre-checkout query. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnPreCheckoutQueryAsync(TBotContext context, PreCheckoutQuery preCheckoutQuery, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a poll update. + /// + /// Bot context. + /// The poll. + protected virtual void OnPoll(TBotContext context, Poll poll) => this.OnPollAsync(context, poll).Wait(); + /// + /// Handles a poll update. + /// + /// Bot context. + /// The poll. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnPollAsync(TBotContext context, Poll poll, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a poll answer update. + /// + /// Bot context. + /// The poll answer. + protected virtual void OnPollAnswer(TBotContext context, PollAnswer pollAnswer) => this.OnPollAnswerAsync(context, pollAnswer).Wait(); + /// + /// Handles a poll answer update. + /// + /// Bot context. + /// The poll answer. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnPollAnswerAsync(TBotContext context, PollAnswer pollAnswer, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a my chat member update. + /// + /// Bot context. + /// The my chat member. + protected virtual void OnMyChatMember(TBotContext context, ChatMemberUpdated myChatMember) => this.OnMyChatMemberAsync(context, myChatMember).Wait(); + /// + /// Handles a my chat member update. + /// + /// Bot context. + /// The my chat member. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnMyChatMemberAsync(TBotContext context, ChatMemberUpdated myChatMember, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a chat member update. + /// + /// Bot context. + /// The chat member. + protected virtual void OnChatMember(TBotContext context, ChatMemberUpdated chatMember) => this.OnChatMemberAsync(context, chatMember).Wait(); + /// + /// Handles a chat member update. + /// + /// The chat member. + /// The chat member. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnChatMemberAsync(TBotContext context, ChatMemberUpdated chatMember, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a chat join request update. + /// + /// Bot context. + /// The chat join request. + /// A representing the asynchronous operation. + protected virtual void OnChatJoinRequest(TBotContext context, ChatJoinRequest chatJoinRequest) => this.OnChatJoinRequestAsync(context, chatJoinRequest).Wait(); + /// + /// Handles a chat join request update. + /// + /// Bot context. + /// The chat join request. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnChatJoinRequestAsync(TBotContext context, ChatJoinRequest chatJoinRequest, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a chat boost update. + /// + /// Bot context. + /// The chat boost. + protected virtual void OnChatBoost(TBotContext context, ChatBoostUpdated chatBoost) => this.OnChatBoostAsync(context, chatBoost).Wait(); + /// + /// Handles a chat boost update. + /// + /// Bot context. + /// The chat boost. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnChatBoostAsync(TBotContext context, ChatBoostUpdated chatBoost, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a removed chat boost update. + /// + /// Bot context. + /// The removed chat boost. + protected virtual void OnRemovedChatBoost(TBotContext context, ChatBoostRemoved removedChatBoost) => this.OnRemovedChatBoostAsync(context, removedChatBoost).Wait(); + /// + /// Handles a removed chat boost update. + /// + /// Bot context. + /// The removed chat boost. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnRemovedChatBoostAsync(TBotContext context, ChatBoostRemoved removedChatBoost, CancellationToken cancellationToken = default) => Task.CompletedTask; + #endregion + + #region Extra Handlers + /// + /// Handles an incoming command extracted from the current message update. + /// + /// Bot context. + /// Message. + /// Command name. + /// A string containing all the arguments of the command. It could be empty if the command has no arguments. + protected virtual void OnCommand(TBotContext context, Message message, string commandName, string args) => this.OnCommandAsync(context, message, commandName, args).Wait(); + + /// + /// Handles an incoming command extracted from the current message update. + /// + /// Message. + /// Command name. + /// A string containing all the arguments of the command. It could be empty if the command has no arguments. + /// Cancellation token + protected virtual Task OnCommandAsync(TBotContext context, Message message, string commandName, string args, CancellationToken cancellationToken = default) => Task.CompletedTask; + + /// + /// Handles an exception thrown by a bot request. + /// + /// Bot context. Null if the exception was thrown while the context was being created. + /// Bot exception + protected virtual void OnBotException(TBotContext? context, BotRequestException exp) => this.OnBotExceptionAsync(context, exp).Wait(); + + /// + /// Handles an exception thrown by a bot request. + /// + /// Bot context. Null if the exception was thrown while the context was being created. + /// Bot exception + /// Cancellation token + protected virtual Task OnBotExceptionAsync(TBotContext? context, BotRequestException exp, CancellationToken cancellationToken = default) => Task.CompletedTask; + + /// + /// Handles an exception thrown by the application. + /// + /// Bot context. Null if the exception was thrown while the context was being created. + /// Exception + protected virtual void OnException(TBotContext? context, Exception exp) => this.OnExceptionAsync(context, exp).Wait(); + + /// + /// Handles an exception thrown by the application. + /// + /// Bot context. Null if the exception was thrown while the context was being created. + /// Exception + /// Cancellation token + protected virtual Task OnExceptionAsync(TBotContext? context, Exception exp, CancellationToken cancellationToken = default) => Task.CompletedTask; + #endregion +} diff --git a/src/library/Telegram.BotAPI.Extensions/IBotCommandExtractor.cs b/src/library/Telegram.BotAPI.Extensions/IBotCommandExtractor.cs new file mode 100644 index 00000000..64fa0e7b --- /dev/null +++ b/src/library/Telegram.BotAPI.Extensions/IBotCommandExtractor.cs @@ -0,0 +1,26 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.Extensions; + +/// +/// Defines methods to extract commands from a message. +/// +public interface IBotCommandExtractor +{ + /// + /// Checks if the message contains a command. + /// + /// The message to check. + /// True if the message contains a command; otherwise, false. + public bool HasCommand(Message message); + + /// + /// Extracts the command and its arguments from the message. + /// + /// The message to extract the command from. + /// A tuple containing the command and + public (string commandName, string args) ExtractCommand(Message message); +} diff --git a/src/library/Telegram.BotAPI.Extensions/SimpleTelegramBotBase.cs b/src/library/Telegram.BotAPI.Extensions/SimpleTelegramBotBase.cs new file mode 100644 index 00000000..dd564bc3 --- /dev/null +++ b/src/library/Telegram.BotAPI.Extensions/SimpleTelegramBotBase.cs @@ -0,0 +1,501 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Telegram.BotAPI.AvailableTypes; +using Telegram.BotAPI.Extensions; +using Telegram.BotAPI.GettingUpdates; +using Telegram.BotAPI.InlineMode; +using Telegram.BotAPI.Payments; + +namespace Telegram.BotAPI.Extensions; + +/// +/// Represents a base class to create a Telegram Bot. +/// +/// +/// If you want to manage a context object for each update, use instead. +/// +public abstract class SimpleTelegramBotBase : TelegramBotSharedMethodsBase, ITelegramBot +{ + #region Handlers + /// + public virtual void OnUpdate(Update update) + { + try + { + if (update.Message != null) + { + this.OnMessage(update.Message); + } + else if (update.EditedMessage != null) + { + this.OnEditedMessage(update.EditedMessage); + } + else if (update.ChannelPost != null) + { + this.OnChannelPost(update.ChannelPost); + } + else if (update.EditedChannelPost != null) + { + this.OnEditedChannelPost(update.EditedChannelPost); + } + else if (update.MessageReaction != null) + { + this.OnMessageReaction(update.MessageReaction); + } + else if (update.MessageReactionCount != null) + { + this.OnMessageReactionCount(update.MessageReactionCount); + } + else if (update.InlineQuery != null) + { + this.OnInlineQuery(update.InlineQuery); + } + else if (update.ChosenInlineResult != null) + { + this.OnChosenInlineResult(update.ChosenInlineResult); + } + else if (update.CallbackQuery != null) + { + this.OnCallbackQuery(update.CallbackQuery); + } + else if (update.ShippingQuery != null) + { + this.OnShippingQuery(update.ShippingQuery); + } + else if (update.PreCheckoutQuery != null) + { + this.OnPreCheckoutQuery(update.PreCheckoutQuery); + } + else if (update.Poll != null) + { + this.OnPoll(update.Poll); + } + else if (update.PollAnswer != null) + { + this.OnPollAnswer(update.PollAnswer); + } + else if (update.MyChatMember != null) + { + this.OnMyChatMember(update.MyChatMember); + } + else if (update.ChatMember != null) + { + this.OnChatMember(update.ChatMember); + } + else if (update.ChatJoinRequest != null) + { + this.OnChatJoinRequest(update.ChatJoinRequest); + } + else if (update.ChatBoost != null) + { + this.OnChatBoost(update.ChatBoost); + } + else if (update.RemovedChatBoost != null) + { + this.OnRemovedChatBoost(update.RemovedChatBoost); + } + } + catch (BotRequestException exp) + { + this.OnBotException(exp); + } + catch (Exception exp) + { + this.OnException(exp); + } + } + /// + public virtual async Task OnUpdateAsync(Update update, CancellationToken cancellationToken = default) + { + try + { + if (update.Message != null) + { + await this.OnMessageAsync(update.Message, cancellationToken).ConfigureAwait(false); + } + else if (update.EditedMessage != null) + { + await this.OnEditedMessageAsync(update.EditedMessage, cancellationToken).ConfigureAwait(false); + } + else if (update.ChannelPost != null) + { + await this.OnChannelPostAsync(update.ChannelPost, cancellationToken).ConfigureAwait(false); + } + else if (update.EditedChannelPost != null) + { + await this.OnEditedChannelPostAsync(update.EditedChannelPost, cancellationToken).ConfigureAwait(false); + } + else if (update.MessageReaction != null) + { + await this.OnMessageReactionAsync(update.MessageReaction, cancellationToken).ConfigureAwait(false); + } + else if (update.MessageReactionCount != null) + { + await this.OnMessageReactionCountAsync(update.MessageReactionCount, cancellationToken).ConfigureAwait(false); + } + else if (update.InlineQuery != null) + { + await this.OnInlineQueryAsync(update.InlineQuery, cancellationToken).ConfigureAwait(false); + } + else if (update.ChosenInlineResult != null) + { + await this.OnChosenInlineResultAsync(update.ChosenInlineResult, cancellationToken).ConfigureAwait(false); + } + else if (update.CallbackQuery != null) + { + await this.OnCallbackQueryAsync(update.CallbackQuery, cancellationToken).ConfigureAwait(false); + } + else if (update.ShippingQuery != null) + { + await this.OnShippingQueryAsync(update.ShippingQuery, cancellationToken).ConfigureAwait(false); + } + else if (update.PreCheckoutQuery != null) + { + await this.OnPreCheckoutQueryAsync(update.PreCheckoutQuery, cancellationToken).ConfigureAwait(false); + } + else if (update.Poll != null) + { + await this.OnPollAsync(update.Poll, cancellationToken).ConfigureAwait(false); + } + else if (update.PollAnswer != null) + { + await this.OnPollAnswerAsync(update.PollAnswer, cancellationToken).ConfigureAwait(false); + } + else if (update.MyChatMember != null) + { + await this.OnMyChatMemberAsync(update.MyChatMember, cancellationToken).ConfigureAwait(false); + } + else if (update.ChatMember != null) + { + await this.OnChatMemberAsync(update.ChatMember, cancellationToken).ConfigureAwait(false); + } + else if (update.ChatJoinRequest != null) + { + await this.OnChatJoinRequestAsync(update.ChatJoinRequest, cancellationToken).ConfigureAwait(false); + } + else if (update.ChatBoost != null) + { + await this.OnChatBoostAsync(update.ChatBoost, cancellationToken).ConfigureAwait(false); + } + else if (update.RemovedChatBoost != null) + { + await this.OnRemovedChatBoostAsync(update.RemovedChatBoost, cancellationToken).ConfigureAwait(false); + } + } + catch (BotRequestException exp) + { + await this.OnBotExceptionAsync(exp, cancellationToken).ConfigureAwait(false); + } + catch (Exception exp) + { + await this.OnExceptionAsync(exp, cancellationToken).ConfigureAwait(false); + } + } + /// + /// Handles a message update. + /// + /// Message. + protected virtual void OnMessage(Message message) + { + if (this.CommandExtractor is null) + { + if (message.Entities?.Any(e => e.Type == "bot_command") ?? false) + { + var textParts = message.Text!.Split([' '], StringSplitOptions.RemoveEmptyEntries); + var commandName = textParts.First().TrimStart('/').Split('@').First(); + var args = string.Join(" ", textParts.Skip(1)); + this.OnCommand(message, commandName, args); + } + } + else + { + if (this.CommandExtractor.HasCommand(message)) + { + var (commandName, args) = this.CommandExtractor.ExtractCommand(message); + this.OnCommand(message, commandName, args); + } + } + } + /// + /// Handles a message update. + /// + /// Message. + /// Cancellation token + protected virtual Task OnMessageAsync(Message message, CancellationToken cancellationToken = default) + { + if (this.CommandExtractor is null) + { + if (message.Entities?.Any(e => e.Type == "bot_command") ?? false) + { + var textParts = message.Text!.Split([' '], StringSplitOptions.RemoveEmptyEntries); + var commandName = textParts.First().TrimStart('/').Split('@').First(); + var args = string.Join(" ", textParts.Skip(1)); + return this.OnCommandAsync(message, commandName, args, cancellationToken); + } + } + else + { + if (this.CommandExtractor.HasCommand(message)) + { + var (commandName, args) = this.CommandExtractor.ExtractCommand(message); + return this.OnCommandAsync(message, commandName, args, cancellationToken); + } + } + + return Task.CompletedTask; + } + /// + /// Handles an edited message update. + /// + /// The edited message. + protected virtual void OnEditedMessage(Message message) => this.OnEditedMessageAsync(message).Wait(); + /// + /// Handles an edited message update. + /// + /// The edited message. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnEditedMessageAsync(Message message, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a channel post update. + /// + /// The channel post. + protected virtual void OnChannelPost(Message message) => this.OnChannelPostAsync(message).Wait(); + /// + /// Handles a channel post update. + /// + /// The channel post. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnChannelPostAsync(Message message, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles an edited channel post update. + /// + /// The edited channel post. + protected virtual void OnEditedChannelPost(Message message) => this.OnEditedChannelPostAsync(message).Wait(); + /// + /// Handles an edited channel post update. + /// + /// The edited channel post. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnEditedChannelPostAsync(Message message, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a message reaction update. + /// + /// The message reaction. + protected virtual void OnMessageReaction(MessageReactionUpdated messageReaction) => this.OnMessageReactionAsync(messageReaction).Wait(); + /// + /// Handles a message reaction update. + /// + /// The message reaction. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnMessageReactionAsync(MessageReactionUpdated messageReaction, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a message reaction count update. + /// + /// The message reaction count. + /// A representing the asynchronous operation. + protected virtual void OnMessageReactionCount(MessageReactionCountUpdated messageReactionCount) => this.OnMessageReactionCountAsync(messageReactionCount).Wait(); + /// + /// Handles a message reaction count update. + /// + /// The message reaction count. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnMessageReactionCountAsync(MessageReactionCountUpdated messageReactionCount, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles an inline query update. + /// + /// The inline query. + protected virtual void OnInlineQuery(InlineQuery inlineQuery) => this.OnInlineQueryAsync(inlineQuery).Wait(); + /// + /// Handles an inline query update. + /// + /// The inline query. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnInlineQueryAsync(InlineQuery inlineQuery, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a chosen inline result update. + /// + /// The chosen inline result. + /// A representing the asynchronous operation. + protected virtual void OnChosenInlineResult(ChosenInlineResult chosenInlineResult) => this.OnChosenInlineResultAsync(chosenInlineResult).Wait(); + /// + /// Handles a chosen inline result update. + /// + /// The chosen inline result. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnChosenInlineResultAsync(ChosenInlineResult chosenInlineResult, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a callback query update. + /// + /// The callback query. + protected virtual void OnCallbackQuery(CallbackQuery callbackQuery) => this.OnCallbackQueryAsync(callbackQuery).Wait(); + /// + /// Handles a callback query update. + /// + /// The callback query. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnCallbackQueryAsync(CallbackQuery callbackQuery, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a shipping query update. + /// + /// The shipping query. + protected virtual void OnShippingQuery(ShippingQuery shippingQuery) => this.OnShippingQueryAsync(shippingQuery).Wait(); + /// + /// Handles a shipping query update. + /// + /// The shipping query. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnShippingQueryAsync(ShippingQuery shippingQuery, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a pre-checkout query update. + /// + /// The pre-checkout query. + protected virtual void OnPreCheckoutQuery(PreCheckoutQuery preCheckoutQuery) => this.OnPreCheckoutQueryAsync(preCheckoutQuery).Wait(); + /// + /// Handles a pre-checkout query update. + /// + /// The pre-checkout query. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnPreCheckoutQueryAsync(PreCheckoutQuery preCheckoutQuery, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a poll update. + /// + /// The poll. + protected virtual void OnPoll(Poll poll) => this.OnPollAsync(poll).Wait(); + /// + /// Handles a poll update. + /// + /// The poll. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnPollAsync(Poll poll, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a poll answer update. + /// + /// The poll answer. + protected virtual void OnPollAnswer(PollAnswer pollAnswer) => this.OnPollAnswerAsync(pollAnswer).Wait(); + /// + /// Handles a poll answer update. + /// + /// The poll answer. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnPollAnswerAsync(PollAnswer pollAnswer, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a my chat member update. + /// + /// The my chat member. + protected virtual void OnMyChatMember(ChatMemberUpdated myChatMember) => this.OnMyChatMemberAsync(myChatMember).Wait(); + /// + /// Handles a my chat member update. + /// + /// The my chat member. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnMyChatMemberAsync(ChatMemberUpdated myChatMember, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a chat member update. + /// + /// The chat member. + protected virtual void OnChatMember(ChatMemberUpdated chatMember) => this.OnChatMemberAsync(chatMember).Wait(); + /// + /// Handles a chat member update. + /// + /// The chat member. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnChatMemberAsync(ChatMemberUpdated chatMember, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a chat join request update. + /// + /// The chat join request. + /// A representing the asynchronous operation. + protected virtual void OnChatJoinRequest(ChatJoinRequest chatJoinRequest) => this.OnChatJoinRequestAsync(chatJoinRequest).Wait(); + /// + /// Handles a chat join request update. + /// + /// The chat join request. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnChatJoinRequestAsync(ChatJoinRequest chatJoinRequest, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a chat boost update. + /// + /// The chat boost. + protected virtual void OnChatBoost(ChatBoostUpdated chatBoost) => this.OnChatBoostAsync(chatBoost).Wait(); + /// + /// Handles a chat boost update. + /// + /// The chat boost. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnChatBoostAsync(ChatBoostUpdated chatBoost, CancellationToken cancellationToken = default) => Task.CompletedTask; + /// + /// Handles a removed chat boost update. + /// + /// The removed chat boost. + protected virtual void OnRemovedChatBoost(ChatBoostRemoved removedChatBoost) => this.OnRemovedChatBoostAsync(removedChatBoost).Wait(); + /// + /// Handles a removed chat boost update. + /// + /// The removed chat boost. + /// Cancellation token + /// A representing the asynchronous operation. + protected virtual Task OnRemovedChatBoostAsync(ChatBoostRemoved removedChatBoost, CancellationToken cancellationToken = default) => Task.CompletedTask; + #endregion + + #region Extra Handlers + /// + /// Handles an incoming command extracted from the current message update. + /// + /// Message. + /// Command name. + /// A string containing all the arguments of the command. It could be empty if the command has no arguments. + protected virtual void OnCommand(Message message, string commandName, string args) => this.OnCommandAsync(message, commandName, args).Wait(); + + /// + /// Handles an incoming command extracted from the current message update. + /// + /// Message. + /// Command name. + /// A string containing all the arguments of the command. It could be empty if the command has no arguments. + /// Cancellation token + protected virtual Task OnCommandAsync(Message message, string commandName, string args, CancellationToken cancellationToken = default) => Task.CompletedTask; + + /// + /// Handles an exception thrown by a bot request. + /// + /// Bot exception + protected virtual void OnBotException(BotRequestException exp) => this.OnBotExceptionAsync(exp).Wait(); + + /// + /// Handles an exception thrown by a bot request. + /// + /// Bot exception + /// Cancellation token + protected virtual Task OnBotExceptionAsync(BotRequestException exp, CancellationToken cancellationToken = default) => Task.CompletedTask; + + /// + /// Handles an exception thrown by the application. + /// + /// Exception + protected virtual void OnException(Exception exp) => this.OnExceptionAsync(exp).Wait(); + + /// + /// Handles an exception thrown by the application. + /// + /// Exception + /// Cancellation token + protected virtual Task OnExceptionAsync(Exception exp, CancellationToken cancellationToken = default) => Task.CompletedTask; + #endregion +} diff --git a/src/library/Telegram.BotAPI.Extensions/Telegram.BotAPI.Extensions.csproj b/src/library/Telegram.BotAPI.Extensions/Telegram.BotAPI.Extensions.csproj new file mode 100644 index 00000000..7c01f34c --- /dev/null +++ b/src/library/Telegram.BotAPI.Extensions/Telegram.BotAPI.Extensions.csproj @@ -0,0 +1,31 @@ + + + + netstandard2.0 + enable + enable + latest + True + latest-recommended + LICENSE + en + Quetzal Rivera + Quetzal Rivera 2024 © + https://github.com/Eptagone/Telegram.BotAPI + https://github.com/Eptagone/Telegram.BotAPI + Telegram;Bot;API;Extensions + 0.1 + + + + + True + \ + + + + + + + + \ No newline at end of file diff --git a/src/library/Telegram.BotAPI.Extensions/TelegramBotClientExtensions.cs b/src/library/Telegram.BotAPI.Extensions/TelegramBotClientExtensions.cs new file mode 100644 index 00000000..ed30a05c --- /dev/null +++ b/src/library/Telegram.BotAPI.Extensions/TelegramBotClientExtensions.cs @@ -0,0 +1,26 @@ +using File = Telegram.BotAPI.AvailableTypes.File; + +namespace Telegram.BotAPI.Extensions; + +/// +/// Defines aditional methods for . +/// +static class TelegramBotClientExtensions +{ + /// + /// Constructs the URL to download a Telegram File. + /// + /// The Telegram Bot Client. + /// The File. + /// + /// + public static string? BuildFileDownloadLink(this ITelegramBotClient client, File file) + { + if (string.IsNullOrEmpty(file.FilePath)) + { + return null; + } + + return $"{client.Options.ServerAddress}/file/bot{client.Options.BotToken}/{file.FilePath}"; + } +} \ No newline at end of file diff --git a/src/library/Telegram.BotAPI.Extensions/TelegramBotSharedMethods.cs b/src/library/Telegram.BotAPI.Extensions/TelegramBotSharedMethods.cs new file mode 100644 index 00000000..8bb794e2 --- /dev/null +++ b/src/library/Telegram.BotAPI.Extensions/TelegramBotSharedMethods.cs @@ -0,0 +1,63 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +namespace Telegram.BotAPI.Extensions; + +/// +/// Defines shared methods used by: +/// +/// +/// +/// +/// +/// +/// This class is not supposed to be implemented outside of this library. +/// +public abstract class TelegramBotSharedMethodsBase +{ + /// + /// Special command extractor used by the bot to extract commands from messages. + /// Use or to configure it. + /// + /// + /// If the command extractor is not configured, the default message handler will extract the commands in the simplest way possible: by checking if the message contains an entity of type "bot_command" and splitting the text by spaces. + /// + /// Set up an extractor to get more advanced features like: + /// + /// Ignore other bots' commands. + /// Remove username from command name. + /// + /// + /// + protected IBotCommandExtractor? CommandExtractor { get; private set; } + + /// + /// Configures the command extractor used by the bot to extract commands from messages. + /// + /// The command extractor to use. + public void SetCommandExtractor(IBotCommandExtractor cmdExtractor) + { + if (cmdExtractor is null) + { + throw new ArgumentNullException(nameof(cmdExtractor)); + } + this.CommandExtractor = cmdExtractor; + } + + /// + /// Configures the command extractor used by the bot to extract commands from messages. + /// + /// The bot username. + /// True to compile the regex used to extract commands. + /// + /// This method uses an internal implementation of that uses regex to extract commands. + /// + protected void SetCommandExtractor(string username, bool useRegexCompile = true) + { + if (string.IsNullOrEmpty(username)) + { + throw new ArgumentNullException(nameof(username)); + } + this.CommandExtractor = new BotCommandExtractor(username, useRegexCompile); + } +} \ No newline at end of file diff --git a/src/library/Telegram.BotAPI.Extensions/UpdateExtensions.cs b/src/library/Telegram.BotAPI.Extensions/UpdateExtensions.cs new file mode 100644 index 00000000..c87e6583 --- /dev/null +++ b/src/library/Telegram.BotAPI.Extensions/UpdateExtensions.cs @@ -0,0 +1,37 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System.Reflection; +using System.Text.Json.Serialization; +using Telegram.BotAPI.GettingUpdates; + +namespace Telegram.BotAPI.Extensions; + +/// +/// Extensions for class. +/// +public static class UpdateExtensions +{ + /// + /// Retrieves the type of the update by examining the properties of the object. + /// + /// The instance of whose type is to be determined. + /// The JSON property name of the first non-null property in the instance, excluding the UpdateId property. This is used to determine the type of the update. + /// Thrown when the provided instance is null. + /// Thrown when the instance does not have any valid properties. + + public static string GetUpdateType(this Update update) + { + if (update is null) + { + throw new ArgumentNullException(nameof(update)); + } + + // Get all properties of the Update class where the value is not null. + var properties = typeof(Update).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetValue(update) != null); + // Get the json name of the first property ignoring UpdateId. + var property = properties.FirstOrDefault(p => p.Name != nameof(Update.UpdateId)) ?? throw new InvalidOperationException("The update is not valid."); + + return property.GetCustomAttribute()!.Name; + } +} \ No newline at end of file diff --git a/src/Telegram.BotAPI/Abstractions/ICaption.cs b/src/library/Telegram.BotAPI/Abstractions/ICaption.cs similarity index 94% rename from src/Telegram.BotAPI/Abstractions/ICaption.cs rename to src/library/Telegram.BotAPI/Abstractions/ICaption.cs index d545fb14..3267a03d 100644 --- a/src/Telegram.BotAPI/Abstractions/ICaption.cs +++ b/src/library/Telegram.BotAPI/Abstractions/ICaption.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Telegram.BotAPI.AvailableTypes; diff --git a/src/Telegram.BotAPI/Abstractions/IContact.cs b/src/library/Telegram.BotAPI/Abstractions/IContact.cs similarity index 94% rename from src/Telegram.BotAPI/Abstractions/IContact.cs rename to src/library/Telegram.BotAPI/Abstractions/IContact.cs index 91b420cf..527e0cb4 100644 --- a/src/Telegram.BotAPI/Abstractions/IContact.cs +++ b/src/library/Telegram.BotAPI/Abstractions/IContact.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI.AvailableTypes; diff --git a/src/Telegram.BotAPI/Abstractions/ICustomizableReplyMarkup.cs b/src/library/Telegram.BotAPI/Abstractions/ICustomizableReplyMarkup.cs similarity index 93% rename from src/Telegram.BotAPI/Abstractions/ICustomizableReplyMarkup.cs rename to src/library/Telegram.BotAPI/Abstractions/ICustomizableReplyMarkup.cs index 86887bc0..79056f34 100644 --- a/src/Telegram.BotAPI/Abstractions/ICustomizableReplyMarkup.cs +++ b/src/library/Telegram.BotAPI/Abstractions/ICustomizableReplyMarkup.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Telegram.BotAPI.AvailableTypes; diff --git a/src/Telegram.BotAPI/Abstractions/IExternalThumbnail.cs b/src/library/Telegram.BotAPI/Abstractions/IExternalThumbnail.cs similarity index 94% rename from src/Telegram.BotAPI/Abstractions/IExternalThumbnail.cs rename to src/library/Telegram.BotAPI/Abstractions/IExternalThumbnail.cs index 8db13ed6..18613959 100644 --- a/src/Telegram.BotAPI/Abstractions/IExternalThumbnail.cs +++ b/src/library/Telegram.BotAPI/Abstractions/IExternalThumbnail.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI; diff --git a/src/Telegram.BotAPI/Abstractions/IFormattableMessage.cs b/src/library/Telegram.BotAPI/Abstractions/IFormattableMessage.cs similarity index 93% rename from src/Telegram.BotAPI/Abstractions/IFormattableMessage.cs rename to src/library/Telegram.BotAPI/Abstractions/IFormattableMessage.cs index af3318b3..b86b84fe 100644 --- a/src/Telegram.BotAPI/Abstractions/IFormattableMessage.cs +++ b/src/library/Telegram.BotAPI/Abstractions/IFormattableMessage.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI; diff --git a/src/Telegram.BotAPI/Abstractions/ILocation.cs b/src/library/Telegram.BotAPI/Abstractions/ILocation.cs similarity index 85% rename from src/Telegram.BotAPI/Abstractions/ILocation.cs rename to src/library/Telegram.BotAPI/Abstractions/ILocation.cs index 95b62628..5c077388 100644 --- a/src/Telegram.BotAPI/Abstractions/ILocation.cs +++ b/src/library/Telegram.BotAPI/Abstractions/ILocation.cs @@ -1,11 +1,14 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Telegram.BotAPI.AvailableTypes; namespace Telegram.BotAPI; -/// Represents a point on the map. Used by . +/// +/// Represents a point on the map. Used by . +/// +[Obsolete("The interface is obsolete. Don't use it.")] public interface ILocation { /// Longitude as defined by sender. diff --git a/src/Telegram.BotAPI/Abstractions/ITelegramFile.cs b/src/library/Telegram.BotAPI/Abstractions/ITelegramFile.cs similarity index 94% rename from src/Telegram.BotAPI/Abstractions/ITelegramFile.cs rename to src/library/Telegram.BotAPI/Abstractions/ITelegramFile.cs index 55fb8ff7..ab1d126f 100644 --- a/src/Telegram.BotAPI/Abstractions/ITelegramFile.cs +++ b/src/library/Telegram.BotAPI/Abstractions/ITelegramFile.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI; diff --git a/src/Telegram.BotAPI/Abstractions/IThumbnail.cs b/src/library/Telegram.BotAPI/Abstractions/IThumbnail.cs similarity index 89% rename from src/Telegram.BotAPI/Abstractions/IThumbnail.cs rename to src/library/Telegram.BotAPI/Abstractions/IThumbnail.cs index 23cbcea9..64417a55 100644 --- a/src/Telegram.BotAPI/Abstractions/IThumbnail.cs +++ b/src/library/Telegram.BotAPI/Abstractions/IThumbnail.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI; diff --git a/src/Telegram.BotAPI/Abstractions/IVenue.cs b/src/library/Telegram.BotAPI/Abstractions/IVenue.cs similarity index 96% rename from src/Telegram.BotAPI/Abstractions/IVenue.cs rename to src/library/Telegram.BotAPI/Abstractions/IVenue.cs index 16b8da20..d9032fe2 100644 --- a/src/Telegram.BotAPI/Abstractions/IVenue.cs +++ b/src/library/Telegram.BotAPI/Abstractions/IVenue.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Telegram.BotAPI.AvailableTypes; diff --git a/src/Telegram.BotAPI/Abstractions/SendMessageBase.cs b/src/library/Telegram.BotAPI/Abstractions/SendMessageBase.cs similarity index 91% rename from src/Telegram.BotAPI/Abstractions/SendMessageBase.cs rename to src/library/Telegram.BotAPI/Abstractions/SendMessageBase.cs index b12d9470..ac350d25 100644 --- a/src/Telegram.BotAPI/Abstractions/SendMessageBase.cs +++ b/src/library/Telegram.BotAPI/Abstractions/SendMessageBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; @@ -48,7 +48,9 @@ protected SendMessageBase(TChatId chatId) [JsonPropertyName(PropertyNames.MessageThreadId)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? MessageThreadId { get; set; } - /// Optional. Sends the message silently. Users will receive a notification with no sound. + /// + /// Sends the message silently. Users will receive a notification with no sound. + /// [JsonPropertyName(PropertyNames.DisableNotification)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? DisableNotification { get; set; } @@ -60,7 +62,9 @@ protected SendMessageBase(TChatId chatId) [JsonPropertyName(PropertyNames.AllowSendingWithoutReply)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? AllowSendingWithoutReply { get; set; } - /// Protects the contents of the sent message from forwarding and saving. + /// + /// Protects the contents of the sent message from forwarding and saving + /// [JsonPropertyName(PropertyNames.ProtectContent)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? ProtectContent { get; set; } diff --git a/src/Telegram.BotAPI/Abstractions/SendMessageWithReplyMarkupBase.cs b/src/library/Telegram.BotAPI/Abstractions/SendMessageWithReplyMarkupBase.cs similarity index 78% rename from src/Telegram.BotAPI/Abstractions/SendMessageWithReplyMarkupBase.cs rename to src/library/Telegram.BotAPI/Abstractions/SendMessageWithReplyMarkupBase.cs index 407584c6..30ad6a80 100644 --- a/src/Telegram.BotAPI/Abstractions/SendMessageWithReplyMarkupBase.cs +++ b/src/library/Telegram.BotAPI/Abstractions/SendMessageWithReplyMarkupBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; @@ -25,7 +25,9 @@ protected SendMessageWithReplyMarkupBase(string chatId) : base(chatId) { } - /// Optional. Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. or or or + /// + /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. + /// [JsonPropertyName(PropertyNames.ReplyMarkup)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public ReplyMarkup? ReplyMarkup { get; set; } diff --git a/src/Telegram.BotAPI/Abstractions/TelegramFileBase.cs b/src/library/Telegram.BotAPI/Abstractions/TelegramFileBase.cs similarity index 96% rename from src/Telegram.BotAPI/Abstractions/TelegramFileBase.cs rename to src/library/Telegram.BotAPI/Abstractions/TelegramFileBase.cs index ae72165e..75c19acc 100644 --- a/src/Telegram.BotAPI/Abstractions/TelegramFileBase.cs +++ b/src/library/Telegram.BotAPI/Abstractions/TelegramFileBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Methods/Args/AnswerCallBackQueryParamsArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/AnswerCallBackQueryParamsArgs.cs similarity index 98% rename from src/Telegram.BotAPI/Available Methods/Args/AnswerCallBackQueryParamsArgs.cs rename to src/library/Telegram.BotAPI/Available Methods/Args/AnswerCallBackQueryParamsArgs.cs index 387c84db..17678eb9 100644 --- a/src/Telegram.BotAPI/Available Methods/Args/AnswerCallBackQueryParamsArgs.cs +++ b/src/library/Telegram.BotAPI/Available Methods/Args/AnswerCallBackQueryParamsArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Methods/Args/CopyMessageArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/CopyMessageArgs.cs similarity index 57% rename from src/Telegram.BotAPI/Available Methods/Args/CopyMessageArgs.cs rename to src/library/Telegram.BotAPI/Available Methods/Args/CopyMessageArgs.cs index 006b9920..3c842fa5 100644 --- a/src/Telegram.BotAPI/Available Methods/Args/CopyMessageArgs.cs +++ b/src/library/Telegram.BotAPI/Available Methods/Args/CopyMessageArgs.cs @@ -1,16 +1,15 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using Telegram.BotAPI.AvailableTypes; - namespace Telegram.BotAPI.AvailableMethods; /// CopyMessage method arguments. [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class CopyMessageArgs : SendMessageWithReplyMarkupBase, ICaption, IFormattableMessage +public class CopyMessageArgs { /// /// Initialize a new instance of . @@ -18,63 +17,116 @@ public class CopyMessageArgs : SendMessageWithReplyMarkupBase, ICaption, IFormat /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) /// Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername) /// Message identifier in the chat specified in from_chat_id - public CopyMessageArgs(long chatId, long fromChatId, int messageId) : base(chatId) + public CopyMessageArgs(long chatId, long fromChatId, int messageId) { + this.ChatId = chatId; this.FromChatId = fromChatId; this.MessageId = messageId; } + /// /// Initialize a new instance of . /// /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) /// Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername) /// Message identifier in the chat specified in from_chat_id - public CopyMessageArgs(string chatId, long fromChatId, int messageId) : base(chatId) + public CopyMessageArgs(string chatId, long fromChatId, int messageId) { + this.ChatId = chatId; this.FromChatId = fromChatId; this.MessageId = messageId; } + /// /// Initialize a new instance of . /// /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) /// Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername) /// Message identifier in the chat specified in from_chat_id - public CopyMessageArgs(long chatId, string fromChatId, int messageId) : base(chatId) + public CopyMessageArgs(long chatId, string fromChatId, int messageId) { + this.ChatId = chatId; this.FromChatId = fromChatId; this.MessageId = messageId; } + /// /// Initialize a new instance of . /// /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) /// Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername) /// Message identifier in the chat specified in from_chat_id - public CopyMessageArgs(string chatId, string fromChatId, int messageId) : base(chatId) + public CopyMessageArgs(string chatId, string fromChatId, int messageId) { + this.ChatId = chatId; this.FromChatId = fromChatId; this.MessageId = messageId; } - /// or . Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername). + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object ChatId { get; set; } + /// + /// Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername) + /// [JsonPropertyName(PropertyNames.FromChatId)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public object FromChatId { get; } - /// Message identifier in the chat specified in from_chat_id. + public object FromChatId { get; set; } + /// + /// Message identifier in the chat specified in from_chat_id + /// [JsonPropertyName(PropertyNames.MessageId)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public int MessageId { get; } - /// New caption for media, 0-1024 characters after entities parsing. If not specified, the original caption is kept. + public int MessageId { get; set; } + /// + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + /// + [JsonPropertyName(PropertyNames.MessageThreadId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? MessageThreadId { get; set; } + /// + /// New caption for media, 0-1024 characters after entities parsing. If not specified, the original caption is kept + /// [JsonPropertyName(PropertyNames.Caption)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? Caption { get; set; } - /// List of special entities that appear in the new caption, which can be specified instead of parse_mode. + /// + /// Mode for parsing entities in the new caption. See formatting options for more details. + /// + [JsonPropertyName(PropertyNames.ParseMode)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? ParseMode { get; set; } + /// + /// A JSON-serialized list of special entities that appear in the new caption, which can be specified instead of parse_mode + /// [JsonPropertyName(PropertyNames.CaptionEntities)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public IEnumerable? CaptionEntities { get; set; } - /// Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. - [JsonPropertyName(PropertyNames.ParseMode)] + /// + /// Sends the message silently. Users will receive a notification with no sound. + /// + [JsonPropertyName(PropertyNames.DisableNotification)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string? ParseMode { get; set; } + public bool? DisableNotification { get; set; } + /// + /// Protects the contents of the sent message from forwarding and saving + /// + [JsonPropertyName(PropertyNames.ProtectContent)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? ProtectContent { get; set; } + /// + /// Description of the message to reply to + /// + [JsonPropertyName(PropertyNames.ReplyParameters)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyParameters? ReplyParameters { get; set; } + /// + /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. + /// + [JsonPropertyName(PropertyNames.ReplyMarkup)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyMarkup? ReplyMarkup { get; set; } } diff --git a/src/library/Telegram.BotAPI/Available Methods/Args/CopyMessagesArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/CopyMessagesArgs.cs new file mode 100644 index 00000000..8128d767 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Methods/Args/CopyMessagesArgs.cs @@ -0,0 +1,109 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// CopyMessages method arguments. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class CopyMessagesArgs +{ + /// + /// Initializes a new instance of with required parameters. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername) + /// Identifiers of 1-100 messages in the chat from_chat_id to copy. The identifiers must be specified in a strictly increasing order. + public CopyMessagesArgs(long chatId, long fromChatId, IEnumerable messageIds) + { + this.ChatId = chatId; + this.FromChatId = fromChatId; + this.MessageIds = messageIds; + } + + /// + /// Initializes a new instance of with required parameters. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername) + /// Identifiers of 1-100 messages in the chat from_chat_id to copy. The identifiers must be specified in a strictly increasing order. + public CopyMessagesArgs(string chatId, long fromChatId, IEnumerable messageIds) + { + this.ChatId = chatId; + this.FromChatId = fromChatId; + this.MessageIds = messageIds; + } + + /// + /// Initializes a new instance of with required parameters. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername) + /// Identifiers of 1-100 messages in the chat from_chat_id to copy. The identifiers must be specified in a strictly increasing order. + public CopyMessagesArgs(long chatId, string fromChatId, IEnumerable messageIds) + { + this.ChatId = chatId; + this.FromChatId = fromChatId; + this.MessageIds = messageIds; + } + + /// + /// Initializes a new instance of with required parameters. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername) + /// Identifiers of 1-100 messages in the chat from_chat_id to copy. The identifiers must be specified in a strictly increasing order. + public CopyMessagesArgs(string chatId, string fromChatId, IEnumerable messageIds) + { + this.ChatId = chatId; + this.FromChatId = fromChatId; + this.MessageIds = messageIds; + } + + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object ChatId { get; } + /// + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.FromChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object FromChatId { get; } + /// + /// Identifiers of 1-100 messages in the chat from_chat_id to copy. The identifiers must be specified in a strictly increasing order. + /// + [JsonPropertyName(PropertyNames.MessageIds)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public IEnumerable MessageIds { get; } + /// + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + /// + [JsonPropertyName(PropertyNames.MessageThreadId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? MessageThreadId { get; set; } + /// + /// Sends the messages silently. Users will receive a notification with no sound. + /// + [JsonPropertyName(PropertyNames.DisableNotification)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? DisableNotification { get; set; } + /// + /// Protects the contents of the sent messages from forwarding and saving + /// + [JsonPropertyName(PropertyNames.ProtectContent)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? ProtectContent { get; set; } + /// + /// Pass True to copy the messages without their captions + /// + [JsonPropertyName(PropertyNames.RemoveCaption)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? RemoveCaption { get; set; } +} diff --git a/src/Telegram.BotAPI/Available Methods/Args/DeleteMyCommandsArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/DeleteMyCommandsArgs.cs similarity index 97% rename from src/Telegram.BotAPI/Available Methods/Args/DeleteMyCommandsArgs.cs rename to src/library/Telegram.BotAPI/Available Methods/Args/DeleteMyCommandsArgs.cs index ea6a2144..e559f4d9 100644 --- a/src/Telegram.BotAPI/Available Methods/Args/DeleteMyCommandsArgs.cs +++ b/src/library/Telegram.BotAPI/Available Methods/Args/DeleteMyCommandsArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/library/Telegram.BotAPI/Available Methods/Args/ForwardMessagesArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/ForwardMessagesArgs.cs new file mode 100644 index 00000000..70959745 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Methods/Args/ForwardMessagesArgs.cs @@ -0,0 +1,103 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// ForwardMessages method arguments. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class ForwardMessagesArgs +{ + /// + /// Initializes a new instance of with required parameters. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername) + /// Identifiers of 1-100 messages in the chat from_chat_id to forward. The identifiers must be specified in a strictly increasing order. + public ForwardMessagesArgs(long chatId, long fromChatId, IEnumerable messageIds) + { + this.ChatId = chatId; + this.FromChatId = fromChatId; + this.MessageIds = messageIds; + } + + /// + /// Initializes a new instance of with required parameters. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername) + /// Identifiers of 1-100 messages in the chat from_chat_id to forward. The identifiers must be specified in a strictly increasing order. + public ForwardMessagesArgs(string chatId, long fromChatId, IEnumerable messageIds) + { + this.ChatId = chatId; + this.FromChatId = fromChatId; + this.MessageIds = messageIds; + } + + /// + /// Initializes a new instance of with required parameters. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername) + /// Identifiers of 1-100 messages in the chat from_chat_id to forward. The identifiers must be specified in a strictly increasing order. + public ForwardMessagesArgs(long chatId, string fromChatId, IEnumerable messageIds) + { + this.ChatId = chatId; + this.FromChatId = fromChatId; + this.MessageIds = messageIds; + } + + /// + /// Initializes a new instance of with required parameters. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername) + /// Identifiers of 1-100 messages in the chat from_chat_id to forward. The identifiers must be specified in a strictly increasing order. + public ForwardMessagesArgs(string chatId, string fromChatId, IEnumerable messageIds) + { + this.ChatId = chatId; + this.FromChatId = fromChatId; + this.MessageIds = messageIds; + } + + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object ChatId { get; } + /// + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.FromChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object FromChatId { get; } + /// + /// Identifiers of 1-100 messages in the chat from_chat_id to forward. The identifiers must be specified in a strictly increasing order. + /// + [JsonPropertyName(PropertyNames.MessageIds)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public IEnumerable MessageIds { get; } + /// + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + /// + [JsonPropertyName(PropertyNames.MessageThreadId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? MessageThreadId { get; set; } + /// + /// Sends the messages silently. Users will receive a notification with no sound. + /// + [JsonPropertyName(PropertyNames.DisableNotification)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? DisableNotification { get; set; } + /// + /// Protects the contents of the forwarded messages from forwarding and saving + /// + [JsonPropertyName(PropertyNames.ProtectContent)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? ProtectContent { get; set; } +} diff --git a/src/Telegram.BotAPI/Available Methods/Args/GetMyCommandsArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/GetMyCommandsArgs.cs similarity index 97% rename from src/Telegram.BotAPI/Available Methods/Args/GetMyCommandsArgs.cs rename to src/library/Telegram.BotAPI/Available Methods/Args/GetMyCommandsArgs.cs index 4012181b..c08a4e99 100644 --- a/src/Telegram.BotAPI/Available Methods/Args/GetMyCommandsArgs.cs +++ b/src/library/Telegram.BotAPI/Available Methods/Args/GetMyCommandsArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Methods/Args/PromoteChatMemberArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/PromoteChatMemberArgs.cs similarity index 99% rename from src/Telegram.BotAPI/Available Methods/Args/PromoteChatMemberArgs.cs rename to src/library/Telegram.BotAPI/Available Methods/Args/PromoteChatMemberArgs.cs index 8d58741f..83a802bd 100644 --- a/src/Telegram.BotAPI/Available Methods/Args/PromoteChatMemberArgs.cs +++ b/src/library/Telegram.BotAPI/Available Methods/Args/PromoteChatMemberArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Methods/Args/RestrictChatMemberArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/RestrictChatMemberArgs.cs similarity index 99% rename from src/Telegram.BotAPI/Available Methods/Args/RestrictChatMemberArgs.cs rename to src/library/Telegram.BotAPI/Available Methods/Args/RestrictChatMemberArgs.cs index af86a66f..7a34034d 100644 --- a/src/Telegram.BotAPI/Available Methods/Args/RestrictChatMemberArgs.cs +++ b/src/library/Telegram.BotAPI/Available Methods/Args/RestrictChatMemberArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Methods/Args/SendAnimationArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/SendAnimationArgs.cs similarity index 72% rename from src/Telegram.BotAPI/Available Methods/Args/SendAnimationArgs.cs rename to src/library/Telegram.BotAPI/Available Methods/Args/SendAnimationArgs.cs index 63b3f31f..832bf0fe 100644 --- a/src/Telegram.BotAPI/Available Methods/Args/SendAnimationArgs.cs +++ b/src/library/Telegram.BotAPI/Available Methods/Args/SendAnimationArgs.cs @@ -1,25 +1,24 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; using Newtonsoft.Json.Serialization; -using System.Linq; using Telegram.BotAPI.AvailableTypes; - namespace Telegram.BotAPI.AvailableMethods; /// SendAnimation method arguments. [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class SendAnimationArgs : SendMessageWithReplyMarkupBase, ICaption, IFormattableMessage, IMultipartForm, IThumbnail +public class SendAnimationArgs : AttachedFilesArgsBase { /// /// Initialize a new instance of . /// /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. - public SendAnimationArgs(long chatId, InputFile animation) : base(chatId) + public SendAnimationArgs(long chatId, InputFile animation) { + this.ChatId = chatId; this.Animation = animation; } /// @@ -27,8 +26,9 @@ public SendAnimationArgs(long chatId, InputFile animation) : base(chatId) /// /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. - public SendAnimationArgs(long chatId, string animation) : base(chatId) + public SendAnimationArgs(long chatId, string animation) { + this.ChatId = chatId; this.Animation = animation; } /// @@ -36,8 +36,9 @@ public SendAnimationArgs(long chatId, string animation) : base(chatId) /// /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. - public SendAnimationArgs(string chatId, InputFile animation) : base(chatId) + public SendAnimationArgs(string chatId, InputFile animation) { + this.ChatId = chatId; this.Animation = animation; } /// @@ -45,11 +46,18 @@ public SendAnimationArgs(string chatId, InputFile animation) : base(chatId) /// /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. - public SendAnimationArgs(string chatId, string animation) : base(chatId) + public SendAnimationArgs(string chatId, string animation) { + this.ChatId = chatId; this.Animation = animation; } + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object ChatId { get; set; } /// /// Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. More information on Sending Files » /// @@ -57,6 +65,12 @@ public SendAnimationArgs(string chatId, string animation) : base(chatId) [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public object Animation { get; set; } /// + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + /// + [JsonPropertyName(PropertyNames.MessageThreadId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? MessageThreadId { get; set; } + /// /// Duration of sent animation in seconds /// [JsonPropertyName(PropertyNames.Duration)] @@ -104,23 +118,28 @@ public SendAnimationArgs(string chatId, string animation) : base(chatId) [JsonPropertyName(PropertyNames.HasSpoiler)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? HasSpoiler { get; set; } - - /// - [System.Text.Json.Serialization.JsonIgnore] - public IEnumerable AttachedFiles { get; set; } = new HashSet(); - - bool IMultipartForm.UseMultipart() - { - if (this.Animation != default && this.Animation.GetType() == typeof(InputFile)) - { - return true; - } - - if (this.Thumbnail != default && this.Thumbnail.GetType() == typeof(InputFile)) - { - return true; - } - - return this.AttachedFiles.Any(); - } + /// + /// Sends the message silently. Users will receive a notification with no sound. + /// + [JsonPropertyName(PropertyNames.DisableNotification)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? DisableNotification { get; set; } + /// + /// Protects the contents of the sent message from forwarding and saving + /// + [JsonPropertyName(PropertyNames.ProtectContent)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? ProtectContent { get; set; } + /// + /// Description of the message to reply to + /// + [JsonPropertyName(PropertyNames.ReplyParameters)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyParameters? ReplyParameters { get; set; } + /// + /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. + /// + [JsonPropertyName(PropertyNames.ReplyMarkup)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyMarkup? ReplyMarkup { get; set; } } diff --git a/src/library/Telegram.BotAPI/Available Methods/Args/SendAttachedFilesArgsBase.cs b/src/library/Telegram.BotAPI/Available Methods/Args/SendAttachedFilesArgsBase.cs new file mode 100644 index 00000000..42654632 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Methods/Args/SendAttachedFilesArgsBase.cs @@ -0,0 +1,20 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.AvailableMethods; + +/// +/// Defines a property to send attached files through multipart/form-data. +/// +/// List of attached files to send. +public abstract class AttachedFilesArgsBase(IEnumerable? attachedFiles = null) +{ + /// + /// List of files to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. + /// + [JsonIgnore] + [Newtonsoft.Json.JsonIgnore] + public IEnumerable AttachedFiles { get; set; } = attachedFiles ?? new List(); +} diff --git a/src/Telegram.BotAPI/Available Methods/Args/SendAudioArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/SendAudioArgs.cs similarity index 55% rename from src/Telegram.BotAPI/Available Methods/Args/SendAudioArgs.cs rename to src/library/Telegram.BotAPI/Available Methods/Args/SendAudioArgs.cs index 8ffe01b2..5590fb90 100644 --- a/src/Telegram.BotAPI/Available Methods/Args/SendAudioArgs.cs +++ b/src/library/Telegram.BotAPI/Available Methods/Args/SendAudioArgs.cs @@ -1,9 +1,8 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; using Newtonsoft.Json.Serialization; -using System.Linq; using Telegram.BotAPI.AvailableTypes; @@ -11,92 +10,127 @@ namespace Telegram.BotAPI.AvailableMethods; /// SendAudio method arguments. [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class SendAudioArgs : SendMessageWithReplyMarkupBase, ICaption, IFormattableMessage, IMultipartForm, IThumbnail +public class SendAudioArgs : AttachedFilesArgsBase { /// Initialize a new instance of . /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. /// - public SendAudioArgs(long chatId, InputFile audio) : base(chatId) + public SendAudioArgs(long chatId, InputFile audio) { + this.ChatId = chatId; this.Audio = audio ?? throw new ArgumentNullException(nameof(audio)); } /// Initialize a new instance of . /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. /// - public SendAudioArgs(long chatId, string audio) : base(chatId) + public SendAudioArgs(long chatId, string audio) { + this.ChatId = chatId; this.Audio = audio ?? throw new ArgumentNullException(nameof(audio)); } /// Initialize a new instance of . /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. /// - public SendAudioArgs(string chatId, InputFile audio) : base(chatId) + public SendAudioArgs(string chatId, InputFile audio) { + this.ChatId = chatId; this.Audio = audio ?? throw new ArgumentNullException(nameof(audio)); } /// Initialize a new instance of . /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. /// - public SendAudioArgs(string chatId, string audio) : base(chatId) + public SendAudioArgs(string chatId, string audio) { + this.ChatId = chatId; this.Audio = audio ?? throw new ArgumentNullException(nameof(audio)); } /// - /// Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object ChatId { get; set; } + /// + /// Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files » /// [JsonPropertyName(PropertyNames.Audio)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public object Audio { get; } - /// Audio caption, 0-1024 characters + public object Audio { get; set; } + /// + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + /// + [JsonPropertyName(PropertyNames.MessageThreadId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? MessageThreadId { get; set; } + /// + /// Audio caption, 0-1024 characters after entities parsing + /// [JsonPropertyName(PropertyNames.Caption)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? Caption { get; set; } - /// Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. + /// + /// Mode for parsing entities in the audio caption. See formatting options for more details. + /// [JsonPropertyName(PropertyNames.ParseMode)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? ParseMode { get; set; } - /// Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode. + /// + /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode + /// [JsonPropertyName(PropertyNames.CaptionEntities)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public IEnumerable? CaptionEntities { get; set; } - /// Optional. Duration of the audio in seconds. + /// + /// Duration of the audio in seconds + /// [JsonPropertyName(PropertyNames.Duration)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public uint? Duration { get; set; } - /// Optional. Performer. + /// + /// Performer + /// [JsonPropertyName(PropertyNames.Performer)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? Performer { get; set; } - /// Optional. Track name. + /// + /// Track name + /// [JsonPropertyName(PropertyNames.Title)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? Title { get; set; } - /// Optional. InputFile or String. Thumbnail of the file sent. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail‘s width and height should not exceed 90. Ignored if the file is not uploaded using multipart/form-data. + /// + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files » + /// [JsonPropertyName(PropertyNames.Thumbnail)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public object? Thumbnail { get; set; } - - /// - [System.Text.Json.Serialization.JsonIgnore] - public IEnumerable AttachedFiles { get; set; } = new HashSet(); - - bool IMultipartForm.UseMultipart() - { - if (this.Audio != default && this.Audio.GetType() == typeof(InputFile)) - { - return true; - } - - if (this.Thumbnail != default && this.Thumbnail.GetType() == typeof(InputFile)) - { - return true; - } - - return this.AttachedFiles.Any(); - } + /// + /// Sends the message silently. Users will receive a notification with no sound. + /// + [JsonPropertyName(PropertyNames.DisableNotification)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? DisableNotification { get; set; } + /// + /// Protects the contents of the sent message from forwarding and saving + /// + [JsonPropertyName(PropertyNames.ProtectContent)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? ProtectContent { get; set; } + /// + /// Description of the message to reply to + /// + [JsonPropertyName(PropertyNames.ReplyParameters)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyParameters? ReplyParameters { get; set; } + /// + /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. + /// + [JsonPropertyName(PropertyNames.ReplyMarkup)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyMarkup? ReplyMarkup { get; set; } } diff --git a/src/library/Telegram.BotAPI/Available Methods/Args/SendContactArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/SendContactArgs.cs new file mode 100644 index 00000000..7a7305e7 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Methods/Args/SendContactArgs.cs @@ -0,0 +1,101 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.AvailableMethods; + +/// SendContact method arguments. +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class SendContactArgs +{ + /// + /// Initialize a new instance of . + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Contact's phone number. + /// Contact's first name. + /// + public SendContactArgs(long chatId, string phoneNumber, string firstName) + { + this.ChatId = chatId; + this.PhoneNumber = phoneNumber ?? throw new ArgumentNullException(nameof(phoneNumber)); + this.FirstName = firstName ?? throw new ArgumentNullException(nameof(firstName)); + } + /// + /// Initialize a new instance of . + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Contact's phone number. + /// Contact's first name. + /// + public SendContactArgs(string chatId, string phoneNumber, string firstName) + { + this.ChatId = chatId ?? throw new ArgumentNullException(nameof(chatId)); + this.PhoneNumber = phoneNumber ?? throw new ArgumentNullException(nameof(phoneNumber)); + this.FirstName = firstName ?? throw new ArgumentNullException(nameof(firstName)); + } + + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object ChatId { get; set; } + /// + /// Contact's phone number + /// + [JsonPropertyName(PropertyNames.PhoneNumber)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string PhoneNumber { get; set; } + /// + /// Contact's first name + /// + [JsonPropertyName(PropertyNames.FirstName)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string FirstName { get; set; } + /// + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + /// + [JsonPropertyName(PropertyNames.MessageThreadId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? MessageThreadId { get; set; } + /// + /// Contact's last name + /// + [JsonPropertyName(PropertyNames.LastName)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? LastName { get; set; } + /// + /// Additional data about the contact in the form of a vCard, 0-2048 bytes + /// + [JsonPropertyName(PropertyNames.Vcard)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? Vcard { get; set; } + /// + /// Sends the message silently. Users will receive a notification with no sound. + /// + [JsonPropertyName(PropertyNames.DisableNotification)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? DisableNotification { get; set; } + /// + /// Protects the contents of the sent message from forwarding and saving + /// + [JsonPropertyName(PropertyNames.ProtectContent)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? ProtectContent { get; set; } + /// + /// Description of the message to reply to + /// + [JsonPropertyName(PropertyNames.ReplyParameters)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyParameters? ReplyParameters { get; set; } + /// + /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. + /// + [JsonPropertyName(PropertyNames.ReplyMarkup)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyMarkup? ReplyMarkup { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Available Methods/Args/SendDiceArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/SendDiceArgs.cs new file mode 100644 index 00000000..8ed255bf --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Methods/Args/SendDiceArgs.cs @@ -0,0 +1,75 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.AvailableMethods; + +/// SendDice method arguments. +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class SendDiceArgs +{ + /// + /// Initialize a new instance of . + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// + public SendDiceArgs(long chatId) + { + this.ChatId = chatId; + } + /// + /// Initialize a new instance of . + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// + public SendDiceArgs(string chatId) + { + this.ChatId = chatId ?? throw new ArgumentNullException(nameof(chatId)); + } + + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object ChatId { get; set; } + /// + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + /// + [JsonPropertyName(PropertyNames.MessageThreadId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? MessageThreadId { get; set; } + /// + /// Emoji on which the dice throw animation is based. Currently, must be one of “”, “”, “”, “”, “”, or “”. Dice can have values 1-6 for “”, “” and “”, values 1-5 for “” and “”, and values 1-64 for “”. Defaults to “” + /// + [JsonPropertyName(PropertyNames.Emoji)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? Emoji { get; set; } + /// + /// Sends the message silently. Users will receive a notification with no sound. + /// + [JsonPropertyName(PropertyNames.DisableNotification)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? DisableNotification { get; set; } + /// + /// Protects the contents of the sent message from forwarding + /// + [JsonPropertyName(PropertyNames.ProtectContent)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? ProtectContent { get; set; } + /// + /// Description of the message to reply to + /// + [JsonPropertyName(PropertyNames.ReplyParameters)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyParameters? ReplyParameters { get; set; } + /// + /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. + /// + [JsonPropertyName(PropertyNames.ReplyMarkup)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyMarkup? ReplyMarkup { get; set; } +} diff --git a/src/Telegram.BotAPI/Available Methods/Args/SendDocumentArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/SendDocumentArgs.cs similarity index 51% rename from src/Telegram.BotAPI/Available Methods/Args/SendDocumentArgs.cs rename to src/library/Telegram.BotAPI/Available Methods/Args/SendDocumentArgs.cs index 901f8a9c..f0559547 100644 --- a/src/Telegram.BotAPI/Available Methods/Args/SendDocumentArgs.cs +++ b/src/library/Telegram.BotAPI/Available Methods/Args/SendDocumentArgs.cs @@ -1,9 +1,8 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; using Newtonsoft.Json.Serialization; -using System.Linq; using Telegram.BotAPI.AvailableTypes; @@ -11,7 +10,7 @@ namespace Telegram.BotAPI.AvailableMethods; /// SendDocument method arguments. [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class SendDocumentArgs : SendMessageWithReplyMarkupBase, ICaption, IFormattableMessage, IMultipartForm, IThumbnail +public class SendDocumentArgs : AttachedFilesArgsBase { /// /// Initialize a new instance of . @@ -19,8 +18,9 @@ public class SendDocumentArgs : SendMessageWithReplyMarkupBase, ICaption, IForma /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. /// - public SendDocumentArgs(long chatId, InputFile document) : base(chatId) + public SendDocumentArgs(long chatId, InputFile document) { + this.ChatId = chatId; this.Document = document ?? throw new ArgumentNullException(nameof(document)); } /// @@ -29,8 +29,9 @@ public SendDocumentArgs(long chatId, InputFile document) : base(chatId) /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. /// - public SendDocumentArgs(long chatId, string document) : base(chatId) + public SendDocumentArgs(long chatId, string document) { + this.ChatId = chatId; this.Document = document ?? throw new ArgumentNullException(nameof(document)); } /// @@ -39,8 +40,9 @@ public SendDocumentArgs(long chatId, string document) : base(chatId) /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. /// - public SendDocumentArgs(string chatId, InputFile document) : base(chatId) + public SendDocumentArgs(string chatId, InputFile document) { + this.ChatId = chatId; this.Document = document ?? throw new ArgumentNullException(nameof(document)); } /// @@ -49,52 +51,82 @@ public SendDocumentArgs(string chatId, InputFile document) : base(chatId) /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. /// - public SendDocumentArgs(string chatId, string document) : base(chatId) + public SendDocumentArgs(string chatId, string document) { + this.ChatId = chatId; this.Document = document ?? throw new ArgumentNullException(nameof(document)); } - /// File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object ChatId { get; set; } + /// + /// File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files » + /// [JsonPropertyName(PropertyNames.Document)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public object Document { get; } - /// Optional. InputFile or String. Thumbnail of the file sent. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail‘s width and height should not exceed 90. Ignored if the file is not uploaded using multipart/form-data. + public object Document { get; set; } + /// + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + /// + [JsonPropertyName(PropertyNames.MessageThreadId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? MessageThreadId { get; set; } + /// + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files » + /// [JsonPropertyName(PropertyNames.Thumbnail)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public object? Thumbnail { get; set; } - /// Document caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing. + /// + /// Document caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing + /// [JsonPropertyName(PropertyNames.Caption)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? Caption { get; set; } - /// Mode for parsing entities in the document caption. See formatting options for more details. + /// + /// Mode for parsing entities in the document caption. See formatting options for more details. + /// [JsonPropertyName(PropertyNames.ParseMode)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? ParseMode { get; set; } - /// Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode. + /// + /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode + /// [JsonPropertyName(PropertyNames.CaptionEntities)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public IEnumerable? CaptionEntities { get; set; } - /// Optional. Disables automatic server-side content type detection for files uploaded using multipart/form-data. Always true, if the document is sent as part of an album. + /// + /// Disables automatic server-side content type detection for files uploaded using multipart/form-data + /// [JsonPropertyName(PropertyNames.DisableContentTypeDetection)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? DisableContentTypeDetection { get; set; } - - /// - [System.Text.Json.Serialization.JsonIgnore] - public IEnumerable AttachedFiles { get; set; } = new HashSet(); - - bool IMultipartForm.UseMultipart() - { - if (this.Document != default && this.Document.GetType() == typeof(InputFile)) - { - return true; - } - - if (this.Thumbnail != default && this.Thumbnail.GetType() == typeof(InputFile)) - { - return true; - } - - return this.AttachedFiles.Any(); - } + /// + /// Sends the message silently. Users will receive a notification with no sound. + /// + [JsonPropertyName(PropertyNames.DisableNotification)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? DisableNotification { get; set; } + /// + /// Protects the contents of the sent message from forwarding and saving + /// + [JsonPropertyName(PropertyNames.ProtectContent)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? ProtectContent { get; set; } + /// + /// Description of the message to reply to + /// + [JsonPropertyName(PropertyNames.ReplyParameters)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyParameters? ReplyParameters { get; set; } + /// + /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. + /// + [JsonPropertyName(PropertyNames.ReplyMarkup)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyMarkup? ReplyMarkup { get; set; } } diff --git a/src/library/Telegram.BotAPI/Available Methods/Args/SendLocationArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/SendLocationArgs.cs new file mode 100644 index 00000000..d89b2cbd --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Methods/Args/SendLocationArgs.cs @@ -0,0 +1,111 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.AvailableMethods; + +/// SendLocation method arguments. +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class SendLocationArgs +{ + /// + /// Initialize a new instance of . + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Longitude as defined by sender. + /// Latitude as defined by sender. + public SendLocationArgs(long chatId, float longitude, float latitude) + { + this.ChatId = chatId; + this.Longitude = longitude; + this.Latitude = latitude; + } + /// + /// Initialize a new instance of . + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Longitude as defined by sender. + /// Latitude as defined by sender. + public SendLocationArgs(string chatId, float longitude, float latitude) + { + this.ChatId = chatId; + this.Longitude = longitude; + this.Latitude = latitude; + } + + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object ChatId { get; set; } + /// + /// Latitude of the location + /// + [JsonPropertyName(PropertyNames.Latitude)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public float Latitude { get; set; } + /// + /// Longitude of the location + /// + [JsonPropertyName(PropertyNames.Longitude)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public float Longitude { get; set; } + /// + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + /// + [JsonPropertyName(PropertyNames.MessageThreadId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? MessageThreadId { get; set; } + /// + /// The radius of uncertainty for the location, measured in meters; 0-1500 + /// + [JsonPropertyName(PropertyNames.HorizontalAccuracy)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public float? HorizontalAccuracy { get; set; } + /// + /// Period in seconds for which the location will be updated (see Live Locations, should be between 60 and 86400. + /// + [JsonPropertyName(PropertyNames.LivePeriod)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public uint? LivePeriod { get; set; } + /// + /// For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. + /// + [JsonPropertyName(PropertyNames.Heading)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ushort? Heading { get; set; } + /// + /// For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. + /// + [JsonPropertyName(PropertyNames.ProximityAlertRadius)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public uint? ProximityAlertRadius { get; set; } + /// + /// Sends the message silently. Users will receive a notification with no sound. + /// + [JsonPropertyName(PropertyNames.DisableNotification)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? DisableNotification { get; set; } + /// + /// Protects the contents of the sent message from forwarding and saving + /// + [JsonPropertyName(PropertyNames.ProtectContent)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? ProtectContent { get; set; } + /// + /// Description of the message to reply to + /// + [JsonPropertyName(PropertyNames.ReplyParameters)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyParameters? ReplyParameters { get; set; } + /// + /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. + /// + [JsonPropertyName(PropertyNames.ReplyMarkup)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyMarkup? ReplyMarkup { get; set; } +} diff --git a/src/Telegram.BotAPI/Available Methods/Args/SendMediaGroupArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/SendMediaGroupArgs.cs similarity index 51% rename from src/Telegram.BotAPI/Available Methods/Args/SendMediaGroupArgs.cs rename to src/library/Telegram.BotAPI/Available Methods/Args/SendMediaGroupArgs.cs index c9e89b67..dc082405 100644 --- a/src/Telegram.BotAPI/Available Methods/Args/SendMediaGroupArgs.cs +++ b/src/library/Telegram.BotAPI/Available Methods/Args/SendMediaGroupArgs.cs @@ -1,24 +1,24 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; using Newtonsoft.Json.Serialization; -using System.Linq; using Telegram.BotAPI.AvailableTypes; namespace Telegram.BotAPI.AvailableMethods; /// SendMediaGroud method arguments. [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class SendMediaGroupArgs : SendMessageBase, IMultipartForm +public class SendMediaGroupArgs : AttachedFilesArgsBase { /// /// Initialize a new instance of . /// /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// An array of , , and describing messages to be sent, must include 2-10 items. - public SendMediaGroupArgs(long chatId, IEnumerable media) : base(chatId) + public SendMediaGroupArgs(long chatId, IEnumerable media) { + this.ChatId = chatId; this.Media = new HashSet(media ?? throw new ArgumentNullException(nameof(media))); } /// @@ -26,22 +26,46 @@ public SendMediaGroupArgs(long chatId, IEnumerable media) : base(cha /// /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// An array of , , and describing messages to be sent, must include 2-10 items. - public SendMediaGroupArgs(string chatId, IEnumerable media) : base(chatId) + public SendMediaGroupArgs(string chatId, IEnumerable media) { + this.ChatId = chatId; this.Media = new HashSet(media ?? throw new ArgumentNullException(nameof(media))); } - /// An array of , , and describing messages to be sent, must include 2-10 items. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object ChatId { get; set; } + /// + /// A JSON-serialized array describing messages to be sent, must include 2-10 items + /// [JsonPropertyName(PropertyNames.Media)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public ICollection Media { get; } - - /// - [System.Text.Json.Serialization.JsonIgnore] - public IEnumerable AttachedFiles { get; set; } = new HashSet(); - - bool IMultipartForm.UseMultipart() - { - return this.AttachedFiles.Any(); - } + public IEnumerable Media { get; set; } + /// + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + /// + [JsonPropertyName(PropertyNames.MessageThreadId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? MessageThreadId { get; set; } + /// + /// Sends messages silently. Users will receive a notification with no sound. + /// + [JsonPropertyName(PropertyNames.DisableNotification)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? DisableNotification { get; set; } + /// + /// Protects the contents of the sent messages from forwarding and saving + /// + [JsonPropertyName(PropertyNames.ProtectContent)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? ProtectContent { get; set; } + /// + /// Description of the message to reply to + /// + [JsonPropertyName(PropertyNames.ReplyParameters)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyParameters? ReplyParameters { get; set; } } diff --git a/src/library/Telegram.BotAPI/Available Methods/Args/SendMessageArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/SendMessageArgs.cs new file mode 100644 index 00000000..0d82235c --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Methods/Args/SendMessageArgs.cs @@ -0,0 +1,92 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using Telegram.BotAPI.AvailableTypes; + + +namespace Telegram.BotAPI.AvailableMethods; + +/// SendMessage method arguments. +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class SendMessageArgs +{ + /// Initialize a new instance of . + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Text of the message to be sent. + public SendMessageArgs(long chatId, string text) + { + this.ChatId = chatId; + this.Text = text; + } + /// Initialize a new instance of . + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Text of the message to be sent. + public SendMessageArgs(string chatId, string text) + { + this.ChatId = chatId; + this.Text = text; + } + + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object ChatId { get; set; } + /// + /// Text of the message to be sent, 1-4096 characters after entities parsing + /// + [JsonPropertyName(PropertyNames.Text)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string Text { get; set; } + /// + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + /// + [JsonPropertyName(PropertyNames.MessageThreadId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? MessageThreadId { get; set; } + /// + /// Mode for parsing entities in the message text. See formatting options for more details. + /// + [JsonPropertyName(PropertyNames.ParseMode)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? ParseMode { get; set; } + /// + /// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode + /// + [JsonPropertyName(PropertyNames.Entities)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public IEnumerable? Entities { get; set; } + /// + /// Link preview generation options for the message + /// + [JsonPropertyName(PropertyNames.LinkPreviewOptions)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public LinkPreviewOptions? LinkPreviewOptions { get; set; } + /// + /// Sends the message silently. Users will receive a notification with no sound. + /// + [JsonPropertyName(PropertyNames.DisableNotification)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? DisableNotification { get; set; } + /// + /// Protects the contents of the sent message from forwarding and saving + /// + [JsonPropertyName(PropertyNames.ProtectContent)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? ProtectContent { get; set; } + /// + /// Description of the message to reply to + /// + [JsonPropertyName(PropertyNames.ReplyParameters)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyParameters? ReplyParameters { get; set; } + /// + /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. + /// + [JsonPropertyName(PropertyNames.ReplyMarkup)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyMarkup? ReplyMarkup { get; set; } +} diff --git a/src/Telegram.BotAPI/Available Methods/Args/SendPhotoArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/SendPhotoArgs.cs similarity index 53% rename from src/Telegram.BotAPI/Available Methods/Args/SendPhotoArgs.cs rename to src/library/Telegram.BotAPI/Available Methods/Args/SendPhotoArgs.cs index 53754b2f..8fd21582 100644 --- a/src/Telegram.BotAPI/Available Methods/Args/SendPhotoArgs.cs +++ b/src/library/Telegram.BotAPI/Available Methods/Args/SendPhotoArgs.cs @@ -1,25 +1,24 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; using Newtonsoft.Json.Serialization; -using System.Linq; using Telegram.BotAPI.AvailableTypes; - namespace Telegram.BotAPI.AvailableMethods; /// SendPhoto method arguments [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class SendPhotoArgs : SendMessageWithReplyMarkupBase, ICaption, IFormattableMessage, IMultipartForm +public class SendPhotoArgs : AttachedFilesArgsBase { /// /// Initialize a new isntance of . /// /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// InputFile or String. Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. - public SendPhotoArgs(long chatId, InputFile photo) : base(chatId) + public SendPhotoArgs(long chatId, InputFile photo) { + this.ChatId = chatId; this.Photo = photo; } @@ -28,8 +27,9 @@ public SendPhotoArgs(long chatId, InputFile photo) : base(chatId) /// /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// InputFile or String. Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. - public SendPhotoArgs(string chatId, InputFile photo) : base(chatId) + public SendPhotoArgs(string chatId, InputFile photo) { + this.ChatId = chatId; this.Photo = photo; } @@ -38,8 +38,9 @@ public SendPhotoArgs(string chatId, InputFile photo) : base(chatId) /// /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// InputFile or String. Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. - public SendPhotoArgs(long chatId, string photo) : base(chatId) + public SendPhotoArgs(long chatId, string photo) { + this.ChatId = chatId; this.Photo = photo; } @@ -48,26 +49,45 @@ public SendPhotoArgs(long chatId, string photo) : base(chatId) /// /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// InputFile or String. Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. - public SendPhotoArgs(string chatId, string photo) : base(chatId) + public SendPhotoArgs(string chatId, string photo) { + this.ChatId = chatId; this.Photo = photo; } /// - /// InputFile or String. Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object ChatId { get; set; } + /// + /// Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More information on Sending Files » /// [JsonPropertyName(PropertyNames.Photo)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public object Photo { get; } - /// Optional. Photo caption (may also be used when resending photos by file_id), 0-1024 characters. + public object Photo { get; set; } + /// + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + /// + [JsonPropertyName(PropertyNames.MessageThreadId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? MessageThreadId { get; set; } + /// + /// Photo caption (may also be used when resending photos by file_id), 0-1024 characters after entities parsing + /// [JsonPropertyName(PropertyNames.Caption)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? Caption { get; set; } - /// Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. + /// + /// Mode for parsing entities in the photo caption. See formatting options for more details. + /// [JsonPropertyName(PropertyNames.ParseMode)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? ParseMode { get; set; } - /// Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode. + /// + /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode + /// [JsonPropertyName(PropertyNames.CaptionEntities)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public IEnumerable? CaptionEntities { get; set; } @@ -77,21 +97,28 @@ public SendPhotoArgs(string chatId, string photo) : base(chatId) [JsonPropertyName(PropertyNames.HasSpoiler)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? HasSpoiler { get; set; } - - /// - [System.Text.Json.Serialization.JsonIgnore] - public IEnumerable AttachedFiles { get; set; } = new HashSet(); - - bool IMultipartForm.UseMultipart() - { - if (this.Photo != default) - { - if (this.Photo.GetType() == typeof(InputFile)) - { - return true; - } - } - - return AttachedFiles.Any(); - } + /// + /// Sends the message silently. Users will receive a notification with no sound. + /// + [JsonPropertyName(PropertyNames.DisableNotification)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? DisableNotification { get; set; } + /// + /// Protects the contents of the sent message from forwarding and saving + /// + [JsonPropertyName(PropertyNames.ProtectContent)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? ProtectContent { get; set; } + /// + /// Description of the message to reply to + /// + [JsonPropertyName(PropertyNames.ReplyParameters)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyParameters? ReplyParameters { get; set; } + /// + /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. + /// + [JsonPropertyName(PropertyNames.ReplyMarkup)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyMarkup? ReplyMarkup { get; set; } } diff --git a/src/library/Telegram.BotAPI/Available Methods/Args/SendPollArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/SendPollArgs.cs new file mode 100644 index 00000000..c139f642 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Methods/Args/SendPollArgs.cs @@ -0,0 +1,149 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.AvailableMethods; + +/// SendPoll method arguments. +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class SendPollArgs +{ + /// + /// Initialize a new instance of . + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Poll question, 1-300 characters. + /// List of answer options, 2-10 strings 1-100 characters each. + /// + public SendPollArgs(long chatId, string question, IEnumerable options) + { + this.ChatId = chatId; + this.Question = question ?? throw new ArgumentNullException(nameof(question)); + this.Options = options ?? throw new ArgumentNullException(nameof(options)); + } + /// + /// Initialize a new instance of . + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Poll question, 1-300 characters. + /// List of answer options, 2-10 strings 1-100 characters each. + /// + public SendPollArgs(string chatId, string question, IEnumerable options) + { + this.ChatId = chatId ?? throw new ArgumentNullException(nameof(chatId)); + this.Question = question ?? throw new ArgumentNullException(nameof(question)); + this.Options = options ?? throw new ArgumentNullException(nameof(options)); + } + + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object ChatId { get; set; } + /// + /// Poll question, 1-300 characters + /// + [JsonPropertyName(PropertyNames.Question)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string Question { get; set; } + /// + /// A JSON-serialized list of answer options, 2-10 strings 1-100 characters each + /// + [JsonPropertyName(PropertyNames.Options)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public IEnumerable Options { get; set; } + /// + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + /// + [JsonPropertyName(PropertyNames.MessageThreadId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? MessageThreadId { get; set; } + /// + /// True, if the poll needs to be anonymous, defaults to True + /// + [JsonPropertyName(PropertyNames.IsAnonymous)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? IsAnonymous { get; set; } + /// + /// Poll type, “quiz” or “regular”, defaults to “regular” + /// + [JsonPropertyName(PropertyNames.Type)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? Type { get; set; } + /// + /// True, if the poll allows multiple answers, ignored for polls in quiz mode, defaults to False + /// + [JsonPropertyName(PropertyNames.AllowsMultipleAnswers)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? AllowsMultipleAnswers { get; set; } + /// + /// 0-based identifier of the correct answer option, required for polls in quiz mode + /// + [JsonPropertyName(PropertyNames.CorrectOptionId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public uint? CorrectOptionId { get; set; } + /// + /// Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing + /// + [JsonPropertyName(PropertyNames.Explanation)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? Explanation { get; set; } + /// + /// Mode for parsing entities in the explanation. See formatting options for more details. + /// + [JsonPropertyName(PropertyNames.ExplanationParseMode)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? ExplanationParseMode { get; set; } + /// + /// A JSON-serialized list of special entities that appear in the poll explanation, which can be specified instead of parse_mode + /// + [JsonPropertyName(PropertyNames.ExplanationEntities)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public IEnumerable? ExplanationEntities { get; set; } + /// + /// Amount of time in seconds the poll will be active after creation, 5-600. Can't be used together with close_date. + /// + [JsonPropertyName(PropertyNames.OpenPeriod)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? OpenPeriod { get; set; } + /// + /// Point in time (Unix timestamp) when the poll will be automatically closed. Must be at least 5 and no more than 600 seconds in the future. Can't be used together with open_period. + /// + [JsonPropertyName(PropertyNames.CloseDate)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public uint? CloseDate { get; set; } + /// + /// Pass True if the poll needs to be immediately closed. This can be useful for poll preview. + /// + [JsonPropertyName(PropertyNames.IsClosed)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? IsClosed { get; set; } + /// + /// Sends the message silently. Users will receive a notification with no sound. + /// + [JsonPropertyName(PropertyNames.DisableNotification)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? DisableNotification { get; set; } + /// + /// Protects the contents of the sent message from forwarding and saving + /// + [JsonPropertyName(PropertyNames.ProtectContent)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? ProtectContent { get; set; } + /// + /// Description of the message to reply to + /// + [JsonPropertyName(PropertyNames.ReplyParameters)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyParameters? ReplyParameters { get; set; } + /// + /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. + /// + [JsonPropertyName(PropertyNames.ReplyMarkup)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyMarkup? ReplyMarkup { get; set; } +} diff --git a/src/Telegram.BotAPI/Available Methods/Args/SendVenueArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/SendVenueArgs.cs similarity index 52% rename from src/Telegram.BotAPI/Available Methods/Args/SendVenueArgs.cs rename to src/library/Telegram.BotAPI/Available Methods/Args/SendVenueArgs.cs index b0f61699..8dbf69f8 100644 --- a/src/Telegram.BotAPI/Available Methods/Args/SendVenueArgs.cs +++ b/src/library/Telegram.BotAPI/Available Methods/Args/SendVenueArgs.cs @@ -1,15 +1,16 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; using Newtonsoft.Json.Serialization; +using Telegram.BotAPI.AvailableTypes; namespace Telegram.BotAPI.AvailableMethods; /// Send Venue. [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class SendVenueArgs : SendMessageWithReplyMarkupBase, IVenue +public class SendVenueArgs { /// /// Initialize a new instance of . @@ -20,8 +21,9 @@ public class SendVenueArgs : SendMessageWithReplyMarkupBase, IVenue /// Name of the venue. /// Address of the venue. /// - public SendVenueArgs(long chatId, float latitude, float longitude, string title, string address) : base(chatId) + public SendVenueArgs(long chatId, float latitude, float longitude, string title, string address) { + this.ChatId = chatId; this.Latitude = latitude; this.Longitude = longitude; this.Title = title ?? throw new ArgumentNullException(nameof(title)); @@ -37,44 +39,97 @@ public SendVenueArgs(long chatId, float latitude, float longitude, string title, /// Name of the venue. /// Address of the venue. /// - public SendVenueArgs(string chatId, float latitude, float longitude, string title, string address) : base(chatId) + public SendVenueArgs(string chatId, float latitude, float longitude, string title, string address) { + this.ChatId = chatId; this.Latitude = latitude; this.Longitude = longitude; this.Title = title ?? throw new ArgumentNullException(nameof(title)); this.Address = address ?? throw new ArgumentNullException(nameof(address)); } - /// Latitude of the venue. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object ChatId { get; set; } + /// + /// Latitude of the venue + /// [JsonPropertyName(PropertyNames.Latitude)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public float Latitude { get; } - /// Longitude of the venue. + public float Latitude { get; set; } + /// + /// Longitude of the venue + /// [JsonPropertyName(PropertyNames.Longitude)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public float Longitude { get; } - /// Name of the venue. + public float Longitude { get; set; } + /// + /// Name of the venue + /// [JsonPropertyName(PropertyNames.Title)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string Title { get; } - /// Address of the venue. + public string Title { get; set; } + /// + /// Address of the venue + /// [JsonPropertyName(PropertyNames.Address)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string Address { get; } - /// Optional. Foursquare identifier of the venue. + public string Address { get; set; } + /// + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + /// + [JsonPropertyName(PropertyNames.MessageThreadId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? MessageThreadId { get; set; } + /// + /// Foursquare identifier of the venue + /// [JsonPropertyName(PropertyNames.FoursquareId)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? FoursquareId { get; set; } - /// Optional. Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”). + /// + /// Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.) + /// [JsonPropertyName(PropertyNames.FoursquareType)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? FoursquareType { get; set; } - /// Optional. Google Places identifier of the venue. + /// + /// Google Places identifier of the venue + /// [JsonPropertyName(PropertyNames.GooglePlaceId)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? GooglePlaceId { get; set; } - /// Optional. Google Places type of the venue. (See supported types.) + /// + /// Google Places type of the venue. (See supported types.) + /// [JsonPropertyName(PropertyNames.GooglePlaceType)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? GooglePlaceType { get; set; } + /// + /// Sends the message silently. Users will receive a notification with no sound. + /// + [JsonPropertyName(PropertyNames.DisableNotification)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? DisableNotification { get; set; } + /// + /// Protects the contents of the sent message from forwarding and saving + /// + [JsonPropertyName(PropertyNames.ProtectContent)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? ProtectContent { get; set; } + /// + /// Description of the message to reply to + /// + [JsonPropertyName(PropertyNames.ReplyParameters)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyParameters? ReplyParameters { get; set; } + /// + /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. + /// + [JsonPropertyName(PropertyNames.ReplyMarkup)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyMarkup? ReplyMarkup { get; set; } } diff --git a/src/Telegram.BotAPI/Available Methods/Args/SendVideoArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/SendVideoArgs.cs similarity index 56% rename from src/Telegram.BotAPI/Available Methods/Args/SendVideoArgs.cs rename to src/library/Telegram.BotAPI/Available Methods/Args/SendVideoArgs.cs index 7223bf0c..3bc0f64c 100644 --- a/src/Telegram.BotAPI/Available Methods/Args/SendVideoArgs.cs +++ b/src/library/Telegram.BotAPI/Available Methods/Args/SendVideoArgs.cs @@ -1,9 +1,8 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; using Newtonsoft.Json.Serialization; -using System.Linq; using Telegram.BotAPI.AvailableTypes; @@ -11,114 +10,135 @@ namespace Telegram.BotAPI.AvailableMethods; /// SendVideo method arguments. [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class SendVideoArgs : SendMessageWithReplyMarkupBase, ICaption, IFormattableMessage, IMultipartForm +public class SendVideoArgs : AttachedFilesArgsBase { /// Initialize a new instance of . /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. - public SendVideoArgs(long chatId, InputFile video) : base(chatId) + public SendVideoArgs(long chatId, InputFile video) { + this.ChatId = chatId; this.Video = video; } /// Initialize a new instance of . /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. - public SendVideoArgs(long chatId, string video) : base(chatId) + public SendVideoArgs(long chatId, string video) { + this.ChatId = chatId; this.Video = video; } /// Initialize a new instance of . /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. - public SendVideoArgs(string chatId, InputFile video) : base(chatId) + public SendVideoArgs(string chatId, InputFile video) { + this.ChatId = chatId; this.Video = video; } /// Initialize a new instance of . /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. - public SendVideoArgs(string chatId, string video) : base(chatId) + public SendVideoArgs(string chatId, string video) { + this.ChatId = chatId; this.Video = video; } /// - /// Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. More information on Sending Files » + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object ChatId { get; set; } + /// + /// Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. More information on Sending Files » /// [JsonPropertyName(PropertyNames.Video)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public object Video { get; } + public object Video { get; set; } + /// + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + /// + [JsonPropertyName(PropertyNames.MessageThreadId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? MessageThreadId { get; set; } /// - /// Optional. Duration of sent video in seconds + /// Duration of sent video in seconds /// [JsonPropertyName(PropertyNames.Duration)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public uint? Duration { get; set; } /// - /// Optional. Video width + /// Video width /// [JsonPropertyName(PropertyNames.Width)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public uint? Width { get; set; } /// - /// Optional. Video height + /// Video height /// [JsonPropertyName(PropertyNames.Height)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public uint? Height { get; set; } /// - /// Optional. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files » + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files » /// [JsonPropertyName(PropertyNames.Thumbnail)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public object? Thumbnail { get; set; } /// - /// Optional. Video caption (may also be used when resending videos by file_id), 0-1024 characters after entities parsing + /// Video caption (may also be used when resending videos by file_id), 0-1024 characters after entities parsing /// [JsonPropertyName(PropertyNames.Caption)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? Caption { get; set; } /// - /// Optional. Mode for parsing entities in the video caption. See formatting options for more details. + /// Mode for parsing entities in the video caption. See formatting options for more details. /// [JsonPropertyName(PropertyNames.ParseMode)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? ParseMode { get; set; } /// - /// Optional. A list of special entities that appear in the caption, which can be specified instead of parse_mode. + /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode /// [JsonPropertyName(PropertyNames.CaptionEntities)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public IEnumerable? CaptionEntities { get; set; } /// - /// Optional. Pass True if the video needs to be covered with a spoiler animation + /// Pass True if the video needs to be covered with a spoiler animation /// [JsonPropertyName(PropertyNames.HasSpoiler)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? HasSpoiler { get; set; } /// - /// Optional. Pass True if the uploaded video is suitable for streaming + /// Pass True if the uploaded video is suitable for streaming /// [JsonPropertyName(PropertyNames.SupportsStreaming)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? SupportsStreaming { get; set; } - - /// - [System.Text.Json.Serialization.JsonIgnore] - public IEnumerable AttachedFiles { get; set; } = new HashSet(); - - bool IMultipartForm.UseMultipart() - { - if (this.Video != default && this.Video.GetType() == typeof(InputFile)) - { - return true; - } - - if (this.Thumbnail != default && this.Thumbnail.GetType() == typeof(InputFile)) - { - return true; - } - - return this.AttachedFiles.Any(); - } + /// + /// Sends the message silently. Users will receive a notification with no sound. + /// + [JsonPropertyName(PropertyNames.DisableNotification)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? DisableNotification { get; set; } + /// + /// Protects the contents of the sent message from forwarding and saving + /// + [JsonPropertyName(PropertyNames.ProtectContent)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? ProtectContent { get; set; } + /// + /// Description of the message to reply to + /// + [JsonPropertyName(PropertyNames.ReplyParameters)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyParameters? ReplyParameters { get; set; } + /// + /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. + /// + [JsonPropertyName(PropertyNames.ReplyMarkup)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyMarkup? ReplyMarkup { get; set; } } diff --git a/src/Telegram.BotAPI/Available Methods/Args/SendVideoNoteArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/SendVideoNoteArgs.cs similarity index 50% rename from src/Telegram.BotAPI/Available Methods/Args/SendVideoNoteArgs.cs rename to src/library/Telegram.BotAPI/Available Methods/Args/SendVideoNoteArgs.cs index 33cf4def..130d39ee 100644 --- a/src/Telegram.BotAPI/Available Methods/Args/SendVideoNoteArgs.cs +++ b/src/library/Telegram.BotAPI/Available Methods/Args/SendVideoNoteArgs.cs @@ -1,17 +1,15 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; using Newtonsoft.Json.Serialization; -using System.Linq; using Telegram.BotAPI.AvailableTypes; - namespace Telegram.BotAPI.AvailableMethods; /// SendVideoNote method arguments. [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class SendVideoNoteArgs : SendMessageWithReplyMarkupBase, IMultipartForm +public class SendVideoNoteArgs : AttachedFilesArgsBase { /// /// Initialize a new instance of . @@ -19,8 +17,9 @@ public class SendVideoNoteArgs : SendMessageWithReplyMarkupBase, IMultipartForm /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. /// - public SendVideoNoteArgs(long chatId, InputFile videoNote) : base(chatId) + public SendVideoNoteArgs(long chatId, InputFile videoNote) { + this.ChatId = chatId; this.VideoNote = videoNote ?? throw new ArgumentNullException(nameof(videoNote)); } /// @@ -29,8 +28,9 @@ public SendVideoNoteArgs(long chatId, InputFile videoNote) : base(chatId) /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. /// - public SendVideoNoteArgs(long chatId, string videoNote) : base(chatId) + public SendVideoNoteArgs(long chatId, string videoNote) { + this.ChatId = chatId; this.VideoNote = videoNote ?? throw new ArgumentNullException(nameof(videoNote)); } /// @@ -39,8 +39,9 @@ public SendVideoNoteArgs(long chatId, string videoNote) : base(chatId) /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. /// - public SendVideoNoteArgs(string chatId, InputFile videoNote) : base(chatId) + public SendVideoNoteArgs(string chatId, InputFile videoNote) { + this.ChatId = chatId; this.VideoNote = videoNote ?? throw new ArgumentNullException(nameof(videoNote)); } /// @@ -49,46 +50,70 @@ public SendVideoNoteArgs(string chatId, InputFile videoNote) : base(chatId) /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. /// - public SendVideoNoteArgs(string chatId, string videoNote) : base(chatId) + public SendVideoNoteArgs(string chatId, string videoNote) { + this.ChatId = chatId; this.VideoNote = videoNote ?? throw new ArgumentNullException(nameof(videoNote)); } - /// Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object ChatId { get; set; } + /// + /// Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ». Sending video notes by a URL is currently unsupported + /// [JsonPropertyName(PropertyNames.VideoNote)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public object VideoNote { get; } - /// Optional. Duration of sent video in seconds. + public object VideoNote { get; set; } + /// + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + /// + [JsonPropertyName(PropertyNames.MessageThreadId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? MessageThreadId { get; set; } + /// + /// Duration of sent video in seconds + /// [JsonPropertyName(PropertyNames.Duration)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public uint? Duration { get; set; } - /// Optional. Video width and height, i.e. diameter of the video message. + /// + /// Video width and height, i.e. diameter of the video message + /// [JsonPropertyName(PropertyNames.Length)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public uint? Length { get; set; } /// - /// Optional. Thumbnail of the file sent. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail‘s width and height should not exceed 90. Ignored if the file is not uploaded using multipart/form-data. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files » /// [JsonPropertyName(PropertyNames.Thumbnail)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public object? Thumbnail { get; set; } - - /// - [System.Text.Json.Serialization.JsonIgnore] - public IEnumerable AttachedFiles { get; set; } = new HashSet(); - - bool IMultipartForm.UseMultipart() - { - if (this.VideoNote != default && this.VideoNote.GetType() == typeof(InputFile)) - { - return true; - } - - if (this.Thumbnail != default && this.Thumbnail.GetType() == typeof(InputFile)) - { - return true; - } - - return this.AttachedFiles.Any(); - } + /// + /// Sends the message silently. Users will receive a notification with no sound. + /// + [JsonPropertyName(PropertyNames.DisableNotification)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? DisableNotification { get; set; } + /// + /// Protects the contents of the sent message from forwarding and saving + /// + [JsonPropertyName(PropertyNames.ProtectContent)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? ProtectContent { get; set; } + /// + /// Description of the message to reply to + /// + [JsonPropertyName(PropertyNames.ReplyParameters)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyParameters? ReplyParameters { get; set; } + /// + /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. + /// + [JsonPropertyName(PropertyNames.ReplyMarkup)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyMarkup? ReplyMarkup { get; set; } } diff --git a/src/Telegram.BotAPI/Available Methods/Args/SendVoiceArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/SendVoiceArgs.cs similarity index 55% rename from src/Telegram.BotAPI/Available Methods/Args/SendVoiceArgs.cs rename to src/library/Telegram.BotAPI/Available Methods/Args/SendVoiceArgs.cs index a40f64e5..51629f6e 100644 --- a/src/Telegram.BotAPI/Available Methods/Args/SendVoiceArgs.cs +++ b/src/library/Telegram.BotAPI/Available Methods/Args/SendVoiceArgs.cs @@ -1,17 +1,15 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; using Newtonsoft.Json.Serialization; -using System.Linq; using Telegram.BotAPI.AvailableTypes; - namespace Telegram.BotAPI.AvailableMethods; /// SendVoice method arguments. [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class SendVoiceArgs : SendMessageWithReplyMarkupBase, ICaption, IFormattableMessage, IMultipartForm +public class SendVoiceArgs : AttachedFilesArgsBase { /// /// Initialize a new instance of . @@ -19,8 +17,9 @@ public class SendVoiceArgs : SendMessageWithReplyMarkupBase, ICaption, IFormatta /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. /// - public SendVoiceArgs(long chatId, InputFile voice) : base(chatId) + public SendVoiceArgs(long chatId, InputFile voice) { + this.ChatId = chatId; this.Voice = voice ?? throw new ArgumentNullException(nameof(voice)); } /// @@ -29,8 +28,9 @@ public SendVoiceArgs(long chatId, InputFile voice) : base(chatId) /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. /// - public SendVoiceArgs(long chatId, string voice) : base(chatId) + public SendVoiceArgs(long chatId, string voice) { + this.ChatId = chatId; this.Voice = voice ?? throw new ArgumentNullException(nameof(voice)); } /// @@ -39,8 +39,9 @@ public SendVoiceArgs(long chatId, string voice) : base(chatId) /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. /// - public SendVoiceArgs(string chatId, InputFile voice) : base(chatId) + public SendVoiceArgs(string chatId, InputFile voice) { + this.ChatId = chatId; this.Voice = voice ?? throw new ArgumentNullException(nameof(voice)); } /// @@ -49,47 +50,76 @@ public SendVoiceArgs(string chatId, InputFile voice) : base(chatId) /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. /// - public SendVoiceArgs(string chatId, string voice) : base(chatId) + public SendVoiceArgs(string chatId, string voice) { + this.ChatId = chatId; this.Voice = voice ?? throw new ArgumentNullException(nameof(voice)); } - /// Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object ChatId { get; set; } + /// + /// Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files » + /// [JsonPropertyName(PropertyNames.Voice)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public object Voice { get; } - /// Voice message caption, 0-1024 characters. + public object Voice { get; set; } + /// + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + /// + [JsonPropertyName(PropertyNames.MessageThreadId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? MessageThreadId { get; set; } + /// + /// Voice message caption, 0-1024 characters after entities parsing + /// [JsonPropertyName(PropertyNames.Caption)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? Caption { get; set; } - /// Optional. Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. + /// + /// Mode for parsing entities in the voice message caption. See formatting options for more details. + /// [JsonPropertyName(PropertyNames.ParseMode)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? ParseMode { get; set; } - /// Optional. List of special entities that appear in the caption, which can be specified instead of parse_mode. + /// + /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode + /// [JsonPropertyName(PropertyNames.CaptionEntities)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public IEnumerable? CaptionEntities { get; set; } - /// Optional. Duration of the voice message in seconds. + /// + /// Duration of the voice message in seconds + /// [JsonPropertyName(PropertyNames.Duration)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public uint? Duration { get; set; } - - /// - [System.Text.Json.Serialization.JsonIgnore] - public IEnumerable AttachedFiles { get; set; } = new HashSet(); - - /// Attached files. - bool IMultipartForm.UseMultipart() - { - if (this.Voice != default) - { - if (this.Voice.GetType() == typeof(InputFile)) - { - return true; - } - } - - return this.AttachedFiles.Any(); - } + /// + /// Sends the message silently. Users will receive a notification with no sound. + /// + [JsonPropertyName(PropertyNames.DisableNotification)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? DisableNotification { get; set; } + /// + /// Protects the contents of the sent message from forwarding and saving + /// + [JsonPropertyName(PropertyNames.ProtectContent)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? ProtectContent { get; set; } + /// + /// Description of the message to reply to + /// + [JsonPropertyName(PropertyNames.ReplyParameters)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyParameters? ReplyParameters { get; set; } + /// + /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. + /// + [JsonPropertyName(PropertyNames.ReplyMarkup)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyMarkup? ReplyMarkup { get; set; } } diff --git a/src/Telegram.BotAPI/Available Methods/Args/SetChatMenuButtonArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/SetChatMenuButtonArgs.cs similarity index 96% rename from src/Telegram.BotAPI/Available Methods/Args/SetChatMenuButtonArgs.cs rename to src/library/Telegram.BotAPI/Available Methods/Args/SetChatMenuButtonArgs.cs index ca9d8380..4f70b1ae 100644 --- a/src/Telegram.BotAPI/Available Methods/Args/SetChatMenuButtonArgs.cs +++ b/src/library/Telegram.BotAPI/Available Methods/Args/SetChatMenuButtonArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Methods/Args/SetChatPermissionsArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/SetChatPermissionsArgs.cs similarity index 98% rename from src/Telegram.BotAPI/Available Methods/Args/SetChatPermissionsArgs.cs rename to src/library/Telegram.BotAPI/Available Methods/Args/SetChatPermissionsArgs.cs index 7583ee09..f832d378 100644 --- a/src/Telegram.BotAPI/Available Methods/Args/SetChatPermissionsArgs.cs +++ b/src/library/Telegram.BotAPI/Available Methods/Args/SetChatPermissionsArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Methods/Args/SetChatPhotoArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/SetChatPhotoArgs.cs similarity index 98% rename from src/Telegram.BotAPI/Available Methods/Args/SetChatPhotoArgs.cs rename to src/library/Telegram.BotAPI/Available Methods/Args/SetChatPhotoArgs.cs index 6fc1332e..3ad5e633 100644 --- a/src/Telegram.BotAPI/Available Methods/Args/SetChatPhotoArgs.cs +++ b/src/library/Telegram.BotAPI/Available Methods/Args/SetChatPhotoArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/library/Telegram.BotAPI/Available Methods/Args/SetMessageReactionArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/SetMessageReactionArgs.cs new file mode 100644 index 00000000..f20c6486 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Methods/Args/SetMessageReactionArgs.cs @@ -0,0 +1,62 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// SetMessageReaction method arguments. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class SetMessageReactionArgs +{ + /// + /// Initializes a new instance of SetMessageReactionArgs with required parameters. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// Identifier of the target message + public SetMessageReactionArgs(long chatId, int messageId) + { + this.ChatId = chatId; + this.MessageId = messageId; + } + + /// + /// Initializes a new instance of SetMessageReactionArgs with required parameters. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// Identifier of the target message + public SetMessageReactionArgs(string chatId, int messageId) + { + this.ChatId = chatId; + this.MessageId = messageId; + } + + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object ChatId { get; set; } + /// + /// Identifier of the target message + /// + [JsonPropertyName(PropertyNames.MessageId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int MessageId { get; set; } + /// + /// New list of reaction types to set on the message. Currently, as non-premium users, bots can set up to one reaction per message. A custom emoji reaction can be used if it is either already present on the message or explicitly allowed by chat administrators. + /// + [JsonPropertyName(PropertyNames.Reaction)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public IEnumerable? Reaction { get; set; } + /// + /// Pass True to set the reaction with a big animation + /// + [JsonPropertyName(PropertyNames.IsBig)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? IsBig { get; set; } + +} diff --git a/src/Telegram.BotAPI/Available Methods/Args/SetMyCommandsArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/SetMyCommandsArgs.cs similarity index 98% rename from src/Telegram.BotAPI/Available Methods/Args/SetMyCommandsArgs.cs rename to src/library/Telegram.BotAPI/Available Methods/Args/SetMyCommandsArgs.cs index 92fba3de..7f31982d 100644 --- a/src/Telegram.BotAPI/Available Methods/Args/SetMyCommandsArgs.cs +++ b/src/library/Telegram.BotAPI/Available Methods/Args/SetMyCommandsArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Methods/Args/SetMyDefaultAdministratorRightsArgs.cs b/src/library/Telegram.BotAPI/Available Methods/Args/SetMyDefaultAdministratorRightsArgs.cs similarity index 97% rename from src/Telegram.BotAPI/Available Methods/Args/SetMyDefaultAdministratorRightsArgs.cs rename to src/library/Telegram.BotAPI/Available Methods/Args/SetMyDefaultAdministratorRightsArgs.cs index 878b4920..17106ea4 100644 --- a/src/Telegram.BotAPI/Available Methods/Args/SetMyDefaultAdministratorRightsArgs.cs +++ b/src/library/Telegram.BotAPI/Available Methods/Args/SetMyDefaultAdministratorRightsArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Methods/Formatting options/ParseMode.cs b/src/library/Telegram.BotAPI/Available Methods/Formatting options/ParseMode.cs similarity index 99% rename from src/Telegram.BotAPI/Available Methods/Formatting options/ParseMode.cs rename to src/library/Telegram.BotAPI/Available Methods/Formatting options/ParseMode.cs index d6cf657b..83ee5538 100644 --- a/src/Telegram.BotAPI/Available Methods/Formatting options/ParseMode.cs +++ b/src/library/Telegram.BotAPI/Available Methods/Formatting options/ParseMode.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI.AvailableMethods.FormattingOptions; diff --git a/src/Telegram.BotAPI/Available Methods/Formatting options/ParseModeKind.cs b/src/library/Telegram.BotAPI/Available Methods/Formatting options/ParseModeKind.cs similarity index 98% rename from src/Telegram.BotAPI/Available Methods/Formatting options/ParseModeKind.cs rename to src/library/Telegram.BotAPI/Available Methods/Formatting options/ParseModeKind.cs index cb4d19f7..11531e36 100644 --- a/src/Telegram.BotAPI/Available Methods/Formatting options/ParseModeKind.cs +++ b/src/library/Telegram.BotAPI/Available Methods/Formatting options/ParseModeKind.cs @@ -1,9 +1,10 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI.AvailableMethods.FormattingOptions; /// Basic styles formatting for messages. +[Obsolete("Use Telegram.BotAPI.Extensions instead.")] public enum ParseModeKind { /// To use this mode, pass Markdown in the parse_mode field. Use the following syntax in your message: diff --git a/src/Telegram.BotAPI/Available Methods/Formatting options/StyleFixer.cs b/src/library/Telegram.BotAPI/Available Methods/Formatting options/StyleFixer.cs similarity index 97% rename from src/Telegram.BotAPI/Available Methods/Formatting options/StyleFixer.cs rename to src/library/Telegram.BotAPI/Available Methods/Formatting options/StyleFixer.cs index 56e33fc8..24c56f59 100644 --- a/src/Telegram.BotAPI/Available Methods/Formatting options/StyleFixer.cs +++ b/src/library/Telegram.BotAPI/Available Methods/Formatting options/StyleFixer.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Linq; @@ -9,6 +9,7 @@ namespace Telegram.BotAPI.AvailableMethods.FormattingOptions; /// /// Use this class to fix text with incorrect style tags or to create custom StyleParsers for use with the StyleParser. /// +[Obsolete("Use Telegram.BotAPI.Extensions instead.")] public class StyleParser : IStyleParser { /// Default StyleParser. diff --git a/src/Telegram.BotAPI/Available Methods/answerCallbackQuery.cs b/src/library/Telegram.BotAPI/Available Methods/answerCallbackQuery.cs similarity index 83% rename from src/Telegram.BotAPI/Available Methods/answerCallbackQuery.cs rename to src/library/Telegram.BotAPI/Available Methods/answerCallbackQuery.cs index ec1dcb24..18813070 100644 --- a/src/Telegram.BotAPI/Available Methods/answerCallbackQuery.cs +++ b/src/library/Telegram.BotAPI/Available Methods/answerCallbackQuery.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -11,22 +11,23 @@ namespace Telegram.BotAPI.AvailableMethods; public static partial class AvailableMethodsExtensions { /// Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned. - /// BotClient + /// BotClient /// Parameters. /// true /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. public static bool AnswerCallbackQuery( - this BotClient? bot, + this ITelegramBotClient client, AnswerCallbackQueryArgs args) { - if (bot == default) + if (client is null) { - throw new ArgumentNullException(nameof(bot)); + throw new ArgumentNullException(nameof(client)); } - return bot.RPC(MethodNames.AnswerCallbackQuery, args); + return client.CallMethod(MethodNames.AnswerCallbackQuery, args); } + /// Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned. /// BotClient /// Unique identifier for the query to be answered. @@ -37,12 +38,12 @@ public static bool AnswerCallbackQuery( /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. public static bool AnswerCallbackQuery( - this BotClient? bot, + this ITelegramBotClient bot, string callbackQueryId, - [Optional] string? text, - [Optional] bool? showAlert, - [Optional] string? url, - [Optional] uint? cacheTime) + string? text = null, + bool? showAlert = null, + string? url = null, + uint? cacheTime = null) { if (bot == default) { @@ -76,22 +77,23 @@ public static bool AnswerCallbackQuery( json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.AnswerCallbackQuery, stream); + return bot.CallMethod(MethodNames.AnswerCallbackQuery, stream); } + /// Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned. - /// BotClient + /// BotClient /// Parameters. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task AnswerCallbackQueryAsync( - this BotClient? bot, + public static Task AnswerCallbackQueryAsync( + this ITelegramBotClient client, AnswerCallbackQueryArgs args, - [Optional] CancellationToken cancellationToken) + CancellationToken cancellationToken = default) { - if (bot == default) + if (client is null) { - throw new ArgumentNullException(nameof(bot)); + throw new ArgumentNullException(nameof(client)); } if (args == default) @@ -99,10 +101,11 @@ public static async Task AnswerCallbackQueryAsync( throw new ArgumentNullException(nameof(args)); } - return await bot.RPCA(MethodNames.AnswerCallbackQuery, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return client.CallMethodAsync(MethodNames.AnswerCallbackQuery, args, cancellationToken: cancellationToken); } + /// Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned. - /// BotClient + /// BotClient /// Unique identifier for the query to be answered. /// Optional. Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters. /// Optional. If true, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to false. @@ -112,17 +115,17 @@ public static async Task AnswerCallbackQueryAsync( /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. public static async Task AnswerCallbackQueryAsync( - this BotClient? bot, + this ITelegramBotClient client, string callbackQueryId, - [Optional] string? text, - [Optional] bool? showAlert, - [Optional] string? url, - [Optional] uint? cacheTime, - [Optional] CancellationToken cancellationToken) + string? text = null, + bool? showAlert = null, + string? url = null, + uint? cacheTime = null, + CancellationToken cancellationToken = default) { - if (bot == default) + if (client is null) { - throw new ArgumentNullException(nameof(bot)); + throw new ArgumentNullException(nameof(client)); } var stream = new MemoryStream(); @@ -153,6 +156,6 @@ public static async Task AnswerCallbackQueryAsync( await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.AnswerCallbackQuery, stream, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.AnswerCallbackQuery, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/approveChatJoinRequest.cs b/src/library/Telegram.BotAPI/Available Methods/approveChatJoinRequest.cs similarity index 78% rename from src/Telegram.BotAPI/Available Methods/approveChatJoinRequest.cs rename to src/library/Telegram.BotAPI/Available Methods/approveChatJoinRequest.cs index f6b0dcfa..d75883bf 100644 --- a/src/Telegram.BotAPI/Available Methods/approveChatJoinRequest.cs +++ b/src/library/Telegram.BotAPI/Available Methods/approveChatJoinRequest.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -12,17 +12,17 @@ namespace Telegram.BotAPI.AvailableMethods; public static partial class AvailableMethodsExtensions { /// Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success. - /// BotClient + /// BotClient /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Unique identifier of the target user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static bool ApproveChatJoinRequest(this BotClient? bot, long chatId, long userId) + public static bool ApproveChatJoinRequest(this ITelegramBotClient client, long chatId, long userId) { - if (bot == default) + if (client is null) { - throw new ArgumentNullException(nameof(bot)); + throw new ArgumentNullException(nameof(client)); } var stream = new MemoryStream(); using var json = new Utf8JsonWriter(stream); @@ -32,20 +32,20 @@ public static bool ApproveChatJoinRequest(this BotClient? bot, long chatId, long json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.ApproveChatJoinRequest, stream); + return client.CallMethod(MethodNames.ApproveChatJoinRequest, stream); } /// Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success. - /// BotClient + /// BotClient /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Unique identifier of the target user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static bool ApproveChatJoinRequest(this BotClient? bot, string chatId, long userId) + public static bool ApproveChatJoinRequest(this ITelegramBotClient client, string chatId, long userId) { - if (bot == default) + if (client is null) { - throw new ArgumentNullException(nameof(bot)); + throw new ArgumentNullException(nameof(client)); } if (string.IsNullOrEmpty(chatId)) { @@ -59,21 +59,21 @@ public static bool ApproveChatJoinRequest(this BotClient? bot, string chatId, lo json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.ApproveChatJoinRequest, stream); + return client.CallMethod(MethodNames.ApproveChatJoinRequest, stream); } /// Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success. - /// BotClient + /// BotClient /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Unique identifier of the target user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static async Task ApproveChatJoinRequestAsync(this BotClient? bot, long chatId, long userId, [Optional] CancellationToken cancellationToken) + public static async Task ApproveChatJoinRequestAsync(this ITelegramBotClient client, long chatId, long userId, CancellationToken cancellationToken = default) { - if (bot == default) + if (client is null) { - throw new ArgumentNullException(nameof(bot)); + throw new ArgumentNullException(nameof(client)); } var stream = new MemoryStream(); using var json = new Utf8JsonWriter(stream); @@ -84,21 +84,21 @@ public static async Task ApproveChatJoinRequestAsync(this BotClient? bot, await json.FlushAsync().ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.ApproveChatJoinRequest, stream, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.ApproveChatJoinRequest, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success. - /// BotClient + /// BotClient /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Unique identifier of the target user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static async Task ApproveChatJoinRequest(this BotClient? bot, string chatId, long userId, [Optional] CancellationToken cancellationToken) + public static async Task ApproveChatJoinRequest(this ITelegramBotClient client, string chatId, long userId, CancellationToken cancellationToken = default) { - if (bot == default) + if (client is null) { - throw new ArgumentNullException(nameof(bot)); + throw new ArgumentNullException(nameof(client)); } if (string.IsNullOrEmpty(chatId)) { @@ -113,6 +113,6 @@ public static async Task ApproveChatJoinRequest(this BotClient? bot, strin await json.FlushAsync().ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.ApproveChatJoinRequest, stream, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.ApproveChatJoinRequest, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/banChatMember.cs b/src/library/Telegram.BotAPI/Available Methods/banChatMember.cs similarity index 85% rename from src/Telegram.BotAPI/Available Methods/banChatMember.cs rename to src/library/Telegram.BotAPI/Available Methods/banChatMember.cs index 69fadc8f..47c00e09 100644 --- a/src/Telegram.BotAPI/Available Methods/banChatMember.cs +++ b/src/library/Telegram.BotAPI/Available Methods/banChatMember.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -19,7 +19,7 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True on success. - public static bool BanChatMember(this BotClient? bot, long chatId, long userId, [Optional] uint? untilDate, [Optional] bool? revokeMessages) + public static bool BanChatMember(this ITelegramBotClient bot, long chatId, long userId, uint? untilDate = null, bool? revokeMessages = null) { if (bot == default) { @@ -42,7 +42,7 @@ public static bool BanChatMember(this BotClient? bot, long chatId, long userId, json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.BanChatMember, stream); + return bot.CallMethod(MethodNames.BanChatMember, stream); } /// Use this method to ban a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. /// BotClient @@ -53,7 +53,7 @@ public static bool BanChatMember(this BotClient? bot, long chatId, long userId, /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True on success. - public static bool BanChatMember(this BotClient? bot, string chatId, long userId, [Optional] uint? untilDate, [Optional] bool? revokeMessages) + public static bool BanChatMember(this ITelegramBotClient bot, string chatId, long userId, uint? untilDate = null, bool? revokeMessages = null) { if (bot == default) { @@ -76,10 +76,10 @@ public static bool BanChatMember(this BotClient? bot, string chatId, long userId json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.BanChatMember, stream); + return bot.CallMethod(MethodNames.BanChatMember, stream); } /// Use this method to ban a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. - /// BotClient + /// BotClient /// Unique identifier for the target group or username of the target supergroup or channel (in the format @channelusername). /// Unique identifier of the target user. /// Date when the user will be unbanned, unix time. If user is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever. @@ -88,11 +88,11 @@ public static bool BanChatMember(this BotClient? bot, string chatId, long userId /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True on success. - public static async Task BanChatMemberAsync(this BotClient? bot, long chatId, long userId, [Optional] uint? untilDate, [Optional] bool? revokeMessages, [Optional] CancellationToken cancellationToken) + public static async Task BanChatMemberAsync(this ITelegramBotClient client, long chatId, long userId, uint? untilDate = null, bool? revokeMessages = null, CancellationToken cancellationToken = default) { - if (bot == default) + if (client is null) { - throw new ArgumentNullException(nameof(bot)); + throw new ArgumentNullException(nameof(client)); } var stream = new MemoryStream(); @@ -112,10 +112,10 @@ public static async Task BanChatMemberAsync(this BotClient? bot, long chat await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.BanChatMember, stream, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.BanChatMember, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to ban a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. - /// BotClient + /// BotClient /// Unique identifier for the target group or username of the target supergroup or channel (in the format @channelusername). /// Unique identifier of the target user. /// Date when the user will be unbanned, unix time. If user is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever. @@ -124,11 +124,11 @@ public static async Task BanChatMemberAsync(this BotClient? bot, long chat /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True on success. - public static async Task BanChatMemberAsync(this BotClient? bot, string chatId, long userId, [Optional] uint? untilDate, [Optional] bool? revokeMessages, [Optional] CancellationToken cancellationToken) + public static async Task BanChatMemberAsync(this ITelegramBotClient client, string chatId, long userId, uint? untilDate = null, bool? revokeMessages = null, CancellationToken cancellationToken = default) { - if (bot == default) + if (client is null) { - throw new ArgumentNullException(nameof(bot)); + throw new ArgumentNullException(nameof(client)); } var stream = new MemoryStream(); @@ -148,6 +148,6 @@ public static async Task BanChatMemberAsync(this BotClient? bot, string ch await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.BanChatMember, stream, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.BanChatMember, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/banChatSenderChat.cs b/src/library/Telegram.BotAPI/Available Methods/banChatSenderChat.cs similarity index 84% rename from src/Telegram.BotAPI/Available Methods/banChatSenderChat.cs rename to src/library/Telegram.BotAPI/Available Methods/banChatSenderChat.cs index 71b307c3..ccef3ec5 100644 --- a/src/Telegram.BotAPI/Available Methods/banChatSenderChat.cs +++ b/src/library/Telegram.BotAPI/Available Methods/banChatSenderChat.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -19,7 +19,7 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True on success. - public static bool BanChatSenderChat(this BotClient? bot, long chatId, long senderChatId, [Optional] uint? untilDate) + public static bool BanChatSenderChat(this ITelegramBotClient bot, long chatId, long senderChatId, uint? untilDate = null) { if (bot == default) { @@ -38,7 +38,7 @@ public static bool BanChatSenderChat(this BotClient? bot, long chatId, long send json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.BanChatSenderChat, stream); + return bot.CallMethod(MethodNames.BanChatSenderChat, stream); } /// Use this method to ban a channel chat in a supergroup or a channel. The owner of the chat will not be able to send messages and join live streams on behalf of the chat, unless it is unbanned first. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. /// BotClient @@ -48,7 +48,7 @@ public static bool BanChatSenderChat(this BotClient? bot, long chatId, long send /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True on success. - public static bool BanChatSenderChat(this BotClient? bot, string chatId, long senderChatId, [Optional] uint? untilDate) + public static bool BanChatSenderChat(this ITelegramBotClient bot, string chatId, long senderChatId, uint? untilDate = null) { if (bot == default) { @@ -67,10 +67,10 @@ public static bool BanChatSenderChat(this BotClient? bot, string chatId, long se json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.BanChatSenderChat, stream); + return bot.CallMethod(MethodNames.BanChatSenderChat, stream); } /// Use this method to ban a channel chat in a supergroup or a channel. The owner of the chat will not be able to send messages and join live streams on behalf of the chat, unless it is unbanned first. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. - /// BotClient + /// BotClient /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) /// Unique identifier of the target sender chat /// Date when the sender chat will be unbanned, unix time. If the chat is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever. @@ -78,11 +78,11 @@ public static bool BanChatSenderChat(this BotClient? bot, string chatId, long se /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True on success. - public static async Task BanChatSenderChatAsync(this BotClient? bot, long chatId, long senderChatId, [Optional] uint? untilDate, [Optional] CancellationToken cancellationToken) + public static async Task BanChatSenderChatAsync(this ITelegramBotClient client, long chatId, long senderChatId, uint? untilDate = null, CancellationToken cancellationToken = default) { - if (bot == default) + if (client is null) { - throw new ArgumentNullException(nameof(bot)); + throw new ArgumentNullException(nameof(client)); } var stream = new MemoryStream(); @@ -98,10 +98,10 @@ public static async Task BanChatSenderChatAsync(this BotClient? bot, long await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.BanChatSenderChat, stream, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.BanChatSenderChat, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to ban a channel chat in a supergroup or a channel. The owner of the chat will not be able to send messages and join live streams on behalf of the chat, unless it is unbanned first. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. - /// BotClient + /// BotClient /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) /// Unique identifier of the target sender chat /// Date when the sender chat will be unbanned, unix time. If the chat is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever. @@ -109,11 +109,11 @@ public static async Task BanChatSenderChatAsync(this BotClient? bot, long /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True on success. - public static async Task BanChatSenderChatAsync(this BotClient? bot, string chatId, long senderChatId, [Optional] uint? untilDate, [Optional] CancellationToken cancellationToken) + public static async Task BanChatSenderChatAsync(this ITelegramBotClient client, string chatId, long senderChatId, uint? untilDate = null, CancellationToken cancellationToken = default) { - if (bot == default) + if (client is null) { - throw new ArgumentNullException(nameof(bot)); + throw new ArgumentNullException(nameof(client)); } var stream = new MemoryStream(); @@ -129,6 +129,6 @@ public static async Task BanChatSenderChatAsync(this BotClient? bot, strin await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.BanChatSenderChat, stream, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.BanChatSenderChat, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/close.cs b/src/library/Telegram.BotAPI/Available Methods/close.cs similarity index 61% rename from src/Telegram.BotAPI/Available Methods/close.cs rename to src/library/Telegram.BotAPI/Available Methods/close.cs index b66bd3d5..666f460f 100644 --- a/src/Telegram.BotAPI/Available Methods/close.cs +++ b/src/library/Telegram.BotAPI/Available Methods/close.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -13,28 +13,30 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static bool Close(this BotClient? bot) + public static bool Close(this ITelegramBotClient bot) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } - return bot.RPC(MethodNames.Close); + return bot.CallMethod(MethodNames.Close); } - /// Use this method to close the bot instance before moving it from one local server to another. You need to delete the webhook before calling this method to ensure that the bot isn't launched again after server restart. The method will return error 429 in the first 10 minutes after the bot is launched. Returns True on success. Requires no parameters. - /// Bot Client + /// + /// Use this method to close the bot instance before moving it from one local server to another. You need to delete the webhook before calling this method to ensure that the bot isn't launched again after server restart. The method will return error 429 in the first 10 minutes after the bot is launched. Returns True on success. Requires no parameters. + /// + /// Bot Client /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static async Task CloseAsync(this BotClient? bot, [Optional] CancellationToken cancellationToken) + public static Task CloseAsync(this ITelegramBotClient client, CancellationToken cancellationToken = default) { - if (bot == default) + if (client is null) { - throw new ArgumentNullException(nameof(bot)); + throw new ArgumentNullException(nameof(client)); } - return await bot.RPCA(MethodNames.Close, cancellationToken).ConfigureAwait(false); + return client.CallMethodAsync(MethodNames.Close, cancellationToken: cancellationToken); } } \ No newline at end of file diff --git a/src/Telegram.BotAPI/Available Methods/closeForumTopic.cs b/src/library/Telegram.BotAPI/Available Methods/closeForumTopic.cs similarity index 85% rename from src/Telegram.BotAPI/Available Methods/closeForumTopic.cs rename to src/library/Telegram.BotAPI/Available Methods/closeForumTopic.cs index 9d62ab84..01983846 100644 --- a/src/Telegram.BotAPI/Available Methods/closeForumTopic.cs +++ b/src/library/Telegram.BotAPI/Available Methods/closeForumTopic.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -18,7 +18,7 @@ public static partial class AvailableMethodsExtensions /// Unique identifier for the target message thread of the forum topic. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool CloseForumTopic(this BotClient? api, long chatId, int messageThreadId) + public static bool CloseForumTopic(this ITelegramBotClient api, long chatId, int messageThreadId) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -29,7 +29,7 @@ public static bool CloseForumTopic(this BotClient? api, long chatId, int message json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.CloseForumTopic, stream); + return api.CallMethod(MethodNames.CloseForumTopic, stream); } /// @@ -40,7 +40,7 @@ public static bool CloseForumTopic(this BotClient? api, long chatId, int message /// Unique identifier for the target message thread of the forum topic. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool CloseForumTopic(this BotClient? api, string chatId, int messageThreadId) + public static bool CloseForumTopic(this ITelegramBotClient api, string chatId, int messageThreadId) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -51,7 +51,7 @@ public static bool CloseForumTopic(this BotClient? api, string chatId, int messa json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.CloseForumTopic, stream); + return api.CallMethod(MethodNames.CloseForumTopic, stream); } /// @@ -63,7 +63,7 @@ public static bool CloseForumTopic(this BotClient? api, string chatId, int messa /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task CloseForumTopicAsync(this BotClient? api, long chatId, int messageThreadId, [Optional] CancellationToken cancellationToken) + public static async Task CloseForumTopicAsync(this ITelegramBotClient api, long chatId, int messageThreadId, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -75,7 +75,7 @@ public static async Task CloseForumTopicAsync(this BotClient? api, long ch await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.CloseForumTopic, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.CloseForumTopic, stream, cancellationToken).ConfigureAwait(false); } /// @@ -87,7 +87,7 @@ public static async Task CloseForumTopicAsync(this BotClient? api, long ch /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task CloseForumTopicAsync(this BotClient? api, string chatId, int messageThreadId, [Optional] CancellationToken cancellationToken) + public static async Task CloseForumTopicAsync(this ITelegramBotClient api, string chatId, int messageThreadId, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -99,6 +99,6 @@ public static async Task CloseForumTopicAsync(this BotClient? api, string await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.CloseForumTopic, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.CloseForumTopic, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/closeGeneralForumTopic.cs b/src/library/Telegram.BotAPI/Available Methods/closeGeneralForumTopic.cs similarity index 86% rename from src/Telegram.BotAPI/Available Methods/closeGeneralForumTopic.cs rename to src/library/Telegram.BotAPI/Available Methods/closeGeneralForumTopic.cs index 941dcbe2..cf389963 100644 --- a/src/Telegram.BotAPI/Available Methods/closeGeneralForumTopic.cs +++ b/src/library/Telegram.BotAPI/Available Methods/closeGeneralForumTopic.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -17,7 +17,7 @@ public static partial class AvailableMethodsExtensions /// Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername). /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool CloseGeneralForumTopic(this BotClient? api, long chatId) + public static bool CloseGeneralForumTopic(this ITelegramBotClient api, long chatId) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -27,7 +27,7 @@ public static bool CloseGeneralForumTopic(this BotClient? api, long chatId) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.CloseGeneralForumTopic, stream); + return api.CallMethod(MethodNames.CloseGeneralForumTopic, stream); } /// @@ -37,7 +37,7 @@ public static bool CloseGeneralForumTopic(this BotClient? api, long chatId) /// Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername). /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool CloseGeneralForumTopic(this BotClient? api, string chatId) + public static bool CloseGeneralForumTopic(this ITelegramBotClient api, string chatId) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -47,7 +47,7 @@ public static bool CloseGeneralForumTopic(this BotClient? api, string chatId) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.CloseGeneralForumTopic, stream); + return api.CallMethod(MethodNames.CloseGeneralForumTopic, stream); } /// @@ -58,7 +58,7 @@ public static bool CloseGeneralForumTopic(this BotClient? api, string chatId) /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task CloseGeneralForumTopicAsync(this BotClient? api, long chatId, [Optional] CancellationToken cancellationToken) + public static async Task CloseGeneralForumTopicAsync(this ITelegramBotClient api, long chatId, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -69,7 +69,7 @@ public static async Task CloseGeneralForumTopicAsync(this BotClient? api, await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.CloseGeneralForumTopic, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.CloseGeneralForumTopic, stream, cancellationToken).ConfigureAwait(false); } /// @@ -80,7 +80,7 @@ public static async Task CloseGeneralForumTopicAsync(this BotClient? api, /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task CloseGeneralForumTopicAsync(this BotClient? api, string chatId, [Optional] CancellationToken cancellationToken) + public static async Task CloseGeneralForumTopicAsync(this ITelegramBotClient api, string chatId, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -91,6 +91,6 @@ public static async Task CloseGeneralForumTopicAsync(this BotClient? api, await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.CloseGeneralForumTopic, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.CloseGeneralForumTopic, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/copyMessage.cs b/src/library/Telegram.BotAPI/Available Methods/copyMessage.cs similarity index 61% rename from src/Telegram.BotAPI/Available Methods/copyMessage.cs rename to src/library/Telegram.BotAPI/Available Methods/copyMessage.cs index 6f8b2fef..dcfa8a14 100644 --- a/src/Telegram.BotAPI/Available Methods/copyMessage.cs +++ b/src/library/Telegram.BotAPI/Available Methods/copyMessage.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -12,57 +12,40 @@ namespace Telegram.BotAPI.AvailableMethods; public static partial class AvailableMethodsExtensions { /// Use this method to forward messages of any kind. On success, the sent Message is returned. - /// BotClient + /// BotClient /// Parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message Object. - public static MessageID CopyMessage( - this BotClient? bot, - CopyMessageArgs args) + public static MessageID CopyMessage(this ITelegramBotClient client, CopyMessageArgs args) { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - - if (args == default) - { + if (client is null) + throw new ArgumentNullException(nameof(client)); + if (args is null) throw new ArgumentNullException(nameof(args)); - } - - return bot.RPC(MethodNames.CopyMessage, args); + return client.CallMethod(MethodNames.CopyMessage, args); } /// Use this method to forward messages of any kind. On success, the sent Message is returned. - /// BotClient + /// BotClient /// Parameters. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message Object. - public static async Task CopyMessageAsync( - this BotClient? bot, - CopyMessageArgs args, - [Optional] CancellationToken cancellationToken) + public static Task CopyMessageAsync(this ITelegramBotClient client, CopyMessageArgs args, CancellationToken cancellationToken = default) { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - - if (args == default) - { + if (client is null) + throw new ArgumentNullException(nameof(client)); + if (args is null) throw new ArgumentNullException(nameof(args)); - } - - return await bot.RPCA(MethodNames.CopyMessage, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return client.CallMethodAsync(MethodNames.CopyMessage, args, cancellationToken: cancellationToken); } /// - /// Use this method to copy messages of any kind. Service messages and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success. + /// Use this method to copy messages of any kind. Service messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername). /// Message identifier in the chat specified in from_chat_id. @@ -72,14 +55,14 @@ public static async Task CopyMessageAsync( /// A JSON-serialized list of special entities that appear in the new caption, which can be specified instead of parse_mode. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static MessageID CopyMessage(this BotClient? api, long chatId, long fromChatId, int messageId, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static MessageID CopyMessage(this ITelegramBotClient client, long chatId, long fromChatId, int messageId, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new CopyMessageArgs(chatId, fromChatId, messageId) { MessageThreadId = messageThreadId, @@ -88,17 +71,16 @@ public static MessageID CopyMessage(this BotClient? api, long chatId, long fromC CaptionEntities = captionEntities, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPC(MethodNames.CopyMessage, args); + return client.CallMethod(MethodNames.CopyMessage, args); } /// - /// Use this method to copy messages of any kind. Service messages and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success. + /// Use this method to copy messages of any kind. Service messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername). /// Message identifier in the chat specified in from_chat_id. @@ -108,14 +90,14 @@ public static MessageID CopyMessage(this BotClient? api, long chatId, long fromC /// A JSON-serialized list of special entities that appear in the new caption, which can be specified instead of parse_mode. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static MessageID CopyMessage(this BotClient? api, long chatId, string fromChatId, int messageId, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static MessageID CopyMessage(this ITelegramBotClient client, long chatId, string fromChatId, int messageId, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new CopyMessageArgs(chatId, fromChatId, messageId) { MessageThreadId = messageThreadId, @@ -124,17 +106,16 @@ public static MessageID CopyMessage(this BotClient? api, long chatId, string fro CaptionEntities = captionEntities, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPC(MethodNames.CopyMessage, args); + return client.CallMethod(MethodNames.CopyMessage, args); } /// - /// Use this method to copy messages of any kind. Service messages and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success. + /// Use this method to copy messages of any kind. Service messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername). /// Message identifier in the chat specified in from_chat_id. @@ -144,14 +125,14 @@ public static MessageID CopyMessage(this BotClient? api, long chatId, string fro /// A JSON-serialized list of special entities that appear in the new caption, which can be specified instead of parse_mode. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static MessageID CopyMessage(this BotClient? api, string chatId, long fromChatId, int messageId, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static MessageID CopyMessage(this ITelegramBotClient client, string chatId, long fromChatId, int messageId, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new CopyMessageArgs(chatId, fromChatId, messageId) { MessageThreadId = messageThreadId, @@ -160,17 +141,16 @@ public static MessageID CopyMessage(this BotClient? api, string chatId, long fro CaptionEntities = captionEntities, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPC(MethodNames.CopyMessage, args); + return client.CallMethod(MethodNames.CopyMessage, args); } /// - /// Use this method to copy messages of any kind. Service messages and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success. + /// Use this method to copy messages of any kind. Service messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername). /// Message identifier in the chat specified in from_chat_id. @@ -180,14 +160,14 @@ public static MessageID CopyMessage(this BotClient? api, string chatId, long fro /// A JSON-serialized list of special entities that appear in the new caption, which can be specified instead of parse_mode. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static MessageID CopyMessage(this BotClient? api, string chatId, string fromChatId, int messageId, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static MessageID CopyMessage(this ITelegramBotClient client, string chatId, string fromChatId, int messageId, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new CopyMessageArgs(chatId, fromChatId, messageId) { MessageThreadId = messageThreadId, @@ -196,17 +176,16 @@ public static MessageID CopyMessage(this BotClient? api, string chatId, string f CaptionEntities = captionEntities, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPC(MethodNames.CopyMessage, args); + return client.CallMethod(MethodNames.CopyMessage, args); } /// - /// Use this method to copy messages of any kind. Service messages and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success. + /// Use this method to copy messages of any kind. Service messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername). /// Message identifier in the chat specified in from_chat_id. @@ -216,15 +195,15 @@ public static MessageID CopyMessage(this BotClient? api, string chatId, string f /// A JSON-serialized list of special entities that appear in the new caption, which can be specified instead of parse_mode. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task CopyMessageAsync(this BotClient? api, long chatId, long fromChatId, int messageId, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task CopyMessageAsync(this ITelegramBotClient client, long chatId, long fromChatId, int messageId, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new CopyMessageArgs(chatId, fromChatId, messageId) { MessageThreadId = messageThreadId, @@ -233,17 +212,16 @@ public static async Task CopyMessageAsync(this BotClient? api, long c CaptionEntities = captionEntities, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCA(MethodNames.CopyMessage, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.CopyMessage, args, cancellationToken).ConfigureAwait(false); } /// - /// Use this method to copy messages of any kind. Service messages and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success. + /// Use this method to copy messages of any kind. Service messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername). /// Message identifier in the chat specified in from_chat_id. @@ -253,15 +231,15 @@ public static async Task CopyMessageAsync(this BotClient? api, long c /// A JSON-serialized list of special entities that appear in the new caption, which can be specified instead of parse_mode. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task CopyMessageAsync(this BotClient? api, long chatId, string fromChatId, int messageId, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task CopyMessageAsync(this ITelegramBotClient client, long chatId, string fromChatId, int messageId, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new CopyMessageArgs(chatId, fromChatId, messageId) { MessageThreadId = messageThreadId, @@ -270,17 +248,16 @@ public static async Task CopyMessageAsync(this BotClient? api, long c CaptionEntities = captionEntities, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCA(MethodNames.CopyMessage, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.CopyMessage, args, cancellationToken).ConfigureAwait(false); } /// - /// Use this method to copy messages of any kind. Service messages and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success. + /// Use this method to copy messages of any kind. Service messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername). /// Message identifier in the chat specified in from_chat_id. @@ -290,15 +267,15 @@ public static async Task CopyMessageAsync(this BotClient? api, long c /// A JSON-serialized list of special entities that appear in the new caption, which can be specified instead of parse_mode. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task CopyMessageAsync(this BotClient? api, string chatId, long fromChatId, int messageId, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task CopyMessageAsync(this ITelegramBotClient client, string chatId, long fromChatId, int messageId, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new CopyMessageArgs(chatId, fromChatId, messageId) { MessageThreadId = messageThreadId, @@ -307,17 +284,16 @@ public static async Task CopyMessageAsync(this BotClient? api, string CaptionEntities = captionEntities, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCA(MethodNames.CopyMessage, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.CopyMessage, args, cancellationToken).ConfigureAwait(false); } /// - /// Use this method to copy messages of any kind. Service messages and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success. + /// Use this method to copy messages of any kind. Service messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername). /// Message identifier in the chat specified in from_chat_id. @@ -327,15 +303,15 @@ public static async Task CopyMessageAsync(this BotClient? api, string /// A JSON-serialized list of special entities that appear in the new caption, which can be specified instead of parse_mode. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task CopyMessageAsync(this BotClient? api, string chatId, string fromChatId, int messageId, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task CopyMessageAsync(this ITelegramBotClient client, string chatId, string fromChatId, int messageId, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new CopyMessageArgs(chatId, fromChatId, messageId) { MessageThreadId = messageThreadId, @@ -344,10 +320,9 @@ public static async Task CopyMessageAsync(this BotClient? api, string CaptionEntities = captionEntities, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCA(MethodNames.CopyMessage, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.CopyMessage, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/library/Telegram.BotAPI/Available Methods/copyMessages.cs b/src/library/Telegram.BotAPI/Available Methods/copyMessages.cs new file mode 100644 index 00000000..352d0130 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Methods/copyMessages.cs @@ -0,0 +1,234 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System.Threading; +using System.Threading.Tasks; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.AvailableMethods; + +/// Available Methods +public static partial class AvailableMethodsExtensions +{ + /// + /// Use this method to copy messages of any kind. If some of the specified messages can't be found or copied, they are skipped. Service messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessages, but the copied messages don't have a link to the original message. Album grouping is kept for copied messages. On success, an array of MessageId of the sent messages is returned. + /// + /// The bot client. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername). + /// Identifiers of 1-100 messages in the chat from_chat_id to copy. The identifiers must be specified in a strictly increasing order. + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. + /// Sends the messages silently. Users will receive a notification with no sound. + /// Protects the contents of the sent messages from forwarding and saving. + /// Pass True to copy the messages without their captions. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static IEnumerable CopyMessages(this ITelegramBotClient client, long chatId, long fromChatId, IEnumerable messageIds, int? messageThreadId = null, bool? disableNotification = null, bool? protectContent = null, bool? removeCaption = null) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new CopyMessagesArgs(chatId, fromChatId, messageIds) + { + MessageThreadId = messageThreadId, + DisableNotification = disableNotification, + ProtectContent = protectContent, + RemoveCaption = removeCaption + }; + return client.CallMethod>(MethodNames.CopyMessages, args); + } + + /// + /// Use this method to copy messages of any kind. If some of the specified messages can't be found or copied, they are skipped. Service messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessages, but the copied messages don't have a link to the original message. Album grouping is kept for copied messages. On success, an array of MessageId of the sent messages is returned. + /// + /// The bot client. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername). + /// Identifiers of 1-100 messages in the chat from_chat_id to copy. The identifiers must be specified in a strictly increasing order. + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. + /// Sends the messages silently. Users will receive a notification with no sound. + /// Protects the contents of the sent messages from forwarding and saving. + /// Pass True to copy the messages without their captions. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static IEnumerable CopyMessages(this ITelegramBotClient client, long chatId, string fromChatId, IEnumerable messageIds, int? messageThreadId = null, bool? disableNotification = null, bool? protectContent = null, bool? removeCaption = null) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new CopyMessagesArgs(chatId, fromChatId, messageIds) + { + MessageThreadId = messageThreadId, + DisableNotification = disableNotification, + ProtectContent = protectContent, + RemoveCaption = removeCaption + }; + return client.CallMethod>(MethodNames.CopyMessages, args); + } + + /// + /// Use this method to copy messages of any kind. If some of the specified messages can't be found or copied, they are skipped. Service messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessages, but the copied messages don't have a link to the original message. Album grouping is kept for copied messages. On success, an array of MessageId of the sent messages is returned. + /// + /// The bot client. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername). + /// Identifiers of 1-100 messages in the chat from_chat_id to copy. The identifiers must be specified in a strictly increasing order. + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. + /// Sends the messages silently. Users will receive a notification with no sound. + /// Protects the contents of the sent messages from forwarding and saving. + /// Pass True to copy the messages without their captions. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static IEnumerable CopyMessages(this ITelegramBotClient client, string chatId, long fromChatId, IEnumerable messageIds, int? messageThreadId = null, bool? disableNotification = null, bool? protectContent = null, bool? removeCaption = null) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new CopyMessagesArgs(chatId, fromChatId, messageIds) + { + MessageThreadId = messageThreadId, + DisableNotification = disableNotification, + ProtectContent = protectContent, + RemoveCaption = removeCaption + }; + return client.CallMethod>(MethodNames.CopyMessages, args); + } + + /// + /// Use this method to copy messages of any kind. If some of the specified messages can't be found or copied, they are skipped. Service messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessages, but the copied messages don't have a link to the original message. Album grouping is kept for copied messages. On success, an array of MessageId of the sent messages is returned. + /// + /// The bot client. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername). + /// Identifiers of 1-100 messages in the chat from_chat_id to copy. The identifiers must be specified in a strictly increasing order. + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. + /// Sends the messages silently. Users will receive a notification with no sound. + /// Protects the contents of the sent messages from forwarding and saving. + /// Pass True to copy the messages without their captions. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static IEnumerable CopyMessages(this ITelegramBotClient client, string chatId, string fromChatId, IEnumerable messageIds, int? messageThreadId = null, bool? disableNotification = null, bool? protectContent = null, bool? removeCaption = null) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new CopyMessagesArgs(chatId, fromChatId, messageIds) + { + MessageThreadId = messageThreadId, + DisableNotification = disableNotification, + ProtectContent = protectContent, + RemoveCaption = removeCaption + }; + return client.CallMethod>(MethodNames.CopyMessages, args); + } + + /// + /// Use this method to copy messages of any kind. If some of the specified messages can't be found or copied, they are skipped. Service messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessages, but the copied messages don't have a link to the original message. Album grouping is kept for copied messages. On success, an array of MessageId of the sent messages is returned. + /// + /// The bot client. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername). + /// Identifiers of 1-100 messages in the chat from_chat_id to copy. The identifiers must be specified in a strictly increasing order. + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. + /// Sends the messages silently. Users will receive a notification with no sound. + /// Protects the contents of the sent messages from forwarding and saving. + /// Pass True to copy the messages without their captions. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static async Task CopyMessagesAsync(this ITelegramBotClient client, long chatId, long fromChatId, IEnumerable messageIds, int? messageThreadId = null, bool? disableNotification = null, bool? protectContent = null, bool? removeCaption = null, CancellationToken cancellationToken = default) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new CopyMessagesArgs(chatId, fromChatId, messageIds) + { + MessageThreadId = messageThreadId, + DisableNotification = disableNotification, + ProtectContent = protectContent, + RemoveCaption = removeCaption + }; + return await client.CallMethodAsync(MethodNames.CopyMessages, args, cancellationToken).ConfigureAwait(false); + } + + /// + /// Use this method to copy messages of any kind. If some of the specified messages can't be found or copied, they are skipped. Service messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessages, but the copied messages don't have a link to the original message. Album grouping is kept for copied messages. On success, an array of MessageId of the sent messages is returned. + /// + /// The bot client. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername). + /// Identifiers of 1-100 messages in the chat from_chat_id to copy. The identifiers must be specified in a strictly increasing order. + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. + /// Sends the messages silently. Users will receive a notification with no sound. + /// Protects the contents of the sent messages from forwarding and saving. + /// Pass True to copy the messages without their captions. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static async Task CopyMessagesAsync(this ITelegramBotClient client, long chatId, string fromChatId, IEnumerable messageIds, int? messageThreadId = null, bool? disableNotification = null, bool? protectContent = null, bool? removeCaption = null, CancellationToken cancellationToken = default) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new CopyMessagesArgs(chatId, fromChatId, messageIds) + { + MessageThreadId = messageThreadId, + DisableNotification = disableNotification, + ProtectContent = protectContent, + RemoveCaption = removeCaption + }; + return await client.CallMethodAsync(MethodNames.CopyMessages, args, cancellationToken).ConfigureAwait(false); + } + + /// + /// Use this method to copy messages of any kind. If some of the specified messages can't be found or copied, they are skipped. Service messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessages, but the copied messages don't have a link to the original message. Album grouping is kept for copied messages. On success, an array of MessageId of the sent messages is returned. + /// + /// The bot client. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername). + /// Identifiers of 1-100 messages in the chat from_chat_id to copy. The identifiers must be specified in a strictly increasing order. + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. + /// Sends the messages silently. Users will receive a notification with no sound. + /// Protects the contents of the sent messages from forwarding and saving. + /// Pass True to copy the messages without their captions. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static async Task CopyMessagesAsync(this ITelegramBotClient client, string chatId, long fromChatId, IEnumerable messageIds, int? messageThreadId = null, bool? disableNotification = null, bool? protectContent = null, bool? removeCaption = null, CancellationToken cancellationToken = default) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new CopyMessagesArgs(chatId, fromChatId, messageIds) + { + MessageThreadId = messageThreadId, + DisableNotification = disableNotification, + ProtectContent = protectContent, + RemoveCaption = removeCaption + }; + return await client.CallMethodAsync(MethodNames.CopyMessages, args, cancellationToken).ConfigureAwait(false); + } + + /// + /// Use this method to copy messages of any kind. If some of the specified messages can't be found or copied, they are skipped. Service messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessages, but the copied messages don't have a link to the original message. Album grouping is kept for copied messages. On success, an array of MessageId of the sent messages is returned. + /// + /// The bot client. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername). + /// Identifiers of 1-100 messages in the chat from_chat_id to copy. The identifiers must be specified in a strictly increasing order. + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. + /// Sends the messages silently. Users will receive a notification with no sound. + /// Protects the contents of the sent messages from forwarding and saving. + /// Pass True to copy the messages without their captions. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static async Task CopyMessagesAsync(this ITelegramBotClient client, string chatId, string fromChatId, IEnumerable messageIds, int? messageThreadId = null, bool? disableNotification = null, bool? protectContent = null, bool? removeCaption = null, CancellationToken cancellationToken = default) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new CopyMessagesArgs(chatId, fromChatId, messageIds) + { + MessageThreadId = messageThreadId, + DisableNotification = disableNotification, + ProtectContent = protectContent, + RemoveCaption = removeCaption + }; + return await client.CallMethodAsync(MethodNames.CopyMessages, args, cancellationToken).ConfigureAwait(false); + } + + +} diff --git a/src/Telegram.BotAPI/Available Methods/createChatInviteLink.cs b/src/library/Telegram.BotAPI/Available Methods/createChatInviteLink.cs similarity index 87% rename from src/Telegram.BotAPI/Available Methods/createChatInviteLink.cs rename to src/library/Telegram.BotAPI/Available Methods/createChatInviteLink.cs index 3ccf20fa..e0835aaf 100644 --- a/src/Telegram.BotAPI/Available Methods/createChatInviteLink.cs +++ b/src/library/Telegram.BotAPI/Available Methods/createChatInviteLink.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -21,7 +21,7 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static ChatInviteLink CreateChatInviteLink(this BotClient? bot, long chatId, [Optional] string name, [Optional] uint? expireDate, [Optional] uint? memberLimit, [Optional] bool? createsJoinRequest) + public static ChatInviteLink CreateChatInviteLink(this ITelegramBotClient bot, long chatId, string? name = null, uint? expireDate = null, uint? memberLimit = null, bool? createsJoinRequest = null) { if (bot == default) { @@ -50,7 +50,7 @@ public static ChatInviteLink CreateChatInviteLink(this BotClient? bot, long chat json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.CreateChatInviteLink, stream); + return bot.CallMethod(MethodNames.CreateChatInviteLink, stream); } /// Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. The link can be revoked using the method revokeChatInviteLink. Returns the new invite link as object. /// BotClient @@ -62,7 +62,7 @@ public static ChatInviteLink CreateChatInviteLink(this BotClient? bot, long chat /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static ChatInviteLink CreateChatInviteLink(this BotClient? bot, string chatId, [Optional] string name, [Optional] uint? expireDate, [Optional] uint? memberLimit, [Optional] bool? createsJoinRequest) + public static ChatInviteLink CreateChatInviteLink(this ITelegramBotClient bot, string chatId, string? name = null, uint? expireDate = null, uint? memberLimit = null, bool? createsJoinRequest = null) { if (bot == default) { @@ -92,7 +92,7 @@ public static ChatInviteLink CreateChatInviteLink(this BotClient? bot, string ch json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.CreateChatInviteLink, stream); + return bot.CallMethod(MethodNames.CreateChatInviteLink, stream); } /// Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. The link can be revoked using the method revokeChatInviteLink. Returns the new invite link as object. /// BotClient @@ -105,7 +105,7 @@ public static ChatInviteLink CreateChatInviteLink(this BotClient? bot, string ch /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static async Task CreateChatInviteLink(this BotClient? bot, long chatId, [Optional] string name, [Optional] uint? expireDate, [Optional] uint? memberLimit, [Optional] bool? createsJoinRequest, [Optional] CancellationToken cancellationToken) + public static async Task CreateChatInviteLink(this ITelegramBotClient bot, long chatId, string? name = null, uint? expireDate = null, uint? memberLimit = null, bool? createsJoinRequest = null, CancellationToken cancellationToken = default) { if (bot == default) { @@ -136,7 +136,7 @@ public static async Task CreateChatInviteLink(this BotClient? bo await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.CreateChatInviteLink, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.CreateChatInviteLink, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. The link can be revoked using the method revokeChatInviteLink. Returns the new invite link as object. /// BotClient @@ -149,7 +149,7 @@ public static async Task CreateChatInviteLink(this BotClient? bo /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static async Task CreateChatInviteLink(this BotClient? bot, string chatId, [Optional] string name, [Optional] uint? expireDate, [Optional] uint? memberLimit, [Optional] bool? createsJoinRequest, [Optional] CancellationToken cancellationToken) + public static async Task CreateChatInviteLink(this ITelegramBotClient bot, string chatId, string? name = null, uint? expireDate = null, uint? memberLimit = null, bool? createsJoinRequest = null, CancellationToken cancellationToken = default) { if (bot == default) { @@ -180,6 +180,6 @@ public static async Task CreateChatInviteLink(this BotClient? bo await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.CreateChatInviteLink, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.CreateChatInviteLink, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/createForumTopic.cs b/src/library/Telegram.BotAPI/Available Methods/createForumTopic.cs similarity index 87% rename from src/Telegram.BotAPI/Available Methods/createForumTopic.cs rename to src/library/Telegram.BotAPI/Available Methods/createForumTopic.cs index 99f4379b..dbce1683 100644 --- a/src/Telegram.BotAPI/Available Methods/createForumTopic.cs +++ b/src/library/Telegram.BotAPI/Available Methods/createForumTopic.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -21,7 +21,7 @@ public static partial class AvailableMethodsExtensions /// Unique identifier of the custom emoji shown as the topic icon. Use getForumTopicIconStickers to get all allowed custom emoji identifiers. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static ForumTopic CreateForumTopic(this BotClient? api, long chatId, string name, [Optional] int? iconColor, [Optional] string iconCustomEmojiId) + public static ForumTopic CreateForumTopic(this ITelegramBotClient api, long chatId, string name, int? iconColor = null, string? iconCustomEmojiId = null) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -40,7 +40,7 @@ public static ForumTopic CreateForumTopic(this BotClient? api, long chatId, stri json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.CreateForumTopic, stream); + return api.CallMethod(MethodNames.CreateForumTopic, stream); } /// @@ -53,7 +53,7 @@ public static ForumTopic CreateForumTopic(this BotClient? api, long chatId, stri /// Unique identifier of the custom emoji shown as the topic icon. Use getForumTopicIconStickers to get all allowed custom emoji identifiers. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static ForumTopic CreateForumTopic(this BotClient? api, string chatId, string name, [Optional] int? iconColor, [Optional] string iconCustomEmojiId) + public static ForumTopic CreateForumTopic(this ITelegramBotClient api, string chatId, string name, int? iconColor = null, string? iconCustomEmojiId = null) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -72,7 +72,7 @@ public static ForumTopic CreateForumTopic(this BotClient? api, string chatId, st json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.CreateForumTopic, stream); + return api.CallMethod(MethodNames.CreateForumTopic, stream); } /// @@ -86,7 +86,7 @@ public static ForumTopic CreateForumTopic(this BotClient? api, string chatId, st /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task CreateForumTopicAsync(this BotClient? api, long chatId, string name, [Optional] int? iconColor, [Optional] string iconCustomEmojiId, [Optional] CancellationToken cancellationToken) + public static async Task CreateForumTopicAsync(this ITelegramBotClient api, long chatId, string name, int? iconColor = null, string? iconCustomEmojiId = null, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -106,7 +106,7 @@ public static async Task CreateForumTopicAsync(this BotClient? api, await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.CreateForumTopic, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.CreateForumTopic, stream, cancellationToken).ConfigureAwait(false); } /// @@ -120,7 +120,7 @@ public static async Task CreateForumTopicAsync(this BotClient? api, /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task CreateForumTopicAsync(this BotClient? api, string chatId, string name, [Optional] int? iconColor, [Optional] string iconCustomEmojiId, [Optional] CancellationToken cancellationToken) + public static async Task CreateForumTopicAsync(this ITelegramBotClient api, string chatId, string name, int? iconColor = null, string? iconCustomEmojiId = null, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -140,6 +140,6 @@ public static async Task CreateForumTopicAsync(this BotClient? api, await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.CreateForumTopic, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.CreateForumTopic, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/declineChatJoinRequest.cs b/src/library/Telegram.BotAPI/Available Methods/declineChatJoinRequest.cs similarity index 85% rename from src/Telegram.BotAPI/Available Methods/declineChatJoinRequest.cs rename to src/library/Telegram.BotAPI/Available Methods/declineChatJoinRequest.cs index b2544393..33ba469e 100644 --- a/src/Telegram.BotAPI/Available Methods/declineChatJoinRequest.cs +++ b/src/library/Telegram.BotAPI/Available Methods/declineChatJoinRequest.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -18,7 +18,7 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static bool DeclineChatJoinRequest(this BotClient? bot, long chatId, long userId) + public static bool DeclineChatJoinRequest(this ITelegramBotClient bot, long chatId, long userId) { if (bot == default) { @@ -32,7 +32,7 @@ public static bool DeclineChatJoinRequest(this BotClient? bot, long chatId, long json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.DeclineChatJoinRequest, stream); + return bot.CallMethod(MethodNames.DeclineChatJoinRequest, stream); } /// Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.. /// BotClient @@ -41,7 +41,7 @@ public static bool DeclineChatJoinRequest(this BotClient? bot, long chatId, long /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static bool DeclineChatJoinRequest(this BotClient? bot, string chatId, long userId) + public static bool DeclineChatJoinRequest(this ITelegramBotClient bot, string chatId, long userId) { if (bot == default) { @@ -59,7 +59,7 @@ public static bool DeclineChatJoinRequest(this BotClient? bot, string chatId, lo json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.DeclineChatJoinRequest, stream); + return bot.CallMethod(MethodNames.DeclineChatJoinRequest, stream); } /// Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.. /// BotClient @@ -69,7 +69,7 @@ public static bool DeclineChatJoinRequest(this BotClient? bot, string chatId, lo /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static async Task DeclineChatJoinRequestAsync(this BotClient? bot, long chatId, long userId, [Optional] CancellationToken cancellationToken) + public static async Task DeclineChatJoinRequestAsync(this ITelegramBotClient bot, long chatId, long userId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -84,7 +84,7 @@ public static async Task DeclineChatJoinRequestAsync(this BotClient? bot, await json.FlushAsync().ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.DeclineChatJoinRequest, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.DeclineChatJoinRequest, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.. /// BotClient @@ -94,7 +94,7 @@ public static async Task DeclineChatJoinRequestAsync(this BotClient? bot, /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static async Task DeclineChatJoinRequest(this BotClient? bot, string chatId, long userId, [Optional] CancellationToken cancellationToken) + public static async Task DeclineChatJoinRequest(this ITelegramBotClient bot, string chatId, long userId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -113,6 +113,6 @@ public static async Task DeclineChatJoinRequest(this BotClient? bot, strin await json.FlushAsync().ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.DeclineChatJoinRequest, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.DeclineChatJoinRequest, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/deleteChatPhoto.cs b/src/library/Telegram.BotAPI/Available Methods/deleteChatPhoto.cs similarity index 88% rename from src/Telegram.BotAPI/Available Methods/deleteChatPhoto.cs rename to src/library/Telegram.BotAPI/Available Methods/deleteChatPhoto.cs index e98abadf..bbf13b96 100644 --- a/src/Telegram.BotAPI/Available Methods/deleteChatPhoto.cs +++ b/src/library/Telegram.BotAPI/Available Methods/deleteChatPhoto.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -16,7 +16,7 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. public static bool DeleteChatPhoto( - this BotClient? bot, + this ITelegramBotClient bot, long chatId) { if (bot == default) @@ -31,7 +31,7 @@ public static bool DeleteChatPhoto( json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.DeleteChatPhoto, stream); + return bot.CallMethod(MethodNames.DeleteChatPhoto, stream); } /// Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. /// BotClient @@ -40,7 +40,7 @@ public static bool DeleteChatPhoto( /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. public static bool DeleteChatPhoto( - this BotClient? bot, + this ITelegramBotClient bot, string chatId) { if (bot == default) @@ -55,7 +55,7 @@ public static bool DeleteChatPhoto( json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.DeleteChatPhoto, stream); + return bot.CallMethod(MethodNames.DeleteChatPhoto, stream); } /// Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. /// BotClient @@ -64,9 +64,9 @@ public static bool DeleteChatPhoto( /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. public static async Task DeleteChatPhotoAsync( - this BotClient? bot, + this ITelegramBotClient bot, long chatId, - [Optional] CancellationToken cancellationToken) + CancellationToken cancellationToken = default) { if (bot == default) { @@ -81,7 +81,7 @@ public static async Task DeleteChatPhotoAsync( await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.DeleteChatPhoto, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.DeleteChatPhoto, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. /// BotClient @@ -90,9 +90,9 @@ public static async Task DeleteChatPhotoAsync( /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. public static async Task DeleteChatPhotoAsync( - this BotClient? bot, + this ITelegramBotClient bot, string chatId, - [Optional] CancellationToken cancellationToken) + CancellationToken cancellationToken = default) { if (bot == default) { @@ -107,6 +107,6 @@ public static async Task DeleteChatPhotoAsync( await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.DeleteChatPhoto, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.DeleteChatPhoto, stream, cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Telegram.BotAPI/Available Methods/deleteChatStickerSet.cs b/src/library/Telegram.BotAPI/Available Methods/deleteChatStickerSet.cs similarity index 90% rename from src/Telegram.BotAPI/Available Methods/deleteChatStickerSet.cs rename to src/library/Telegram.BotAPI/Available Methods/deleteChatStickerSet.cs index 390f9079..b48bc61d 100644 --- a/src/Telegram.BotAPI/Available Methods/deleteChatStickerSet.cs +++ b/src/library/Telegram.BotAPI/Available Methods/deleteChatStickerSet.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -16,7 +16,7 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. public static bool DeleteChatStickerSet( - this BotClient? bot, + this ITelegramBotClient bot, long chatId) { if (bot == default) @@ -31,7 +31,7 @@ public static bool DeleteChatStickerSet( json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.DeleteChatStickerSet, stream); + return bot.CallMethod(MethodNames.DeleteChatStickerSet, stream); } /// Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success. /// BotClient @@ -39,7 +39,7 @@ public static bool DeleteChatStickerSet( /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. public static bool DeleteChatStickerSet( - this BotClient? bot, + this ITelegramBotClient bot, string chatId) { if (bot == default) @@ -54,7 +54,7 @@ public static bool DeleteChatStickerSet( json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.DeleteChatStickerSet, stream); + return bot.CallMethod(MethodNames.DeleteChatStickerSet, stream); } /// Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success. /// BotClient @@ -63,9 +63,9 @@ public static bool DeleteChatStickerSet( /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. public static async Task DeleteChatStickerSetAsync( - this BotClient? bot, + this ITelegramBotClient bot, long chatId, - [Optional] CancellationToken cancellationToken) + CancellationToken cancellationToken = default) { if (bot == default) { @@ -80,7 +80,7 @@ public static async Task DeleteChatStickerSetAsync( await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.DeleteChatStickerSet, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.DeleteChatStickerSet, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success. /// BotClient @@ -89,9 +89,9 @@ public static async Task DeleteChatStickerSetAsync( /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. public static async Task DeleteChatStickerSetAsync( - this BotClient? bot, + this ITelegramBotClient bot, string chatId, - [Optional] CancellationToken cancellationToken) + CancellationToken cancellationToken = default) { if (bot == default) { @@ -108,7 +108,7 @@ public static async Task DeleteChatStickerSetAsync( await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA( + return await bot.CallMethodAsync( "deleteChatStickerSet", stream, cancellationToken).ConfigureAwait(false); diff --git a/src/Telegram.BotAPI/Available Methods/deleteForumTopic.cs b/src/library/Telegram.BotAPI/Available Methods/deleteForumTopic.cs similarity index 85% rename from src/Telegram.BotAPI/Available Methods/deleteForumTopic.cs rename to src/library/Telegram.BotAPI/Available Methods/deleteForumTopic.cs index 97447cad..eb520209 100644 --- a/src/Telegram.BotAPI/Available Methods/deleteForumTopic.cs +++ b/src/library/Telegram.BotAPI/Available Methods/deleteForumTopic.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -18,7 +18,7 @@ public static partial class AvailableMethodsExtensions /// Unique identifier for the target message thread of the forum topic. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool DeleteForumTopic(this BotClient? api, long chatId, int messageThreadId) + public static bool DeleteForumTopic(this ITelegramBotClient api, long chatId, int messageThreadId) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -29,7 +29,7 @@ public static bool DeleteForumTopic(this BotClient? api, long chatId, int messag json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.DeleteForumTopic, stream); + return api.CallMethod(MethodNames.DeleteForumTopic, stream); } /// @@ -40,7 +40,7 @@ public static bool DeleteForumTopic(this BotClient? api, long chatId, int messag /// Unique identifier for the target message thread of the forum topic. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool DeleteForumTopic(this BotClient? api, string chatId, int messageThreadId) + public static bool DeleteForumTopic(this ITelegramBotClient api, string chatId, int messageThreadId) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -51,7 +51,7 @@ public static bool DeleteForumTopic(this BotClient? api, string chatId, int mess json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.DeleteForumTopic, stream); + return api.CallMethod(MethodNames.DeleteForumTopic, stream); } /// @@ -63,7 +63,7 @@ public static bool DeleteForumTopic(this BotClient? api, string chatId, int mess /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task DeleteForumTopicAsync(this BotClient? api, long chatId, int messageThreadId, [Optional] CancellationToken cancellationToken) + public static async Task DeleteForumTopicAsync(this ITelegramBotClient api, long chatId, int messageThreadId, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -75,7 +75,7 @@ public static async Task DeleteForumTopicAsync(this BotClient? api, long c await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.DeleteForumTopic, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.DeleteForumTopic, stream, cancellationToken).ConfigureAwait(false); } /// @@ -87,7 +87,7 @@ public static async Task DeleteForumTopicAsync(this BotClient? api, long c /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task DeleteForumTopicAsync(this BotClient? api, string chatId, int messageThreadId, [Optional] CancellationToken cancellationToken) + public static async Task DeleteForumTopicAsync(this ITelegramBotClient api, string chatId, int messageThreadId, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -99,6 +99,6 @@ public static async Task DeleteForumTopicAsync(this BotClient? api, string await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.DeleteForumTopic, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.DeleteForumTopic, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/deleteMyCommands.cs b/src/library/Telegram.BotAPI/Available Methods/deleteMyCommands.cs similarity index 76% rename from src/Telegram.BotAPI/Available Methods/deleteMyCommands.cs rename to src/library/Telegram.BotAPI/Available Methods/deleteMyCommands.cs index c7390f57..02e12415 100644 --- a/src/Telegram.BotAPI/Available Methods/deleteMyCommands.cs +++ b/src/library/Telegram.BotAPI/Available Methods/deleteMyCommands.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -14,7 +14,7 @@ public static partial class AvailableMethodsExtensions /// A object, describing scope of users for which the commands are relevant. Defaults to . /// A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands. /// True on success. - public static bool DeleteMyCommands(this BotClient? bot, [Optional] BotCommandScope scope, [Optional] string languageCode) + public static bool DeleteMyCommands(this ITelegramBotClient bot, BotCommandScope? scope = null, string? languageCode = null) { if (bot == null) { @@ -22,14 +22,14 @@ public static bool DeleteMyCommands(this BotClient? bot, [Optional] BotCommandSc } var args = new DeleteMyCommandsArgs(scope, languageCode); - return bot.RPC(MethodNames.DeleteMyCommands, args); + return bot.CallMethod(MethodNames.DeleteMyCommands, args); } /// Use this method to delete the list of the bot's commands for the given scope and user language. After deletion, higher level commands will be shown to affected users. /// BotClient /// Parameters. /// True on success. - public static bool DeleteMyCommands(this BotClient? bot, DeleteMyCommandsArgs args) + public static bool DeleteMyCommands(this ITelegramBotClient bot, DeleteMyCommandsArgs args) { if (bot == null) { @@ -40,7 +40,7 @@ public static bool DeleteMyCommands(this BotClient? bot, DeleteMyCommandsArgs ar throw new ArgumentNullException(nameof(args)); } - return bot.RPC(MethodNames.DeleteMyCommands, args); + return bot.CallMethod(MethodNames.DeleteMyCommands, args); } /// Use this method to delete the list of the bot's commands for the given scope and user language. After deletion, higher level commands will be shown to affected users. @@ -49,7 +49,7 @@ public static bool DeleteMyCommands(this BotClient? bot, DeleteMyCommandsArgs ar /// A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands. /// The cancellation token to cancel operation. /// True on success. - public static async Task DeleteMyCommandsAsync(this BotClient? bot, [Optional] BotCommandScope scope, [Optional] string languageCode, CancellationToken cancellationToken) + public static async Task DeleteMyCommandsAsync(this ITelegramBotClient bot, BotCommandScope? scope = null, string? languageCode = null, CancellationToken cancellationToken = default) { if (bot == null) { @@ -57,7 +57,7 @@ public static async Task DeleteMyCommandsAsync(this BotClient? bot, [Optio } var args = new DeleteMyCommandsArgs(scope, languageCode); - return await bot.RPCA(MethodNames.DeleteMyCommands, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.DeleteMyCommands, args, cancellationToken: cancellationToken).ConfigureAwait(false); } /// Use this method to delete the list of the bot's commands for the given scope and user language. After deletion, higher level commands will be shown to affected users. @@ -65,7 +65,7 @@ public static async Task DeleteMyCommandsAsync(this BotClient? bot, [Optio /// Parameters. /// The cancellation token to cancel operation. /// True on success. - public static async Task DeleteMyCommandsAsync(this BotClient? bot, DeleteMyCommandsArgs args, [Optional] CancellationToken cancellationToken) + public static async Task DeleteMyCommandsAsync(this ITelegramBotClient bot, DeleteMyCommandsArgs args, CancellationToken cancellationToken = default) { if (bot == null) { @@ -76,6 +76,6 @@ public static async Task DeleteMyCommandsAsync(this BotClient? bot, Delete throw new ArgumentNullException(nameof(args)); } - return await bot.RPCA(MethodNames.DeleteMyCommands, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.DeleteMyCommands, args, cancellationToken: cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/editChatInviteLink.cs b/src/library/Telegram.BotAPI/Available Methods/editChatInviteLink.cs similarity index 87% rename from src/Telegram.BotAPI/Available Methods/editChatInviteLink.cs rename to src/library/Telegram.BotAPI/Available Methods/editChatInviteLink.cs index 05b76d16..4df4f368 100644 --- a/src/Telegram.BotAPI/Available Methods/editChatInviteLink.cs +++ b/src/library/Telegram.BotAPI/Available Methods/editChatInviteLink.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -22,7 +22,7 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static ChatInviteLink EditChatInviteLink(this BotClient? bot, long chatId, string inviteLink, [Optional] string name, [Optional] uint? expireDate, [Optional] uint? memberLimit, [Optional] bool? createsJoinRequest) + public static ChatInviteLink EditChatInviteLink(this ITelegramBotClient bot, long chatId, string inviteLink, [Optional] string name, [Optional] uint? expireDate, [Optional] uint? memberLimit, [Optional] bool? createsJoinRequest) { if (bot == default) { @@ -56,7 +56,7 @@ public static ChatInviteLink EditChatInviteLink(this BotClient? bot, long chatId json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.EditChatInviteLink, stream); + return bot.CallMethod(MethodNames.EditChatInviteLink, stream); } /// Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns the edited invite link as object. /// BotClient @@ -69,7 +69,7 @@ public static ChatInviteLink EditChatInviteLink(this BotClient? bot, long chatId /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static ChatInviteLink EditChatInviteLink(this BotClient? bot, string chatId, string inviteLink, [Optional] string name, [Optional] uint? expireDate, [Optional] uint? memberLimit, [Optional] bool? createsJoinRequest) + public static ChatInviteLink EditChatInviteLink(this ITelegramBotClient bot, string chatId, string inviteLink, [Optional] string name, [Optional] uint? expireDate, [Optional] uint? memberLimit, [Optional] bool? createsJoinRequest) { if (bot == default) { @@ -103,7 +103,7 @@ public static ChatInviteLink EditChatInviteLink(this BotClient? bot, string chat json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.EditChatInviteLink, stream); + return bot.CallMethod(MethodNames.EditChatInviteLink, stream); } /// Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns the edited invite link as object. /// BotClient @@ -117,7 +117,7 @@ public static ChatInviteLink EditChatInviteLink(this BotClient? bot, string chat /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static async Task EditChatInviteLink(this BotClient? bot, long chatId, string inviteLink, [Optional] string name, [Optional] uint? expireDate, [Optional] uint? memberLimit, [Optional] bool? createsJoinRequest, [Optional] CancellationToken cancellationToken) + public static async Task EditChatInviteLink(this ITelegramBotClient bot, long chatId, string inviteLink, [Optional] string name, [Optional] uint? expireDate, [Optional] uint? memberLimit, [Optional] bool? createsJoinRequest, CancellationToken cancellationToken = default) { if (bot == default) { @@ -152,7 +152,7 @@ public static async Task EditChatInviteLink(this BotClient? bot, await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.EditChatInviteLink, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.EditChatInviteLink, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns the edited invite link as object. /// BotClient @@ -166,7 +166,7 @@ public static async Task EditChatInviteLink(this BotClient? bot, /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static async Task EditChatInviteLink(this BotClient? bot, string chatId, string inviteLink, [Optional] string name, [Optional] uint? expireDate, [Optional] uint? memberLimit, [Optional] bool? createsJoinRequest, [Optional] CancellationToken cancellationToken) + public static async Task EditChatInviteLink(this ITelegramBotClient bot, string chatId, string inviteLink, [Optional] string name, [Optional] uint? expireDate, [Optional] uint? memberLimit, [Optional] bool? createsJoinRequest, CancellationToken cancellationToken = default) { if (bot == default) { @@ -201,6 +201,6 @@ public static async Task EditChatInviteLink(this BotClient? bot, await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.EditChatInviteLink, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.EditChatInviteLink, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/editForumTopic.cs b/src/library/Telegram.BotAPI/Available Methods/editForumTopic.cs similarity index 87% rename from src/Telegram.BotAPI/Available Methods/editForumTopic.cs rename to src/library/Telegram.BotAPI/Available Methods/editForumTopic.cs index d9510c9a..0a164273 100644 --- a/src/Telegram.BotAPI/Available Methods/editForumTopic.cs +++ b/src/library/Telegram.BotAPI/Available Methods/editForumTopic.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -20,7 +20,7 @@ public static partial class AvailableMethodsExtensions /// New unique identifier of the custom emoji shown as the topic icon. Use getForumTopicIconStickers to get all allowed custom emoji identifiers. Pass an empty string to remove the icon. If not specified, the current icon will be kept. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool EditForumTopic(this BotClient? api, long chatId, int messageThreadId, [Optional] string? name, [Optional] string? iconCustomEmojiId) + public static bool EditForumTopic(this ITelegramBotClient api, long chatId, int messageThreadId, [Optional] string? name, [Optional] string? iconCustomEmojiId) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -39,7 +39,7 @@ public static bool EditForumTopic(this BotClient? api, long chatId, int messageT json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.EditForumTopic, stream); + return api.CallMethod(MethodNames.EditForumTopic, stream); } /// @@ -52,7 +52,7 @@ public static bool EditForumTopic(this BotClient? api, long chatId, int messageT /// New unique identifier of the custom emoji shown as the topic icon. Use getForumTopicIconStickers to get all allowed custom emoji identifiers. Pass an empty string to remove the icon. If not specified, the current icon will be kept. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool EditForumTopic(this BotClient? api, string chatId, int messageThreadId, [Optional] string? name, [Optional] string? iconCustomEmojiId) + public static bool EditForumTopic(this ITelegramBotClient api, string chatId, int messageThreadId, [Optional] string? name, [Optional] string? iconCustomEmojiId) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -71,7 +71,7 @@ public static bool EditForumTopic(this BotClient? api, string chatId, int messag json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.EditForumTopic, stream); + return api.CallMethod(MethodNames.EditForumTopic, stream); } /// @@ -85,7 +85,7 @@ public static bool EditForumTopic(this BotClient? api, string chatId, int messag /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task EditForumTopicAsync(this BotClient? api, long chatId, int messageThreadId, [Optional] string? name, [Optional] string? iconCustomEmojiId, [Optional] CancellationToken cancellationToken) + public static async Task EditForumTopicAsync(this ITelegramBotClient api, long chatId, int messageThreadId, [Optional] string? name, [Optional] string? iconCustomEmojiId, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -105,7 +105,7 @@ public static async Task EditForumTopicAsync(this BotClient? api, long cha await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.EditForumTopic, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.EditForumTopic, stream, cancellationToken).ConfigureAwait(false); } /// @@ -119,7 +119,7 @@ public static async Task EditForumTopicAsync(this BotClient? api, long cha /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task EditForumTopicAsync(this BotClient? api, string chatId, int messageThreadId, [Optional] string? name, [Optional] string? iconCustomEmojiId, [Optional] CancellationToken cancellationToken) + public static async Task EditForumTopicAsync(this ITelegramBotClient api, string chatId, int messageThreadId, [Optional] string? name, [Optional] string? iconCustomEmojiId, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -139,6 +139,6 @@ public static async Task EditForumTopicAsync(this BotClient? api, string c await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.EditForumTopic, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.EditForumTopic, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/editGeneralForumTopic.cs b/src/library/Telegram.BotAPI/Available Methods/editGeneralForumTopic.cs similarity index 86% rename from src/Telegram.BotAPI/Available Methods/editGeneralForumTopic.cs rename to src/library/Telegram.BotAPI/Available Methods/editGeneralForumTopic.cs index 81d00f42..c04240da 100644 --- a/src/Telegram.BotAPI/Available Methods/editGeneralForumTopic.cs +++ b/src/library/Telegram.BotAPI/Available Methods/editGeneralForumTopic.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -20,7 +20,7 @@ public static partial class AvailableMethodsExtensions /// New topic name, 1-128 characters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool EditGeneralForumTopic(this BotClient? api, long chatId, string name) + public static bool EditGeneralForumTopic(this ITelegramBotClient api, long chatId, string name) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -31,7 +31,7 @@ public static bool EditGeneralForumTopic(this BotClient? api, long chatId, strin json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.EditGeneralForumTopic, stream); + return api.CallMethod(MethodNames.EditGeneralForumTopic, stream); } /// @@ -42,7 +42,7 @@ public static bool EditGeneralForumTopic(this BotClient? api, long chatId, strin /// New topic name, 1-128 characters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool EditGeneralForumTopic(this BotClient? api, string chatId, string name) + public static bool EditGeneralForumTopic(this ITelegramBotClient api, string chatId, string name) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -53,7 +53,7 @@ public static bool EditGeneralForumTopic(this BotClient? api, string chatId, str json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.EditGeneralForumTopic, stream); + return api.CallMethod(MethodNames.EditGeneralForumTopic, stream); } /// @@ -65,7 +65,7 @@ public static bool EditGeneralForumTopic(this BotClient? api, string chatId, str /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task EditGeneralForumTopicAsync(this BotClient? api, long chatId, string name, [Optional] CancellationToken cancellationToken) + public static async Task EditGeneralForumTopicAsync(this ITelegramBotClient api, long chatId, string name, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -77,7 +77,7 @@ public static async Task EditGeneralForumTopicAsync(this BotClient? api, l await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.EditGeneralForumTopic, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.EditGeneralForumTopic, stream, cancellationToken).ConfigureAwait(false); } /// @@ -89,7 +89,7 @@ public static async Task EditGeneralForumTopicAsync(this BotClient? api, l /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task EditGeneralForumTopicAsync(this BotClient? api, string chatId, string name, [Optional] CancellationToken cancellationToken) + public static async Task EditGeneralForumTopicAsync(this ITelegramBotClient api, string chatId, string name, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -101,6 +101,6 @@ public static async Task EditGeneralForumTopicAsync(this BotClient? api, s await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.EditGeneralForumTopic, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.EditGeneralForumTopic, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/exportChatInviteLink.cs b/src/library/Telegram.BotAPI/Available Methods/exportChatInviteLink.cs similarity index 86% rename from src/Telegram.BotAPI/Available Methods/exportChatInviteLink.cs rename to src/library/Telegram.BotAPI/Available Methods/exportChatInviteLink.cs index 6c8e2790..cd4335a2 100644 --- a/src/Telegram.BotAPI/Available Methods/exportChatInviteLink.cs +++ b/src/library/Telegram.BotAPI/Available Methods/exportChatInviteLink.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -15,7 +15,7 @@ public static partial class AvailableMethodsExtensions /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static string ExportChatInviteLink(this BotClient? bot, long chatId) + public static string ExportChatInviteLink(this ITelegramBotClient bot, long chatId) { if (bot == default) { @@ -29,14 +29,14 @@ public static string ExportChatInviteLink(this BotClient? bot, long chatId) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.ExportChatInviteLink, stream); + return bot.CallMethod(MethodNames.ExportChatInviteLink, stream); } /// Use this method to generate a new invite link for a chat; any previously generated link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns the new invite link as String on success. /// BotClient /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static string ExportChatInviteLink(this BotClient? bot, string chatId) + public static string ExportChatInviteLink(this ITelegramBotClient bot, string chatId) { if (bot == default) { @@ -50,7 +50,7 @@ public static string ExportChatInviteLink(this BotClient? bot, string chatId) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.ExportChatInviteLink, stream); + return bot.CallMethod(MethodNames.ExportChatInviteLink, stream); } /// Use this method to generate a new invite link for a chat; any previously generated link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns the new invite link as String on success. /// BotClient @@ -58,7 +58,7 @@ public static string ExportChatInviteLink(this BotClient? bot, string chatId) /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task ExportChatInviteLinkAsync(this BotClient? bot, long chatId, [Optional] CancellationToken cancellationToken) + public static async Task ExportChatInviteLinkAsync(this ITelegramBotClient bot, long chatId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -73,7 +73,7 @@ public static async Task ExportChatInviteLinkAsync(this BotClient? bot, await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.ExportChatInviteLink, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.ExportChatInviteLink, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to generate a new invite link for a chat; any previously generated link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns the new invite link as String on success. /// BotClient @@ -81,7 +81,7 @@ public static async Task ExportChatInviteLinkAsync(this BotClient? bot, /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task ExportChatInviteLinkAsync(this BotClient? bot, string chatId, [Optional] CancellationToken cancellationToken) + public static async Task ExportChatInviteLinkAsync(this ITelegramBotClient bot, string chatId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -96,6 +96,6 @@ public static async Task ExportChatInviteLinkAsync(this BotClient? bot, await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.ExportChatInviteLink, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.ExportChatInviteLink, stream, cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Telegram.BotAPI/Available Methods/forwardMessage.cs b/src/library/Telegram.BotAPI/Available Methods/forwardMessage.cs similarity index 86% rename from src/Telegram.BotAPI/Available Methods/forwardMessage.cs rename to src/library/Telegram.BotAPI/Available Methods/forwardMessage.cs index 72b598c8..c2e449d2 100644 --- a/src/Telegram.BotAPI/Available Methods/forwardMessage.cs +++ b/src/library/Telegram.BotAPI/Available Methods/forwardMessage.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -24,7 +24,7 @@ public static partial class AvailableMethodsExtensions /// Protects the contents of the forwarded message from forwarding and saving. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message ForwardMessage(this BotClient? api, long chatId, long fromChatId, int messageId, [Optional] int? messageThreadId, [Optional] bool? disableNotification, [Optional] bool? protectContent) + public static Message ForwardMessage(this ITelegramBotClient api, long chatId, long fromChatId, int messageId, [Optional] int? messageThreadId, [Optional] bool? disableNotification, [Optional] bool? protectContent) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -48,7 +48,7 @@ public static Message ForwardMessage(this BotClient? api, long chatId, long from json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.ForwardMessage, stream); + return api.CallMethod(MethodNames.ForwardMessage, stream); } /// @@ -63,7 +63,7 @@ public static Message ForwardMessage(this BotClient? api, long chatId, long from /// Protects the contents of the forwarded message from forwarding and saving. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message ForwardMessage(this BotClient? api, long chatId, string fromChatId, int messageId, [Optional] int? messageThreadId, [Optional] bool? disableNotification, [Optional] bool? protectContent) + public static Message ForwardMessage(this ITelegramBotClient api, long chatId, string fromChatId, int messageId, [Optional] int? messageThreadId, [Optional] bool? disableNotification, [Optional] bool? protectContent) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -87,7 +87,7 @@ public static Message ForwardMessage(this BotClient? api, long chatId, string fr json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.ForwardMessage, stream); + return api.CallMethod(MethodNames.ForwardMessage, stream); } /// @@ -102,7 +102,7 @@ public static Message ForwardMessage(this BotClient? api, long chatId, string fr /// Protects the contents of the forwarded message from forwarding and saving. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message ForwardMessage(this BotClient? api, string chatId, long fromChatId, int messageId, [Optional] int? messageThreadId, [Optional] bool? disableNotification, [Optional] bool? protectContent) + public static Message ForwardMessage(this ITelegramBotClient api, string chatId, long fromChatId, int messageId, [Optional] int? messageThreadId, [Optional] bool? disableNotification, [Optional] bool? protectContent) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -126,7 +126,7 @@ public static Message ForwardMessage(this BotClient? api, string chatId, long fr json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.ForwardMessage, stream); + return api.CallMethod(MethodNames.ForwardMessage, stream); } /// @@ -141,7 +141,7 @@ public static Message ForwardMessage(this BotClient? api, string chatId, long fr /// Protects the contents of the forwarded message from forwarding and saving. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message ForwardMessage(this BotClient? api, string chatId, string fromChatId, int messageId, [Optional] int? messageThreadId, [Optional] bool? disableNotification, [Optional] bool? protectContent) + public static Message ForwardMessage(this ITelegramBotClient api, string chatId, string fromChatId, int messageId, [Optional] int? messageThreadId, [Optional] bool? disableNotification, [Optional] bool? protectContent) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -165,7 +165,7 @@ public static Message ForwardMessage(this BotClient? api, string chatId, string json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.ForwardMessage, stream); + return api.CallMethod(MethodNames.ForwardMessage, stream); } /// @@ -181,7 +181,7 @@ public static Message ForwardMessage(this BotClient? api, string chatId, string /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task ForwardMessageAsync(this BotClient? api, long chatId, long fromChatId, int messageId, [Optional] int? messageThreadId, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] CancellationToken cancellationToken) + public static async Task ForwardMessageAsync(this ITelegramBotClient api, long chatId, long fromChatId, int messageId, [Optional] int? messageThreadId, [Optional] bool? disableNotification, [Optional] bool? protectContent, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -206,7 +206,7 @@ public static async Task ForwardMessageAsync(this BotClient? api, long await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.ForwardMessage, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.ForwardMessage, stream, cancellationToken).ConfigureAwait(false); } /// @@ -222,7 +222,7 @@ public static async Task ForwardMessageAsync(this BotClient? api, long /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task ForwardMessageAsync(this BotClient? api, long chatId, string fromChatId, int messageId, [Optional] int? messageThreadId, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] CancellationToken cancellationToken) + public static async Task ForwardMessageAsync(this ITelegramBotClient api, long chatId, string fromChatId, int messageId, [Optional] int? messageThreadId, [Optional] bool? disableNotification, [Optional] bool? protectContent, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -247,7 +247,7 @@ public static async Task ForwardMessageAsync(this BotClient? api, long await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.ForwardMessage, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.ForwardMessage, stream, cancellationToken).ConfigureAwait(false); } /// @@ -263,7 +263,7 @@ public static async Task ForwardMessageAsync(this BotClient? api, long /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task ForwardMessageAsync(this BotClient? api, string chatId, long fromChatId, int messageId, [Optional] int? messageThreadId, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] CancellationToken cancellationToken) + public static async Task ForwardMessageAsync(this ITelegramBotClient api, string chatId, long fromChatId, int messageId, [Optional] int? messageThreadId, [Optional] bool? disableNotification, [Optional] bool? protectContent, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -288,7 +288,7 @@ public static async Task ForwardMessageAsync(this BotClient? api, strin await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.ForwardMessage, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.ForwardMessage, stream, cancellationToken).ConfigureAwait(false); } /// @@ -304,7 +304,7 @@ public static async Task ForwardMessageAsync(this BotClient? api, strin /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task ForwardMessageAsync(this BotClient? api, string chatId, string fromChatId, int messageId, [Optional] int? messageThreadId, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] CancellationToken cancellationToken) + public static async Task ForwardMessageAsync(this ITelegramBotClient api, string chatId, string fromChatId, int messageId, [Optional] int? messageThreadId, [Optional] bool? disableNotification, [Optional] bool? protectContent, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -329,6 +329,6 @@ public static async Task ForwardMessageAsync(this BotClient? api, strin await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.ForwardMessage, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.ForwardMessage, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/library/Telegram.BotAPI/Available Methods/forwardMessages.cs b/src/library/Telegram.BotAPI/Available Methods/forwardMessages.cs new file mode 100644 index 00000000..22b46d16 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Methods/forwardMessages.cs @@ -0,0 +1,216 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System.Threading; +using System.Threading.Tasks; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.AvailableMethods; + +/// Available Methods +public static partial class AvailableMethodsExtensions +{ + /// + /// Use this method to forward multiple messages of any kind. If some of the specified messages can't be found or forwarded, they are skipped. Service messages and messages with protected content can't be forwarded. Album grouping is kept for forwarded messages. On success, an array of MessageId of the sent messages is returned. + /// + /// The bot client. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername). + /// Identifiers of 1-100 messages in the chat from_chat_id to forward. The identifiers must be specified in a strictly increasing order. + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. + /// Sends the messages silently. Users will receive a notification with no sound. + /// Protects the contents of the forwarded messages from forwarding and saving. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static IEnumerable ForwardMessages(this ITelegramBotClient client, long chatId, long fromChatId, IEnumerable messageIds, int? messageThreadId = null, bool? disableNotification = null, bool? protectContent = null) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new ForwardMessagesArgs(chatId, fromChatId, messageIds) + { + MessageThreadId = messageThreadId, + DisableNotification = disableNotification, + ProtectContent = protectContent + }; + return client.CallMethod>(MethodNames.ForwardMessages, args); + } + + /// + /// Use this method to forward multiple messages of any kind. If some of the specified messages can't be found or forwarded, they are skipped. Service messages and messages with protected content can't be forwarded. Album grouping is kept for forwarded messages. On success, an array of MessageId of the sent messages is returned. + /// + /// The bot client. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername). + /// Identifiers of 1-100 messages in the chat from_chat_id to forward. The identifiers must be specified in a strictly increasing order. + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. + /// Sends the messages silently. Users will receive a notification with no sound. + /// Protects the contents of the forwarded messages from forwarding and saving. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static IEnumerable ForwardMessages(this ITelegramBotClient client, long chatId, string fromChatId, IEnumerable messageIds, int? messageThreadId = null, bool? disableNotification = null, bool? protectContent = null) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new ForwardMessagesArgs(chatId, fromChatId, messageIds) + { + MessageThreadId = messageThreadId, + DisableNotification = disableNotification, + ProtectContent = protectContent + }; + return client.CallMethod>(MethodNames.ForwardMessages, args); + } + + /// + /// Use this method to forward multiple messages of any kind. If some of the specified messages can't be found or forwarded, they are skipped. Service messages and messages with protected content can't be forwarded. Album grouping is kept for forwarded messages. On success, an array of MessageId of the sent messages is returned. + /// + /// The bot client. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername). + /// Identifiers of 1-100 messages in the chat from_chat_id to forward. The identifiers must be specified in a strictly increasing order. + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. + /// Sends the messages silently. Users will receive a notification with no sound. + /// Protects the contents of the forwarded messages from forwarding and saving. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static IEnumerable ForwardMessages(this ITelegramBotClient client, string chatId, long fromChatId, IEnumerable messageIds, int? messageThreadId = null, bool? disableNotification = null, bool? protectContent = null) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new ForwardMessagesArgs(chatId, fromChatId, messageIds) + { + MessageThreadId = messageThreadId, + DisableNotification = disableNotification, + ProtectContent = protectContent + }; + return client.CallMethod>(MethodNames.ForwardMessages, args); + } + + /// + /// Use this method to forward multiple messages of any kind. If some of the specified messages can't be found or forwarded, they are skipped. Service messages and messages with protected content can't be forwarded. Album grouping is kept for forwarded messages. On success, an array of MessageId of the sent messages is returned. + /// + /// The bot client. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername). + /// Identifiers of 1-100 messages in the chat from_chat_id to forward. The identifiers must be specified in a strictly increasing order. + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. + /// Sends the messages silently. Users will receive a notification with no sound. + /// Protects the contents of the forwarded messages from forwarding and saving. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static IEnumerable ForwardMessages(this ITelegramBotClient client, string chatId, string fromChatId, IEnumerable messageIds, int? messageThreadId = null, bool? disableNotification = null, bool? protectContent = null) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new ForwardMessagesArgs(chatId, fromChatId, messageIds) + { + MessageThreadId = messageThreadId, + DisableNotification = disableNotification, + ProtectContent = protectContent + }; + return client.CallMethod>(MethodNames.ForwardMessages, args); + } + + /// + /// Use this method to forward multiple messages of any kind. If some of the specified messages can't be found or forwarded, they are skipped. Service messages and messages with protected content can't be forwarded. Album grouping is kept for forwarded messages. On success, an array of MessageId of the sent messages is returned. + /// + /// The bot client. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername). + /// Identifiers of 1-100 messages in the chat from_chat_id to forward. The identifiers must be specified in a strictly increasing order. + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. + /// Sends the messages silently. Users will receive a notification with no sound. + /// Protects the contents of the forwarded messages from forwarding and saving. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static async Task> ForwardMessagesAsync(this ITelegramBotClient client, long chatId, long fromChatId, IEnumerable messageIds, int? messageThreadId = null, bool? disableNotification = null, bool? protectContent = null, CancellationToken cancellationToken = default) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new ForwardMessagesArgs(chatId, fromChatId, messageIds) + { + MessageThreadId = messageThreadId, + DisableNotification = disableNotification, + ProtectContent = protectContent + }; + return await client.CallMethodAsync>(MethodNames.ForwardMessages, args, cancellationToken).ConfigureAwait(false); + } + + /// + /// Use this method to forward multiple messages of any kind. If some of the specified messages can't be found or forwarded, they are skipped. Service messages and messages with protected content can't be forwarded. Album grouping is kept for forwarded messages. On success, an array of MessageId of the sent messages is returned. + /// + /// The bot client. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername). + /// Identifiers of 1-100 messages in the chat from_chat_id to forward. The identifiers must be specified in a strictly increasing order. + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. + /// Sends the messages silently. Users will receive a notification with no sound. + /// Protects the contents of the forwarded messages from forwarding and saving. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static async Task> ForwardMessagesAsync(this ITelegramBotClient client, long chatId, string fromChatId, IEnumerable messageIds, int? messageThreadId = null, bool? disableNotification = null, bool? protectContent = null, CancellationToken cancellationToken = default) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new ForwardMessagesArgs(chatId, fromChatId, messageIds) + { + MessageThreadId = messageThreadId, + DisableNotification = disableNotification, + ProtectContent = protectContent + }; + return await client.CallMethodAsync>(MethodNames.ForwardMessages, args, cancellationToken).ConfigureAwait(false); + } + + /// + /// Use this method to forward multiple messages of any kind. If some of the specified messages can't be found or forwarded, they are skipped. Service messages and messages with protected content can't be forwarded. Album grouping is kept for forwarded messages. On success, an array of MessageId of the sent messages is returned. + /// + /// The bot client. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername). + /// Identifiers of 1-100 messages in the chat from_chat_id to forward. The identifiers must be specified in a strictly increasing order. + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. + /// Sends the messages silently. Users will receive a notification with no sound. + /// Protects the contents of the forwarded messages from forwarding and saving. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static async Task> ForwardMessagesAsync(this ITelegramBotClient client, string chatId, long fromChatId, IEnumerable messageIds, int? messageThreadId = null, bool? disableNotification = null, bool? protectContent = null, CancellationToken cancellationToken = default) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new ForwardMessagesArgs(chatId, fromChatId, messageIds) + { + MessageThreadId = messageThreadId, + DisableNotification = disableNotification, + ProtectContent = protectContent + }; + return await client.CallMethodAsync>(MethodNames.ForwardMessages, args, cancellationToken).ConfigureAwait(false); + } + + /// + /// Use this method to forward multiple messages of any kind. If some of the specified messages can't be found or forwarded, they are skipped. Service messages and messages with protected content can't be forwarded. Album grouping is kept for forwarded messages. On success, an array of MessageId of the sent messages is returned. + /// + /// The bot client. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Unique identifier for the chat where the original messages were sent (or channel username in the format @channelusername). + /// Identifiers of 1-100 messages in the chat from_chat_id to forward. The identifiers must be specified in a strictly increasing order. + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. + /// Sends the messages silently. Users will receive a notification with no sound. + /// Protects the contents of the forwarded messages from forwarding and saving. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static async Task> ForwardMessagesAsync(this ITelegramBotClient client, string chatId, string fromChatId, IEnumerable messageIds, int? messageThreadId = null, bool? disableNotification = null, bool? protectContent = null, CancellationToken cancellationToken = default) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new ForwardMessagesArgs(chatId, fromChatId, messageIds) + { + MessageThreadId = messageThreadId, + DisableNotification = disableNotification, + ProtectContent = protectContent + }; + return await client.CallMethodAsync>(MethodNames.ForwardMessages, args, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Telegram.BotAPI/Available Methods/getChat.cs b/src/library/Telegram.BotAPI/Available Methods/getChat.cs similarity index 85% rename from src/Telegram.BotAPI/Available Methods/getChat.cs rename to src/library/Telegram.BotAPI/Available Methods/getChat.cs index e768e39f..c05f7452 100644 --- a/src/Telegram.BotAPI/Available Methods/getChat.cs +++ b/src/library/Telegram.BotAPI/Available Methods/getChat.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -17,7 +17,7 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Chat Object. - public static Chat GetChat(this BotClient? bot, string chatId) + public static Chat GetChat(this ITelegramBotClient bot, string chatId) { if (bot == default) { @@ -31,7 +31,7 @@ public static Chat GetChat(this BotClient? bot, string chatId) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.GetChat, stream); + return bot.CallMethod(MethodNames.GetChat, stream); } /// Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success. /// BotClient @@ -39,7 +39,7 @@ public static Chat GetChat(this BotClient? bot, string chatId) /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Chat Object. - public static Chat GetChat(this BotClient? bot, long chatId) + public static Chat GetChat(this ITelegramBotClient bot, long chatId) { if (bot == default) { @@ -53,7 +53,7 @@ public static Chat GetChat(this BotClient? bot, long chatId) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.GetChat, stream); + return bot.CallMethod(MethodNames.GetChat, stream); } /// Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success. /// BotClient @@ -62,7 +62,7 @@ public static Chat GetChat(this BotClient? bot, long chatId) /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Chat Object. - public static async Task GetChatAsync(this BotClient? bot, string chatId, [Optional] CancellationToken cancellationToken) + public static async Task GetChatAsync(this ITelegramBotClient bot, string chatId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -76,7 +76,7 @@ public static async Task GetChatAsync(this BotClient? bot, string chatId, json.WriteEndObject(); await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.GetChat, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetChat, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success. /// BotClient @@ -85,7 +85,7 @@ public static async Task GetChatAsync(this BotClient? bot, string chatId, /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Chat Object. - public static async Task GetChatAsync(this BotClient? bot, long chatId, [Optional] CancellationToken cancellationToken) + public static async Task GetChatAsync(this ITelegramBotClient bot, long chatId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -99,6 +99,6 @@ public static async Task GetChatAsync(this BotClient? bot, long chatId, [O json.WriteEndObject(); await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.GetChat, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetChat, stream, cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Telegram.BotAPI/Available Methods/getChatAdministrators.cs b/src/library/Telegram.BotAPI/Available Methods/getChatAdministrators.cs similarity index 87% rename from src/Telegram.BotAPI/Available Methods/getChatAdministrators.cs rename to src/library/Telegram.BotAPI/Available Methods/getChatAdministrators.cs index 1e04e9aa..af345f56 100644 --- a/src/Telegram.BotAPI/Available Methods/getChatAdministrators.cs +++ b/src/library/Telegram.BotAPI/Available Methods/getChatAdministrators.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -17,7 +17,7 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Array de ChatMember Object. - public static ChatMember[] GetChatAdministrators(this BotClient? bot, long chatId) + public static ChatMember[] GetChatAdministrators(this ITelegramBotClient bot, long chatId) { if (bot == default) { @@ -31,7 +31,7 @@ public static ChatMember[] GetChatAdministrators(this BotClient? bot, long chatI json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.GetChatAdministrators, stream); + return bot.CallMethod(MethodNames.GetChatAdministrators, stream); } /// Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned. /// BotClient @@ -39,7 +39,7 @@ public static ChatMember[] GetChatAdministrators(this BotClient? bot, long chatI /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Array de ChatMember Object. - public static ChatMember[] GetChatAdministrators(this BotClient? bot, string chatId) + public static ChatMember[] GetChatAdministrators(this ITelegramBotClient bot, string chatId) { if (bot == default) { @@ -53,7 +53,7 @@ public static ChatMember[] GetChatAdministrators(this BotClient? bot, string cha json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.GetChatAdministrators, stream); + return bot.CallMethod(MethodNames.GetChatAdministrators, stream); } /// Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned. /// BotClient @@ -62,7 +62,7 @@ public static ChatMember[] GetChatAdministrators(this BotClient? bot, string cha /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Array de ChatMember Object. - public static async Task GetChatAdministratorsAsync(this BotClient? bot, long chatId, [Optional] CancellationToken cancellationToken) + public static async Task GetChatAdministratorsAsync(this ITelegramBotClient bot, long chatId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -77,7 +77,7 @@ public static async Task GetChatAdministratorsAsync(this BotClient await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.GetChatAdministrators, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetChatAdministrators, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned. /// BotClient @@ -86,7 +86,7 @@ public static async Task GetChatAdministratorsAsync(this BotClient /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Array de ChatMember Object. - public static async Task GetChatAdministratorsAsync(this BotClient? bot, string chatId, [Optional] CancellationToken cancellationToken) + public static async Task GetChatAdministratorsAsync(this ITelegramBotClient bot, string chatId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -101,7 +101,7 @@ public static async Task GetChatAdministratorsAsync(this BotClient await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.GetChatAdministrators, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetChatAdministrators, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned. /// BotClient @@ -109,7 +109,7 @@ public static async Task GetChatAdministratorsAsync(this BotClient /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Array de ChatMember Object. - public static T GetChatAdministrators(this BotClient? bot, long chatId) + public static T GetChatAdministrators(this ITelegramBotClient bot, long chatId) where T : IEnumerable { if (bot == default) @@ -124,7 +124,7 @@ public static T GetChatAdministrators(this BotClient? bot, long chatId) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.GetChatAdministrators, stream); + return bot.CallMethod(MethodNames.GetChatAdministrators, stream); } /// Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned. /// BotClient @@ -132,7 +132,7 @@ public static T GetChatAdministrators(this BotClient? bot, long chatId) /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Array de ChatMember Object. - public static T GetChatAdministrators(this BotClient? bot, string chatId) + public static T GetChatAdministrators(this ITelegramBotClient bot, string chatId) where T : IEnumerable { if (bot == default) @@ -147,7 +147,7 @@ public static T GetChatAdministrators(this BotClient? bot, string chatId) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.GetChatAdministrators, stream); + return bot.CallMethod(MethodNames.GetChatAdministrators, stream); } /// Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned. /// BotClient @@ -156,7 +156,7 @@ public static T GetChatAdministrators(this BotClient? bot, string chatId) /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Array de ChatMember Object. - public static async Task GetChatAdministratorsAsync(this BotClient? bot, long chatId, [Optional] CancellationToken cancellationToken) + public static async Task GetChatAdministratorsAsync(this ITelegramBotClient bot, long chatId, CancellationToken cancellationToken = default) where T : IEnumerable { if (bot == default) @@ -172,7 +172,7 @@ public static async Task GetChatAdministratorsAsync(this BotClient? bot, l await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.GetChatAdministrators, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetChatAdministrators, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned. /// BotClient @@ -181,7 +181,7 @@ public static async Task GetChatAdministratorsAsync(this BotClient? bot, l /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Array de ChatMember Object. - public static async Task GetChatAdministratorsAsync(this BotClient? bot, string chatId, [Optional] CancellationToken cancellationToken) + public static async Task GetChatAdministratorsAsync(this ITelegramBotClient bot, string chatId, CancellationToken cancellationToken = default) where T : IEnumerable { if (bot == default) @@ -197,6 +197,6 @@ public static async Task GetChatAdministratorsAsync(this BotClient? bot, s await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.GetChatAdministrators, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetChatAdministrators, stream, cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Telegram.BotAPI/Available Methods/getChatMember.cs b/src/library/Telegram.BotAPI/Available Methods/getChatMember.cs similarity index 83% rename from src/Telegram.BotAPI/Available Methods/getChatMember.cs rename to src/library/Telegram.BotAPI/Available Methods/getChatMember.cs index 48c8544a..059e4ab2 100644 --- a/src/Telegram.BotAPI/Available Methods/getChatMember.cs +++ b/src/library/Telegram.BotAPI/Available Methods/getChatMember.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -18,7 +18,7 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static ChatMember GetChatMember(this BotClient? bot, string chatId, long userId) + public static ChatMember GetChatMember(this ITelegramBotClient bot, string chatId, long userId) { if (bot == default) { @@ -33,7 +33,7 @@ public static ChatMember GetChatMember(this BotClient? bot, string chatId, long json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.GetChatMember, stream); + return bot.CallMethod(MethodNames.GetChatMember, stream); } /// Use this method to get information about a member of a chat. Returns a ChatMember object on success. /// BotClient @@ -42,7 +42,7 @@ public static ChatMember GetChatMember(this BotClient? bot, string chatId, long /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static ChatMember GetChatMember(this BotClient? bot, long chatId, long userId) + public static ChatMember GetChatMember(this ITelegramBotClient bot, long chatId, long userId) { if (bot == default) { @@ -57,7 +57,7 @@ public static ChatMember GetChatMember(this BotClient? bot, long chatId, long us json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.GetChatMember, stream); + return bot.CallMethod(MethodNames.GetChatMember, stream); } /// Use this method to get information about a member of a chat. Returns a ChatMember object on success. /// BotClient @@ -67,7 +67,7 @@ public static ChatMember GetChatMember(this BotClient? bot, long chatId, long us /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static async Task GetChatMemberAsync(this BotClient? bot, long chatId, long userId, [Optional] CancellationToken cancellationToken) + public static async Task GetChatMemberAsync(this ITelegramBotClient bot, long chatId, long userId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -82,7 +82,7 @@ public static async Task GetChatMemberAsync(this BotClient? bot, lon json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.GetChatMember, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetChatMember, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to get information about a member of a chat. Returns a ChatMember object on success. /// BotClient @@ -92,7 +92,7 @@ public static async Task GetChatMemberAsync(this BotClient? bot, lon /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static async Task GetChatMemberAsync(this BotClient? bot, string chatId, long userId, [Optional] CancellationToken cancellationToken) + public static async Task GetChatMemberAsync(this ITelegramBotClient bot, string chatId, long userId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -107,6 +107,6 @@ public static async Task GetChatMemberAsync(this BotClient? bot, str json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.GetChatMember, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetChatMember, stream, cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Telegram.BotAPI/Available Methods/getChatMemberCount.cs b/src/library/Telegram.BotAPI/Available Methods/getChatMemberCount.cs similarity index 82% rename from src/Telegram.BotAPI/Available Methods/getChatMemberCount.cs rename to src/library/Telegram.BotAPI/Available Methods/getChatMemberCount.cs index 69ef3fa8..8224ba53 100644 --- a/src/Telegram.BotAPI/Available Methods/getChatMemberCount.cs +++ b/src/library/Telegram.BotAPI/Available Methods/getChatMemberCount.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -15,7 +15,7 @@ public static partial class AvailableMethodsExtensions /// Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername). /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static uint GetChatMemberCount(this BotClient? bot, long chatId) + public static uint GetChatMemberCount(this ITelegramBotClient bot, long chatId) { if (bot == default) { @@ -29,14 +29,14 @@ public static uint GetChatMemberCount(this BotClient? bot, long chatId) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.GetChatMemberCount, stream); + return bot.CallMethod(MethodNames.GetChatMemberCount, stream); } /// Use this method to get the number of members in a chat. Returns Int on success. /// BotClient /// Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername). /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static uint GetChatMemberCount(this BotClient? bot, string chatId) + public static uint GetChatMemberCount(this ITelegramBotClient bot, string chatId) { if (bot == default) { @@ -50,7 +50,7 @@ public static uint GetChatMemberCount(this BotClient? bot, string chatId) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.GetChatMemberCount, stream); + return bot.CallMethod(MethodNames.GetChatMemberCount, stream); } /// Use this method to get the number of members in a chat. Returns Int on success. /// BotClient @@ -58,7 +58,7 @@ public static uint GetChatMemberCount(this BotClient? bot, string chatId) /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task GetChatMemberCountAsync(this BotClient? bot, long chatId, [Optional] CancellationToken cancellationToken) + public static async Task GetChatMemberCountAsync(this ITelegramBotClient bot, long chatId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -73,7 +73,7 @@ public static async Task GetChatMemberCountAsync(this BotClient? bot, long await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.GetChatMemberCount, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetChatMemberCount, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to get the number of members in a chat. Returns Int on success. /// BotClient @@ -81,7 +81,7 @@ public static async Task GetChatMemberCountAsync(this BotClient? bot, long /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task GetChatMemberCountAsync(this BotClient? bot, string chatId, [Optional] CancellationToken cancellationToken) + public static async Task GetChatMemberCountAsync(this ITelegramBotClient bot, string chatId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -96,6 +96,6 @@ public static async Task GetChatMemberCountAsync(this BotClient? bot, stri await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.GetChatMemberCount, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetChatMemberCount, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/getFile.cs b/src/library/Telegram.BotAPI/Available Methods/getFile.cs similarity index 83% rename from src/Telegram.BotAPI/Available Methods/getFile.cs rename to src/library/Telegram.BotAPI/Available Methods/getFile.cs index bf9823de..8566cd8e 100644 --- a/src/Telegram.BotAPI/Available Methods/getFile.cs +++ b/src/library/Telegram.BotAPI/Available Methods/getFile.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -17,7 +17,7 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static File GetFile(this BotClient? bot, string fileId) + public static File GetFile(this ITelegramBotClient bot, string fileId) { if (bot == default) { @@ -31,7 +31,7 @@ public static File GetFile(this BotClient? bot, string fileId) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.GetFile, stream); + return bot.CallMethod(MethodNames.GetFile, stream); } /// Use this method to get basic info about a file and prepare it for downloading.. On success, a File object is returned. /// BotClient @@ -40,7 +40,7 @@ public static File GetFile(this BotClient? bot, string fileId) /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static async Task GetFileAsync(this BotClient? bot, string fileId, [Optional] CancellationToken cancellationToken) + public static async Task GetFileAsync(this ITelegramBotClient bot, string fileId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -54,6 +54,6 @@ public static async Task GetFileAsync(this BotClient? bot, string fileId, json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.GetFile, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetFile, stream, cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Telegram.BotAPI/Available Methods/getForumTopicIconStickers.cs b/src/library/Telegram.BotAPI/Available Methods/getForumTopicIconStickers.cs similarity index 79% rename from src/Telegram.BotAPI/Available Methods/getForumTopicIconStickers.cs rename to src/library/Telegram.BotAPI/Available Methods/getForumTopicIconStickers.cs index 538db079..795da2d3 100644 --- a/src/Telegram.BotAPI/Available Methods/getForumTopicIconStickers.cs +++ b/src/library/Telegram.BotAPI/Available Methods/getForumTopicIconStickers.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -15,10 +15,10 @@ public static partial class AvailableMethodsExtensions /// The bot client. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Sticker[] GetForumTopicIconStickers(this BotClient? api) + public static Sticker[] GetForumTopicIconStickers(this ITelegramBotClient api) { if (api == null) { throw new ArgumentNullException(nameof(api)); } - return api.RPC(MethodNames.GetForumTopicIconStickers); + return api.CallMethod(MethodNames.GetForumTopicIconStickers); } /// @@ -28,9 +28,9 @@ public static Sticker[] GetForumTopicIconStickers(this BotClient? api) /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task GetForumTopicIconStickersAsync(this BotClient? api, [Optional] CancellationToken cancellationToken) + public static async Task GetForumTopicIconStickersAsync(this ITelegramBotClient api, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } - return await api.RPCA(MethodNames.GetForumTopicIconStickers, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.GetForumTopicIconStickers, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/getMe.cs b/src/library/Telegram.BotAPI/Available Methods/getMe.cs similarity index 79% rename from src/Telegram.BotAPI/Available Methods/getMe.cs rename to src/library/Telegram.BotAPI/Available Methods/getMe.cs index 222ed88b..b02c2ab1 100644 --- a/src/Telegram.BotAPI/Available Methods/getMe.cs +++ b/src/library/Telegram.BotAPI/Available Methods/getMe.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -14,14 +14,14 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// User Object. - public static User GetMe(this BotClient? bot) + public static User GetMe(this ITelegramBotClient bot) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } - return bot.RPC(MethodNames.GetMe); + return bot.CallMethod(MethodNames.GetMe); } /// A simple method for testing your bot's auth token. Returns basic information about the bot in form of a User object. /// Bot Client @@ -29,13 +29,13 @@ public static User GetMe(this BotClient? bot) /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// User Object. - public static async Task GetMeAsync(this BotClient? bot, [Optional] CancellationToken cancellationToken) + public static async Task GetMeAsync(this ITelegramBotClient bot, CancellationToken cancellationToken = default) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } - return await bot.RPCA(MethodNames.GetMe, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetMe, cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Telegram.BotAPI/Available Methods/getMyCommands.cs b/src/library/Telegram.BotAPI/Available Methods/getMyCommands.cs similarity index 81% rename from src/Telegram.BotAPI/Available Methods/getMyCommands.cs rename to src/library/Telegram.BotAPI/Available Methods/getMyCommands.cs index 406ba45d..a677cdc1 100644 --- a/src/Telegram.BotAPI/Available Methods/getMyCommands.cs +++ b/src/library/Telegram.BotAPI/Available Methods/getMyCommands.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -16,7 +16,7 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Array of on success. If commands aren't set, an empty list is returned. - public static BotCommand[] GetMyCommands(this BotClient? bot, [Optional] BotCommandScope scope, [Optional] string languageCode) => bot.GetMyCommands(scope, languageCode); + public static BotCommand[] GetMyCommands(this ITelegramBotClient bot, [Optional] BotCommandScope scope, [Optional] string languageCode) => bot.GetMyCommands(scope, languageCode); /// Use this method to get the current list of the bot's commands for the given scope and user language. /// BotClient @@ -25,7 +25,7 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Array of on success. If commands aren't set, an empty list is returned. - public static TValue GetMyCommands(this BotClient? bot, [Optional] BotCommandScope scope, [Optional] string languageCode) + public static TValue GetMyCommands(this ITelegramBotClient bot, [Optional] BotCommandScope scope, [Optional] string languageCode) where TValue : IEnumerable { if (bot == null) @@ -34,7 +34,7 @@ public static TValue GetMyCommands(this BotClient? bot, [Optional] BotCo } var args = new GetMyCommandsArgs(scope, languageCode); - return bot.RPC(MethodNames.GetMyCommands, args); + return bot.CallMethod(MethodNames.GetMyCommands, args); } /// Use this method to get the current list of the bot's commands for the given scope and user language. @@ -43,7 +43,7 @@ public static TValue GetMyCommands(this BotClient? bot, [Optional] BotCo /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Array of on success. If commands aren't set, an empty list is returned. - public static BotCommand[] GetMyCommands(this BotClient? bot, GetMyCommandsArgs args) => bot.GetMyCommands(args); + public static BotCommand[] GetMyCommands(this ITelegramBotClient bot, GetMyCommandsArgs args) => bot.GetMyCommands(args); /// Use this method to get the current list of the bot's commands for the given scope and user language. /// BotClient @@ -51,7 +51,7 @@ public static TValue GetMyCommands(this BotClient? bot, [Optional] BotCo /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Array of on success. If commands aren't set, an empty list is returned. - public static TValue GetMyCommands(this BotClient? bot, GetMyCommandsArgs args) + public static TValue GetMyCommands(this ITelegramBotClient bot, GetMyCommandsArgs args) where TValue : IEnumerable { if (bot == null) @@ -62,7 +62,7 @@ public static TValue GetMyCommands(this BotClient? bot, GetMyCommandsArg { throw new ArgumentNullException(nameof(args)); } - return bot.RPC(MethodNames.GetMyCommands, args); + return bot.CallMethod(MethodNames.GetMyCommands, args); } /// Use this method to get the current list of the bot's commands for the given scope and user language. @@ -73,7 +73,7 @@ public static TValue GetMyCommands(this BotClient? bot, GetMyCommandsArg /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Array of on success. If commands aren't set, an empty list is returned. - public static async Task GetMyCommandsAsync(this BotClient? bot, [Optional] BotCommandScope scope, [Optional] string languageCode, [Optional] CancellationToken cancellationToken) => await bot.GetMyCommandsAsync(scope, languageCode, cancellationToken); + public static async Task GetMyCommandsAsync(this ITelegramBotClient bot, [Optional] BotCommandScope scope, [Optional] string languageCode, CancellationToken cancellationToken = default) => await bot.GetMyCommandsAsync(scope, languageCode, cancellationToken); /// Use this method to get the current list of the bot's commands for the given scope and user language. /// BotClient @@ -83,7 +83,7 @@ public static TValue GetMyCommands(this BotClient? bot, GetMyCommandsArg /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Array of on success. If commands aren't set, an empty list is returned. on success. If commands aren't set, an empty list is returned. - public static async Task GetMyCommandsAsync(this BotClient? bot, [Optional] BotCommandScope scope, [Optional] string languageCode, [Optional] CancellationToken cancellationToken) + public static async Task GetMyCommandsAsync(this ITelegramBotClient bot, [Optional] BotCommandScope scope, [Optional] string languageCode, CancellationToken cancellationToken = default) where TValue : IEnumerable { if (bot == null) @@ -92,7 +92,7 @@ public static async Task GetMyCommandsAsync(this BotClient? bot, } var args = new GetMyCommandsArgs(scope, languageCode); - return await bot.RPCA(MethodNames.GetMyCommands, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetMyCommands, args, cancellationToken: cancellationToken).ConfigureAwait(false); } /// Use this method to get the current list of the bot's commands for the given scope and user language. @@ -102,7 +102,7 @@ public static async Task GetMyCommandsAsync(this BotClient? bot, /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Array of on success. If commands aren't set, an empty list is returned. on success. If commands aren't set, an empty list is returned. - public static async Task GetMyCommandsAsync(this BotClient? bot, GetMyCommandsArgs args, [Optional] CancellationToken cancellationToken) => await bot.GetMyCommandsAsync(args, cancellationToken); + public static async Task GetMyCommandsAsync(this ITelegramBotClient bot, GetMyCommandsArgs args, CancellationToken cancellationToken = default) => await bot.GetMyCommandsAsync(args, cancellationToken); /// Use this method to get the current list of the bot's commands for the given scope and user language. /// BotClient @@ -111,7 +111,7 @@ public static async Task GetMyCommandsAsync(this BotClient? bot, /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Array of on success. If commands aren't set, an empty list is returned. on success. If commands aren't set, an empty list is returned. - public static async Task GetMyCommandsAsync(this BotClient? bot, GetMyCommandsArgs args, [Optional] CancellationToken cancellationToken) + public static async Task GetMyCommandsAsync(this ITelegramBotClient bot, GetMyCommandsArgs args, CancellationToken cancellationToken = default) where TValue : IEnumerable { if (bot == null) @@ -122,6 +122,6 @@ public static async Task GetMyCommandsAsync(this BotClient? bot, { throw new ArgumentNullException(nameof(args)); } - return await bot.RPCA(MethodNames.GetMyCommands, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetMyCommands, args, cancellationToken: cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/getMyDefaultAdministratorRights.cs b/src/library/Telegram.BotAPI/Available Methods/getMyDefaultAdministratorRights.cs similarity index 84% rename from src/Telegram.BotAPI/Available Methods/getMyDefaultAdministratorRights.cs rename to src/library/Telegram.BotAPI/Available Methods/getMyDefaultAdministratorRights.cs index 82dec828..c380e158 100644 --- a/src/Telegram.BotAPI/Available Methods/getMyDefaultAdministratorRights.cs +++ b/src/library/Telegram.BotAPI/Available Methods/getMyDefaultAdministratorRights.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -17,7 +17,7 @@ public static partial class AvailableMethodsExtensions /// Pass True to get default administrator rights of the bot in channels. Otherwise, default administrator rights of the bot for groups and supergroups will be returned. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static ChatAdministratorRights GetMyDefaultAdministratorRights(this BotClient? api, [Optional] bool? forChannels) + public static ChatAdministratorRights GetMyDefaultAdministratorRights(this ITelegramBotClient api, [Optional] bool? forChannels) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -30,7 +30,7 @@ public static ChatAdministratorRights GetMyDefaultAdministratorRights(this BotCl json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.GetMyDefaultAdministratorRights, stream); + return api.CallMethod(MethodNames.GetMyDefaultAdministratorRights, stream); } /// Use this method to get the current default administrator rights of the bot. Returns ChatAdministratorRights on success. @@ -39,7 +39,7 @@ public static ChatAdministratorRights GetMyDefaultAdministratorRights(this BotCl /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task GetMyDefaultAdministratorRightsAsync(this BotClient? api, [Optional] bool? forChannels, [Optional] CancellationToken cancellationToken) + public static async Task GetMyDefaultAdministratorRightsAsync(this ITelegramBotClient api, [Optional] bool? forChannels, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -53,6 +53,6 @@ public static async Task GetMyDefaultAdministratorRight await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.GetMyDefaultAdministratorRights, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.GetMyDefaultAdministratorRights, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/getMyDescription.cs b/src/library/Telegram.BotAPI/Available Methods/getMyDescription.cs similarity index 83% rename from src/Telegram.BotAPI/Available Methods/getMyDescription.cs rename to src/library/Telegram.BotAPI/Available Methods/getMyDescription.cs index 89619d85..c0573aef 100644 --- a/src/Telegram.BotAPI/Available Methods/getMyDescription.cs +++ b/src/library/Telegram.BotAPI/Available Methods/getMyDescription.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -18,7 +18,7 @@ public static partial class AvailableMethodsExtensions /// A two-letter ISO 639-1 language code or an empty string. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static BotDescription GetMyDescription(this BotClient? bot, [Optional] string? languageCode) + public static BotDescription GetMyDescription(this ITelegramBotClient bot, [Optional] string? languageCode) { if (bot == default) { @@ -35,7 +35,7 @@ public static BotDescription GetMyDescription(this BotClient? bot, [Optional] st json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.GetMyDescription, stream); + return bot.CallMethod(MethodNames.GetMyDescription, stream); } /// @@ -46,7 +46,7 @@ public static BotDescription GetMyDescription(this BotClient? bot, [Optional] st /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task GetMyDescriptionAsync(this BotClient? bot, [Optional] string? languageCode, [Optional] CancellationToken cancellationToken) + public static async Task GetMyDescriptionAsync(this ITelegramBotClient bot, [Optional] string? languageCode, CancellationToken cancellationToken = default) { if (bot == default) { @@ -64,6 +64,6 @@ public static async Task GetMyDescriptionAsync(this BotClient? b await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.GetMyDescription, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetMyDescription, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/getMyName.cs b/src/library/Telegram.BotAPI/Available Methods/getMyName.cs similarity index 78% rename from src/Telegram.BotAPI/Available Methods/getMyName.cs rename to src/library/Telegram.BotAPI/Available Methods/getMyName.cs index 4b0f0dc5..257d9332 100644 --- a/src/Telegram.BotAPI/Available Methods/getMyName.cs +++ b/src/library/Telegram.BotAPI/Available Methods/getMyName.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -18,7 +18,7 @@ public static partial class AvailableMethodsExtensions /// A two-letter ISO 639-1 language code or an empty string. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static BotName GetMyName(this BotClient api, [Optional] string? languageCode) + public static BotName GetMyName(this ITelegramBotClient api, [Optional] string? languageCode) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -26,12 +26,12 @@ public static BotName GetMyName(this BotClient api, [Optional] string? languageC json.WriteStartObject(); if (languageCode is not null) { - json.WriteString(PropertyNames.LanguageCode, (string)languageCode); + json.WriteString(PropertyNames.LanguageCode, languageCode); } json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.GetMyName, stream); + return api.CallMethod(MethodNames.GetMyName, stream); } /// @@ -42,7 +42,7 @@ public static BotName GetMyName(this BotClient api, [Optional] string? languageC /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task GetMyNameAsync(this BotClient api, [Optional] string? languageCode, [Optional] CancellationToken cancellationToken) + public static async Task GetMyNameAsync(this ITelegramBotClient api, [Optional] string? languageCode, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -50,12 +50,12 @@ public static async Task GetMyNameAsync(this BotClient api, [Optional] json.WriteStartObject(); if (languageCode is not null) { - json.WriteString(PropertyNames.LanguageCode, (string)languageCode); + json.WriteString(PropertyNames.LanguageCode, languageCode); } json.WriteEndObject(); await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.GetMyName, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.GetMyName, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/getMyShortDescription.cs b/src/library/Telegram.BotAPI/Available Methods/getMyShortDescription.cs similarity index 82% rename from src/Telegram.BotAPI/Available Methods/getMyShortDescription.cs rename to src/library/Telegram.BotAPI/Available Methods/getMyShortDescription.cs index fa87afa4..92df8fb2 100644 --- a/src/Telegram.BotAPI/Available Methods/getMyShortDescription.cs +++ b/src/library/Telegram.BotAPI/Available Methods/getMyShortDescription.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -18,7 +18,7 @@ public static partial class AvailableMethodsExtensions /// A two-letter ISO 639-1 language code or an empty string /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static BotShortDescription GetMyShortDescription(this BotClient? bot, [Optional] string? languageCode) + public static BotShortDescription GetMyShortDescription(this ITelegramBotClient bot, [Optional] string? languageCode) { if (bot == default) { @@ -35,7 +35,7 @@ public static BotShortDescription GetMyShortDescription(this BotClient? bot, [Op json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.GetMyShortDescription, stream); + return bot.CallMethod(MethodNames.GetMyShortDescription, stream); } /// @@ -46,7 +46,7 @@ public static BotShortDescription GetMyShortDescription(this BotClient? bot, [Op /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task GetMyShortDescriptionAsync(this BotClient? bot, [Optional] string? languageCode, [Optional] CancellationToken cancellationToken) + public static async Task GetMyShortDescriptionAsync(this ITelegramBotClient bot, [Optional] string? languageCode, CancellationToken cancellationToken = default) { if (bot == default) { @@ -64,6 +64,6 @@ public static async Task GetMyShortDescriptionAsync(this Bo await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.GetMyShortDescription, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetMyShortDescription, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/library/Telegram.BotAPI/Available Methods/getUserChatBoosts.cs b/src/library/Telegram.BotAPI/Available Methods/getUserChatBoosts.cs new file mode 100644 index 00000000..564d4940 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Methods/getUserChatBoosts.cs @@ -0,0 +1,102 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System.IO; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.AvailableMethods; + +/// Available Methods +public static partial class AvailableMethodsExtensions +{ + /// + /// Use this method to get the list of boosts added to a chat by a user. Requires administrator rights in the chat. Returns a UserChatBoosts object. + /// + /// The bot client. + /// Unique identifier for the chat or username of the channel (in the format @channelusername). + /// Unique identifier of the target user. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static UserChatBoosts GetUserChatBoosts(this ITelegramBotClient client, long chatId, int userId) + { + var stream = new MemoryStream(); + using var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }); + json.WriteStartObject(); + json.WriteNumber(PropertyNames.ChatId, chatId); + json.WriteNumber(PropertyNames.UserId, userId); + json.WriteEndObject(); + json.Flush(); json.Dispose(); + stream.Seek(0, SeekOrigin.Begin); + return client.CallMethod(MethodNames.GetUserChatBoosts, stream); + } + + /// + /// Use this method to get the list of boosts added to a chat by a user. Requires administrator rights in the chat. Returns a UserChatBoosts object. + /// + /// The bot client. + /// Unique identifier for the chat or username of the channel (in the format @channelusername). + /// Unique identifier of the target user. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static UserChatBoosts GetUserChatBoosts(this ITelegramBotClient client, string chatId, int userId) + { + var stream = new MemoryStream(); + using var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }); + json.WriteStartObject(); + json.WriteString(PropertyNames.ChatId, chatId); + json.WriteNumber(PropertyNames.UserId, userId); + json.WriteEndObject(); + json.Flush(); json.Dispose(); + stream.Seek(0, SeekOrigin.Begin); + return client.CallMethod(MethodNames.GetUserChatBoosts, stream); + } + + /// + /// Use this method to get the list of boosts added to a chat by a user. Requires administrator rights in the chat. Returns a UserChatBoosts object. + /// + /// The bot client. + /// Unique identifier for the chat or username of the channel (in the format @channelusername). + /// Unique identifier of the target user. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static async Task GetUserChatBoostsAsync(this ITelegramBotClient client, long chatId, int userId, CancellationToken cancellationToken = default) + { + var stream = new MemoryStream(); + using var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }); + json.WriteStartObject(); + json.WriteNumber(PropertyNames.ChatId, chatId); + json.WriteNumber(PropertyNames.UserId, userId); + json.WriteEndObject(); + await json.FlushAsync(cancellationToken).ConfigureAwait(false); + await json.DisposeAsync().ConfigureAwait(false); + stream.Seek(0, SeekOrigin.Begin); + return await client.CallMethodAsync(MethodNames.GetUserChatBoosts, stream, cancellationToken).ConfigureAwait(false); + } + + /// + /// Use this method to get the list of boosts added to a chat by a user. Requires administrator rights in the chat. Returns a UserChatBoosts object. + /// + /// The bot client. + /// Unique identifier for the chat or username of the channel (in the format @channelusername). + /// Unique identifier of the target user. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static async Task GetUserChatBoostsAsync(this ITelegramBotClient client, string chatId, int userId, CancellationToken cancellationToken = default) + { + var stream = new MemoryStream(); + using var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }); + json.WriteStartObject(); + json.WriteString(PropertyNames.ChatId, chatId); + json.WriteNumber(PropertyNames.UserId, userId); + json.WriteEndObject(); + await json.FlushAsync(cancellationToken).ConfigureAwait(false); + await json.DisposeAsync().ConfigureAwait(false); + stream.Seek(0, SeekOrigin.Begin); + return await client.CallMethodAsync(MethodNames.GetUserChatBoosts, stream, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Telegram.BotAPI/Available Methods/getUserProfilePhotos.cs b/src/library/Telegram.BotAPI/Available Methods/getUserProfilePhotos.cs similarity index 89% rename from src/Telegram.BotAPI/Available Methods/getUserProfilePhotos.cs rename to src/library/Telegram.BotAPI/Available Methods/getUserProfilePhotos.cs index 9aac67dd..3deda20d 100644 --- a/src/Telegram.BotAPI/Available Methods/getUserProfilePhotos.cs +++ b/src/library/Telegram.BotAPI/Available Methods/getUserProfilePhotos.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -20,7 +20,7 @@ public static partial class AvailableMethodsExtensions /// Thrown when a required parameter is null. /// UserProfilePhotos Object. public static UserProfilePhotos GetUserProfilePhotos( - this BotClient? bot, + this ITelegramBotClient bot, long userId, [Optional] int? offset, [Optional] ushort? limit) @@ -47,7 +47,7 @@ public static UserProfilePhotos GetUserProfilePhotos( json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.GetUserProfilePhotos, stream); + return bot.CallMethod(MethodNames.GetUserProfilePhotos, stream); } /// Use this method to get a list of profile pictures for a user. /// BotClient @@ -59,11 +59,11 @@ public static UserProfilePhotos GetUserProfilePhotos( /// Thrown when a required parameter is null. /// UserProfilePhotos Object. public static async Task GetUserProfilePhotosAsync( - this BotClient? bot, + this ITelegramBotClient bot, long userId, [Optional] int? offset, [Optional] ushort? limit, - [Optional] CancellationToken cancellationToken) + CancellationToken cancellationToken = default) { if (bot == default) { @@ -88,6 +88,6 @@ public static async Task GetUserProfilePhotosAsync( await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.GetUserProfilePhotos, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetUserProfilePhotos, stream, cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Telegram.BotAPI/Available Methods/gtChatMenuButton.cs b/src/library/Telegram.BotAPI/Available Methods/gtChatMenuButton.cs similarity index 84% rename from src/Telegram.BotAPI/Available Methods/gtChatMenuButton.cs rename to src/library/Telegram.BotAPI/Available Methods/gtChatMenuButton.cs index 4d0fafa2..21608f5f 100644 --- a/src/Telegram.BotAPI/Available Methods/gtChatMenuButton.cs +++ b/src/library/Telegram.BotAPI/Available Methods/gtChatMenuButton.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -16,7 +16,7 @@ public static partial class AvailableMethodsExtensions /// Unique identifier for the target private chat. If not specified, default bot's menu button will be returned. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static MenuButton GetChatMenuButton(this BotClient? api, [Optional] long? chatId) + public static MenuButton GetChatMenuButton(this ITelegramBotClient api, [Optional] long? chatId) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -29,7 +29,7 @@ public static MenuButton GetChatMenuButton(this BotClient? api, [Optional] long? json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.GetChatMenuButton, stream); + return api.CallMethod(MethodNames.GetChatMenuButton, stream); } /// Use this method to get the current value of the bot's menu button in a private chat, or the default menu button. Returns MenuButton on success. @@ -38,7 +38,7 @@ public static MenuButton GetChatMenuButton(this BotClient? api, [Optional] long? /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task GetChatMenuButtonAsync(this BotClient? api, [Optional] long? chatId, [Optional] CancellationToken cancellationToken) + public static async Task GetChatMenuButtonAsync(this ITelegramBotClient api, [Optional] long? chatId, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -52,6 +52,6 @@ public static async Task GetChatMenuButtonAsync(this BotClient? api, await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.GetChatMenuButton, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.GetChatMenuButton, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/hideGeneralForumTopic.cs b/src/library/Telegram.BotAPI/Available Methods/hideGeneralForumTopic.cs similarity index 86% rename from src/Telegram.BotAPI/Available Methods/hideGeneralForumTopic.cs rename to src/library/Telegram.BotAPI/Available Methods/hideGeneralForumTopic.cs index 607f042d..edd1f1df 100644 --- a/src/Telegram.BotAPI/Available Methods/hideGeneralForumTopic.cs +++ b/src/library/Telegram.BotAPI/Available Methods/hideGeneralForumTopic.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -19,7 +19,7 @@ public static partial class AvailableMethodsExtensions /// Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername). /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool HideGeneralForumTopic(this BotClient? api, long chatId) + public static bool HideGeneralForumTopic(this ITelegramBotClient api, long chatId) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -29,7 +29,7 @@ public static bool HideGeneralForumTopic(this BotClient? api, long chatId) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.HideGeneralForumTopic, stream); + return api.CallMethod(MethodNames.HideGeneralForumTopic, stream); } /// @@ -39,7 +39,7 @@ public static bool HideGeneralForumTopic(this BotClient? api, long chatId) /// Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername). /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool HideGeneralForumTopic(this BotClient? api, string chatId) + public static bool HideGeneralForumTopic(this ITelegramBotClient api, string chatId) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -49,7 +49,7 @@ public static bool HideGeneralForumTopic(this BotClient? api, string chatId) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.HideGeneralForumTopic, stream); + return api.CallMethod(MethodNames.HideGeneralForumTopic, stream); } /// @@ -60,7 +60,7 @@ public static bool HideGeneralForumTopic(this BotClient? api, string chatId) /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task HideGeneralForumTopicAsync(this BotClient? api, long chatId, [Optional] CancellationToken cancellationToken) + public static async Task HideGeneralForumTopicAsync(this ITelegramBotClient api, long chatId, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -71,7 +71,7 @@ public static async Task HideGeneralForumTopicAsync(this BotClient? api, l await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.HideGeneralForumTopic, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.HideGeneralForumTopic, stream, cancellationToken).ConfigureAwait(false); } /// @@ -82,7 +82,7 @@ public static async Task HideGeneralForumTopicAsync(this BotClient? api, l /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task HideGeneralForumTopicAsync(this BotClient? api, string chatId, [Optional] CancellationToken cancellationToken) + public static async Task HideGeneralForumTopicAsync(this ITelegramBotClient api, string chatId, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -93,6 +93,6 @@ public static async Task HideGeneralForumTopicAsync(this BotClient? api, s await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.HideGeneralForumTopic, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.HideGeneralForumTopic, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/leaveChat.cs b/src/library/Telegram.BotAPI/Available Methods/leaveChat.cs similarity index 83% rename from src/Telegram.BotAPI/Available Methods/leaveChat.cs rename to src/library/Telegram.BotAPI/Available Methods/leaveChat.cs index b9b005ba..05b5534e 100644 --- a/src/Telegram.BotAPI/Available Methods/leaveChat.cs +++ b/src/library/Telegram.BotAPI/Available Methods/leaveChat.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -15,7 +15,7 @@ public static partial class AvailableMethodsExtensions /// Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername). /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool LeaveChat(this BotClient? bot, long chatId) + public static bool LeaveChat(this ITelegramBotClient bot, long chatId) { if (bot == default) { @@ -29,14 +29,14 @@ public static bool LeaveChat(this BotClient? bot, long chatId) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.LeaveChat, stream); + return bot.CallMethod(MethodNames.LeaveChat, stream); } /// Use this method for your bot to leave a group, supergroup or channel. Returns True on success. /// BotClient /// Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername). /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool LeaveChat(this BotClient? bot, string chatId) + public static bool LeaveChat(this ITelegramBotClient bot, string chatId) { if (bot == default) { @@ -50,7 +50,7 @@ public static bool LeaveChat(this BotClient? bot, string chatId) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.LeaveChat, stream); + return bot.CallMethod(MethodNames.LeaveChat, stream); } /// Use this method for your bot to leave a group, supergroup or channel. Returns True on success. /// BotClient @@ -58,7 +58,7 @@ public static bool LeaveChat(this BotClient? bot, string chatId) /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task LeaveChatAsync(this BotClient? bot, long chatId, [Optional] CancellationToken cancellationToken) + public static async Task LeaveChatAsync(this ITelegramBotClient bot, long chatId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -73,7 +73,7 @@ public static async Task LeaveChatAsync(this BotClient? bot, long chatId, await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.LeaveChat, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.LeaveChat, stream, cancellationToken).ConfigureAwait(false); } /// Use this method for your bot to leave a group, supergroup or channel. Returns True on success. /// BotClient @@ -81,7 +81,7 @@ public static async Task LeaveChatAsync(this BotClient? bot, long chatId, /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task LeaveChatAsync(this BotClient? bot, string chatId, [Optional] CancellationToken cancellationToken) + public static async Task LeaveChatAsync(this ITelegramBotClient bot, string chatId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -96,6 +96,6 @@ public static async Task LeaveChatAsync(this BotClient? bot, string chatId await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.LeaveChat, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.LeaveChat, stream, cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Telegram.BotAPI/Available Methods/logOut.cs b/src/library/Telegram.BotAPI/Available Methods/logOut.cs similarity index 83% rename from src/Telegram.BotAPI/Available Methods/logOut.cs rename to src/library/Telegram.BotAPI/Available Methods/logOut.cs index 12116cf0..85d9e203 100644 --- a/src/Telegram.BotAPI/Available Methods/logOut.cs +++ b/src/library/Telegram.BotAPI/Available Methods/logOut.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -13,14 +13,14 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static bool LogOut(this BotClient? bot) + public static bool LogOut(this ITelegramBotClient bot) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } - return bot.RPC(MethodNames.LogOut); + return bot.CallMethod(MethodNames.LogOut); } /// Use this method to log out from the cloud Bot API server before launching the bot locally. You must log out the bot before running it locally, otherwise there is no guarantee that the bot will receive updates. After a successful call, you will not be able to log in again using the same token for 10 minutes. Returns True on success. Requires no parameters. /// Bot Client @@ -28,13 +28,13 @@ public static bool LogOut(this BotClient? bot) /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static async Task LogOutAsync(this BotClient? bot, [Optional] CancellationToken cancellationToken) + public static async Task LogOutAsync(this ITelegramBotClient bot, CancellationToken cancellationToken = default) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } - return await bot.RPCA(MethodNames.LogOut, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.LogOut, cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Telegram.BotAPI/Available Methods/pinChatMessage.cs b/src/library/Telegram.BotAPI/Available Methods/pinChatMessage.cs similarity index 86% rename from src/Telegram.BotAPI/Available Methods/pinChatMessage.cs rename to src/library/Telegram.BotAPI/Available Methods/pinChatMessage.cs index 0778aea7..69af9bf1 100644 --- a/src/Telegram.BotAPI/Available Methods/pinChatMessage.cs +++ b/src/library/Telegram.BotAPI/Available Methods/pinChatMessage.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -17,7 +17,7 @@ public static partial class AvailableMethodsExtensions /// Optional. Pass True, if it is not necessary to send a notification to all chat members about the new pinned message. Notifications are always disabled in channels. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool PinChatMessage(this BotClient? bot, long chatId, int messageId, [Optional] bool? disableNotification) + public static bool PinChatMessage(this ITelegramBotClient bot, long chatId, int messageId, [Optional] bool? disableNotification) { if (bot == default) { @@ -37,7 +37,7 @@ public static bool PinChatMessage(this BotClient? bot, long chatId, int messageI json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.PinChatMessage, stream); + return bot.CallMethod(MethodNames.PinChatMessage, stream); } /// Use this method to pin a message in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin right in the channel. Returns True on success. /// BotClient @@ -46,7 +46,7 @@ public static bool PinChatMessage(this BotClient? bot, long chatId, int messageI /// Optional. Pass True, if it is not necessary to send a notification to all chat members about the new pinned message. Notifications are always disabled in channels. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool PinChatMessage(this BotClient? bot, string chatId, int messageId, [Optional] bool? disableNotification) + public static bool PinChatMessage(this ITelegramBotClient bot, string chatId, int messageId, [Optional] bool? disableNotification) { if (bot == default) { @@ -66,7 +66,7 @@ public static bool PinChatMessage(this BotClient? bot, string chatId, int messag json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.PinChatMessage, stream); + return bot.CallMethod(MethodNames.PinChatMessage, stream); } /// Use this method to pin a message in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin right in the channel. Returns True on success. /// BotClient @@ -76,7 +76,7 @@ public static bool PinChatMessage(this BotClient? bot, string chatId, int messag /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task PinChatMessageAsync(this BotClient? bot, long chatId, int messageId, [Optional] bool? disableNotification, [Optional] CancellationToken cancellationToken) + public static async Task PinChatMessageAsync(this ITelegramBotClient bot, long chatId, int messageId, [Optional] bool? disableNotification, CancellationToken cancellationToken = default) { if (bot == default) { @@ -97,7 +97,7 @@ public static async Task PinChatMessageAsync(this BotClient? bot, long cha await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.PinChatMessage, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.PinChatMessage, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to pin a message in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin right in the channel. Returns True on success. /// BotClient @@ -107,7 +107,7 @@ public static async Task PinChatMessageAsync(this BotClient? bot, long cha /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task PinChatMessageAsync(this BotClient? bot, string chatId, int messageId, [Optional] bool? disableNotification, [Optional] CancellationToken cancellationToken) + public static async Task PinChatMessageAsync(this ITelegramBotClient bot, string chatId, int messageId, [Optional] bool? disableNotification, CancellationToken cancellationToken = default) { if (bot == default) { @@ -128,6 +128,6 @@ public static async Task PinChatMessageAsync(this BotClient? bot, string c await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.PinChatMessage, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.PinChatMessage, stream, cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Telegram.BotAPI/Available Methods/promoteChatMember.cs b/src/library/Telegram.BotAPI/Available Methods/promoteChatMember.cs similarity index 87% rename from src/Telegram.BotAPI/Available Methods/promoteChatMember.cs rename to src/library/Telegram.BotAPI/Available Methods/promoteChatMember.cs index bf0fff16..e6f4d452 100644 --- a/src/Telegram.BotAPI/Available Methods/promoteChatMember.cs +++ b/src/library/Telegram.BotAPI/Available Methods/promoteChatMember.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -15,14 +15,14 @@ public static partial class AvailableMethodsExtensions /// Parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool PromoteChatMember(this BotClient? bot, PromoteChatMemberArgs args) + public static bool PromoteChatMember(this ITelegramBotClient bot, PromoteChatMemberArgs args) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } - return bot.RPC(MethodNames.PromoteChatMember, args); + return bot.CallMethod(MethodNames.PromoteChatMember, args); } /// Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Pass False for all boolean parameters to demote a user. Returns True on success. @@ -31,7 +31,7 @@ public static bool PromoteChatMember(this BotClient? bot, PromoteChatMemberArgs /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task PromoteChatMemberAsync(this BotClient? bot, PromoteChatMemberArgs args, [Optional] CancellationToken cancellationToken) + public static async Task PromoteChatMemberAsync(this ITelegramBotClient bot, PromoteChatMemberArgs args, CancellationToken cancellationToken = default) { if (bot == default) { @@ -43,9 +43,9 @@ public static async Task PromoteChatMemberAsync(this BotClient? bot, Promo throw new ArgumentNullException(nameof(args)); } - return await bot.RPCA(MethodNames.PromoteChatMember, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.PromoteChatMember, args, cancellationToken: cancellationToken).ConfigureAwait(false); } - + /// /// Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Pass False for all boolean parameters to demote a user. Returns True on success. /// @@ -69,7 +69,7 @@ public static async Task PromoteChatMemberAsync(this BotClient? bot, Promo /// Pass True if the user is allowed to create, rename, close, and reopen forum topics, supergroups only. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool PromoteChatMember(this BotClient api, long chatId, long userId, [Optional] bool? isAnonymous, [Optional] bool? canManageChat, [Optional] bool? canPostMessages, [Optional] bool? canEditMessages, [Optional] bool? canDeleteMessages, [Optional] bool? canPostStories, [Optional] bool? canEditStories, [Optional] bool? canDeleteStories, [Optional] bool? canManageVideoChats, [Optional] bool? canRestrictMembers, [Optional] bool? canPromoteMembers, [Optional] bool? canChangeInfo, [Optional] bool? canInviteUsers, [Optional] bool? canPinMessages, [Optional] bool? canManageTopics) + public static bool PromoteChatMember(this ITelegramBotClient api, long chatId, long userId, bool? isAnonymous = null, bool? canManageChat = null, bool? canPostMessages = null, bool? canEditMessages = null, bool? canDeleteMessages = null, bool? canPostStories = null, bool? canEditStories = null, bool? canDeleteStories = null, bool? canManageVideoChats = null, bool? canRestrictMembers = null, bool? canPromoteMembers = null, bool? canChangeInfo = null, bool? canInviteUsers = null, bool? canPinMessages = null, bool? canManageTopics = null) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -140,7 +140,7 @@ public static bool PromoteChatMember(this BotClient api, long chatId, long userI json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.PromoteChatMember, stream); + return api.CallMethod(MethodNames.PromoteChatMember, stream); } /// @@ -166,7 +166,7 @@ public static bool PromoteChatMember(this BotClient api, long chatId, long userI /// Pass True if the user is allowed to create, rename, close, and reopen forum topics, supergroups only. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool PromoteChatMember(this BotClient api, string chatId, long userId, [Optional] bool? isAnonymous, [Optional] bool? canManageChat, [Optional] bool? canPostMessages, [Optional] bool? canEditMessages, [Optional] bool? canDeleteMessages, [Optional] bool? canPostStories, [Optional] bool? canEditStories, [Optional] bool? canDeleteStories, [Optional] bool? canManageVideoChats, [Optional] bool? canRestrictMembers, [Optional] bool? canPromoteMembers, [Optional] bool? canChangeInfo, [Optional] bool? canInviteUsers, [Optional] bool? canPinMessages, [Optional] bool? canManageTopics) + public static bool PromoteChatMember(this ITelegramBotClient api, string chatId, long userId, bool? isAnonymous = null, bool? canManageChat = null, bool? canPostMessages = null, bool? canEditMessages = null, bool? canDeleteMessages = null, bool? canPostStories = null, bool? canEditStories = null, bool? canDeleteStories = null, bool? canManageVideoChats = null, bool? canRestrictMembers = null, bool? canPromoteMembers = null, bool? canChangeInfo = null, bool? canInviteUsers = null, bool? canPinMessages = null, bool? canManageTopics = null) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -237,7 +237,7 @@ public static bool PromoteChatMember(this BotClient api, string chatId, long use json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.PromoteChatMember, stream); + return api.CallMethod(MethodNames.PromoteChatMember, stream); } /// @@ -264,7 +264,7 @@ public static bool PromoteChatMember(this BotClient api, string chatId, long use /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task PromoteChatMemberAsync(this BotClient api, long chatId, long userId, [Optional] bool? isAnonymous, [Optional] bool? canManageChat, [Optional] bool? canPostMessages, [Optional] bool? canEditMessages, [Optional] bool? canDeleteMessages, [Optional] bool? canPostStories, [Optional] bool? canEditStories, [Optional] bool? canDeleteStories, [Optional] bool? canManageVideoChats, [Optional] bool? canRestrictMembers, [Optional] bool? canPromoteMembers, [Optional] bool? canChangeInfo, [Optional] bool? canInviteUsers, [Optional] bool? canPinMessages, [Optional] bool? canManageTopics, [Optional] CancellationToken cancellationToken) + public static async Task PromoteChatMemberAsync(this ITelegramBotClient api, long chatId, long userId, bool? isAnonymous = null, bool? canManageChat = null, bool? canPostMessages = null, bool? canEditMessages = null, bool? canDeleteMessages = null, bool? canPostStories = null, bool? canEditStories = null, bool? canDeleteStories = null, bool? canManageVideoChats = null, bool? canRestrictMembers = null, bool? canPromoteMembers = null, bool? canChangeInfo = null, bool? canInviteUsers = null, bool? canPinMessages = null, bool? canManageTopics = null, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -336,7 +336,7 @@ public static async Task PromoteChatMemberAsync(this BotClient api, long c await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.PromoteChatMember, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.PromoteChatMember, stream, cancellationToken).ConfigureAwait(false); } /// @@ -363,7 +363,7 @@ public static async Task PromoteChatMemberAsync(this BotClient api, long c /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task PromoteChatMemberAsync(this BotClient api, string chatId, long userId, [Optional] bool? isAnonymous, [Optional] bool? canManageChat, [Optional] bool? canPostMessages, [Optional] bool? canEditMessages, [Optional] bool? canDeleteMessages, [Optional] bool? canPostStories, [Optional] bool? canEditStories, [Optional] bool? canDeleteStories, [Optional] bool? canManageVideoChats, [Optional] bool? canRestrictMembers, [Optional] bool? canPromoteMembers, [Optional] bool? canChangeInfo, [Optional] bool? canInviteUsers, [Optional] bool? canPinMessages, [Optional] bool? canManageTopics, [Optional] CancellationToken cancellationToken) + public static async Task PromoteChatMemberAsync(this ITelegramBotClient api, string chatId, long userId, bool? isAnonymous = null, bool? canManageChat = null, bool? canPostMessages = null, bool? canEditMessages = null, bool? canDeleteMessages = null, bool? canPostStories = null, bool? canEditStories = null, bool? canDeleteStories = null, bool? canManageVideoChats = null, bool? canRestrictMembers = null, bool? canPromoteMembers = null, bool? canChangeInfo = null, bool? canInviteUsers = null, bool? canPinMessages = null, bool? canManageTopics = null, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -435,6 +435,6 @@ public static async Task PromoteChatMemberAsync(this BotClient api, string await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.PromoteChatMember, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.PromoteChatMember, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/reopenForumTopic.cs b/src/library/Telegram.BotAPI/Available Methods/reopenForumTopic.cs similarity index 85% rename from src/Telegram.BotAPI/Available Methods/reopenForumTopic.cs rename to src/library/Telegram.BotAPI/Available Methods/reopenForumTopic.cs index eaa619a7..1fbe218b 100644 --- a/src/Telegram.BotAPI/Available Methods/reopenForumTopic.cs +++ b/src/library/Telegram.BotAPI/Available Methods/reopenForumTopic.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -18,7 +18,7 @@ public static partial class AvailableMethodsExtensions /// Unique identifier for the target message thread of the forum topic. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool ReopenForumTopic(this BotClient? api, long chatId, int messageThreadId) + public static bool ReopenForumTopic(this ITelegramBotClient api, long chatId, int messageThreadId) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -29,7 +29,7 @@ public static bool ReopenForumTopic(this BotClient? api, long chatId, int messag json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.ReopenForumTopic, stream); + return api.CallMethod(MethodNames.ReopenForumTopic, stream); } /// @@ -40,7 +40,7 @@ public static bool ReopenForumTopic(this BotClient? api, long chatId, int messag /// Unique identifier for the target message thread of the forum topic. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool ReopenForumTopic(this BotClient? api, string chatId, int messageThreadId) + public static bool ReopenForumTopic(this ITelegramBotClient api, string chatId, int messageThreadId) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -51,7 +51,7 @@ public static bool ReopenForumTopic(this BotClient? api, string chatId, int mess json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.ReopenForumTopic, stream); + return api.CallMethod(MethodNames.ReopenForumTopic, stream); } /// @@ -63,7 +63,7 @@ public static bool ReopenForumTopic(this BotClient? api, string chatId, int mess /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task ReopenForumTopicAsync(this BotClient? api, long chatId, int messageThreadId, [Optional] CancellationToken cancellationToken) + public static async Task ReopenForumTopicAsync(this ITelegramBotClient api, long chatId, int messageThreadId, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -75,7 +75,7 @@ public static async Task ReopenForumTopicAsync(this BotClient? api, long c await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.ReopenForumTopic, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.ReopenForumTopic, stream, cancellationToken).ConfigureAwait(false); } /// @@ -87,7 +87,7 @@ public static async Task ReopenForumTopicAsync(this BotClient? api, long c /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task ReopenForumTopicAsync(this BotClient? api, string chatId, int messageThreadId, [Optional] CancellationToken cancellationToken) + public static async Task ReopenForumTopicAsync(this ITelegramBotClient api, string chatId, int messageThreadId, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -99,6 +99,6 @@ public static async Task ReopenForumTopicAsync(this BotClient? api, string await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.ReopenForumTopic, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.ReopenForumTopic, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/reopenGeneralForumTopic.cs b/src/library/Telegram.BotAPI/Available Methods/reopenGeneralForumTopic.cs similarity index 86% rename from src/Telegram.BotAPI/Available Methods/reopenGeneralForumTopic.cs rename to src/library/Telegram.BotAPI/Available Methods/reopenGeneralForumTopic.cs index 3dd924bb..a2977e81 100644 --- a/src/Telegram.BotAPI/Available Methods/reopenGeneralForumTopic.cs +++ b/src/library/Telegram.BotAPI/Available Methods/reopenGeneralForumTopic.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -19,7 +19,7 @@ public static partial class AvailableMethodsExtensions /// Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername). /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool ReopenGeneralForumTopic(this BotClient? api, long chatId) + public static bool ReopenGeneralForumTopic(this ITelegramBotClient api, long chatId) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -29,7 +29,7 @@ public static bool ReopenGeneralForumTopic(this BotClient? api, long chatId) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.ReopenGeneralForumTopic, stream); + return api.CallMethod(MethodNames.ReopenGeneralForumTopic, stream); } /// @@ -39,7 +39,7 @@ public static bool ReopenGeneralForumTopic(this BotClient? api, long chatId) /// Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername). /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool ReopenGeneralForumTopic(this BotClient? api, string chatId) + public static bool ReopenGeneralForumTopic(this ITelegramBotClient api, string chatId) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -49,7 +49,7 @@ public static bool ReopenGeneralForumTopic(this BotClient? api, string chatId) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.ReopenGeneralForumTopic, stream); + return api.CallMethod(MethodNames.ReopenGeneralForumTopic, stream); } /// @@ -60,7 +60,7 @@ public static bool ReopenGeneralForumTopic(this BotClient? api, string chatId) /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task ReopenGeneralForumTopicAsync(this BotClient? api, long chatId, [Optional] CancellationToken cancellationToken) + public static async Task ReopenGeneralForumTopicAsync(this ITelegramBotClient api, long chatId, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -71,7 +71,7 @@ public static async Task ReopenGeneralForumTopicAsync(this BotClient? api, await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.ReopenGeneralForumTopic, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.ReopenGeneralForumTopic, stream, cancellationToken).ConfigureAwait(false); } /// @@ -82,7 +82,7 @@ public static async Task ReopenGeneralForumTopicAsync(this BotClient? api, /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task ReopenGeneralForumTopicAsync(this BotClient? api, string chatId, [Optional] CancellationToken cancellationToken) + public static async Task ReopenGeneralForumTopicAsync(this ITelegramBotClient api, string chatId, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -93,6 +93,6 @@ public static async Task ReopenGeneralForumTopicAsync(this BotClient? api, await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.ReopenGeneralForumTopic, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.ReopenGeneralForumTopic, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/restrictChatMember.cs b/src/library/Telegram.BotAPI/Available Methods/restrictChatMember.cs similarity index 84% rename from src/Telegram.BotAPI/Available Methods/restrictChatMember.cs rename to src/library/Telegram.BotAPI/Available Methods/restrictChatMember.cs index 6137788a..d0619881 100644 --- a/src/Telegram.BotAPI/Available Methods/restrictChatMember.cs +++ b/src/library/Telegram.BotAPI/Available Methods/restrictChatMember.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -14,7 +14,7 @@ public static partial class AvailableMethodsExtensions /// Parameters /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool RestrictChatMember(this BotClient? bot, RestrictChatMemberArgs args) + public static bool RestrictChatMember(this ITelegramBotClient bot, RestrictChatMemberArgs args) { if (bot == default) { @@ -26,7 +26,7 @@ public static bool RestrictChatMember(this BotClient? bot, RestrictChatMemberArg throw new ArgumentNullException(nameof(args)); } - return bot.RPC(MethodNames.RestrictChatMember, args); + return bot.CallMethod(MethodNames.RestrictChatMember, args); } /// Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate administrator rights. Pass True for all permissions to lift restrictions from a user. Returns True on success. @@ -37,7 +37,7 @@ public static bool RestrictChatMember(this BotClient? bot, RestrictChatMemberArg /// Date when restrictions will be lifted for the user, unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool RestrictChatMember(this BotClient? bot, long chatId, long userId, ChatPermissions permissions, [Optional] uint? untilDate) + public static bool RestrictChatMember(this ITelegramBotClient bot, long chatId, long userId, ChatPermissions permissions, [Optional] uint? untilDate) { if (bot == null) { @@ -48,7 +48,7 @@ public static bool RestrictChatMember(this BotClient? bot, long chatId, long use UntilDate = untilDate }; - return bot.RPC(MethodNames.RestrictChatMember, args); + return bot.CallMethod(MethodNames.RestrictChatMember, args); } /// @@ -62,7 +62,7 @@ public static bool RestrictChatMember(this BotClient? bot, long chatId, long use /// Date when restrictions will be lifted for the user, unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool RestrictChatMember(this BotClient api, long chatId, long userId, ChatPermissions permissions, [Optional] bool? useIndependentChatPermissions, [Optional] uint? untilDate) + public static bool RestrictChatMember(this ITelegramBotClient api, long chatId, long userId, ChatPermissions permissions, [Optional] bool? useIndependentChatPermissions, [Optional] uint? untilDate) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new RestrictChatMemberArgs(chatId, userId, permissions) @@ -70,7 +70,7 @@ public static bool RestrictChatMember(this BotClient api, long chatId, long user UseIndependentChatPermissions = useIndependentChatPermissions, UntilDate = untilDate }; - return api.RPC(MethodNames.RestrictChatMember, args); + return api.CallMethod(MethodNames.RestrictChatMember, args); } /// @@ -84,7 +84,7 @@ public static bool RestrictChatMember(this BotClient api, long chatId, long user /// Date when restrictions will be lifted for the user, unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool RestrictChatMember(this BotClient api, string chatId, long userId, ChatPermissions permissions, [Optional] bool? useIndependentChatPermissions, [Optional] uint? untilDate) + public static bool RestrictChatMember(this ITelegramBotClient api, string chatId, long userId, ChatPermissions permissions, [Optional] bool? useIndependentChatPermissions, [Optional] uint? untilDate) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new RestrictChatMemberArgs(chatId, userId, permissions) @@ -92,7 +92,7 @@ public static bool RestrictChatMember(this BotClient api, string chatId, long us UseIndependentChatPermissions = useIndependentChatPermissions, UntilDate = untilDate }; - return api.RPC(MethodNames.RestrictChatMember, args); + return api.CallMethod(MethodNames.RestrictChatMember, args); } /// @@ -107,7 +107,7 @@ public static bool RestrictChatMember(this BotClient api, string chatId, long us /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task RestrictChatMemberAsync(this BotClient api, long chatId, long userId, ChatPermissions permissions, [Optional] bool? useIndependentChatPermissions, [Optional] uint? untilDate, [Optional] CancellationToken cancellationToken) + public static async Task RestrictChatMemberAsync(this ITelegramBotClient api, long chatId, long userId, ChatPermissions permissions, [Optional] bool? useIndependentChatPermissions, [Optional] uint? untilDate, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new RestrictChatMemberArgs(chatId, userId, permissions) @@ -115,7 +115,7 @@ public static async Task RestrictChatMemberAsync(this BotClient api, long UseIndependentChatPermissions = useIndependentChatPermissions, UntilDate = untilDate }; - return await api.RPCA(MethodNames.RestrictChatMember, args, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.RestrictChatMember, args, cancellationToken).ConfigureAwait(false); } /// @@ -130,7 +130,7 @@ public static async Task RestrictChatMemberAsync(this BotClient api, long /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task RestrictChatMemberAsync(this BotClient api, string chatId, long userId, ChatPermissions permissions, [Optional] bool? useIndependentChatPermissions, [Optional] uint? untilDate, [Optional] CancellationToken cancellationToken) + public static async Task RestrictChatMemberAsync(this ITelegramBotClient api, string chatId, long userId, ChatPermissions permissions, [Optional] bool? useIndependentChatPermissions, [Optional] uint? untilDate, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new RestrictChatMemberArgs(chatId, userId, permissions) @@ -138,6 +138,6 @@ public static async Task RestrictChatMemberAsync(this BotClient api, strin UseIndependentChatPermissions = useIndependentChatPermissions, UntilDate = untilDate }; - return await api.RPCA(MethodNames.RestrictChatMember, args, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.RestrictChatMember, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/revokeChatInviteLink.cs b/src/library/Telegram.BotAPI/Available Methods/revokeChatInviteLink.cs similarity index 87% rename from src/Telegram.BotAPI/Available Methods/revokeChatInviteLink.cs rename to src/library/Telegram.BotAPI/Available Methods/revokeChatInviteLink.cs index 8437295b..3902c735 100644 --- a/src/Telegram.BotAPI/Available Methods/revokeChatInviteLink.cs +++ b/src/library/Telegram.BotAPI/Available Methods/revokeChatInviteLink.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -18,7 +18,7 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static ChatInviteLink RevokeChatInviteLink(this BotClient? bot, long chatId, string inviteLink) + public static ChatInviteLink RevokeChatInviteLink(this ITelegramBotClient bot, long chatId, string inviteLink) { if (bot == default) { @@ -36,7 +36,7 @@ public static ChatInviteLink RevokeChatInviteLink(this BotClient? bot, long chat json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.RevokeChatInviteLink, stream); + return bot.CallMethod(MethodNames.RevokeChatInviteLink, stream); } /// Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns the revoked invite link object. /// BotClient @@ -45,7 +45,7 @@ public static ChatInviteLink RevokeChatInviteLink(this BotClient? bot, long chat /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static ChatInviteLink RevokeChatInviteLink(this BotClient? bot, string chatId, string inviteLink) + public static ChatInviteLink RevokeChatInviteLink(this ITelegramBotClient bot, string chatId, string inviteLink) { if (bot == default) { @@ -63,7 +63,7 @@ public static ChatInviteLink RevokeChatInviteLink(this BotClient? bot, string ch json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.RevokeChatInviteLink, stream); + return bot.CallMethod(MethodNames.RevokeChatInviteLink, stream); } /// Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns the revoked invite link object. /// BotClient @@ -73,7 +73,7 @@ public static ChatInviteLink RevokeChatInviteLink(this BotClient? bot, string ch /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static async Task RevokeChatInviteLink(this BotClient? bot, long chatId, string inviteLink, [Optional] CancellationToken cancellationToken) + public static async Task RevokeChatInviteLink(this ITelegramBotClient bot, long chatId, string inviteLink, CancellationToken cancellationToken = default) { if (bot == default) { @@ -92,7 +92,7 @@ public static async Task RevokeChatInviteLink(this BotClient? bo await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.RevokeChatInviteLink, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.RevokeChatInviteLink, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns the revoked invite link object. /// BotClient @@ -102,7 +102,7 @@ public static async Task RevokeChatInviteLink(this BotClient? bo /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// - public static async Task RevokeChatInviteLink(this BotClient? bot, string chatId, string inviteLink, [Optional] CancellationToken cancellationToken) + public static async Task RevokeChatInviteLink(this ITelegramBotClient bot, string chatId, string inviteLink, CancellationToken cancellationToken = default) { if (bot == default) { @@ -121,6 +121,6 @@ public static async Task RevokeChatInviteLink(this BotClient? bo await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.RevokeChatInviteLink, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.RevokeChatInviteLink, stream, cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Telegram.BotAPI/Available Methods/sendAnimation.cs b/src/library/Telegram.BotAPI/Available Methods/sendAnimation.cs similarity index 73% rename from src/Telegram.BotAPI/Available Methods/sendAnimation.cs rename to src/library/Telegram.BotAPI/Available Methods/sendAnimation.cs index 45b74ebb..7570a361 100644 --- a/src/Telegram.BotAPI/Available Methods/sendAnimation.cs +++ b/src/library/Telegram.BotAPI/Available Methods/sendAnimation.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -10,38 +10,40 @@ namespace Telegram.BotAPI.AvailableMethods; public static partial class AvailableMethodsExtensions { /// Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. - /// BotClient + /// The bot client /// Parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message Object. - public static Message SendAnimation(this BotClient? bot, SendAnimationArgs args) + public static Message SendAnimation(this ITelegramBotClient client, SendAnimationArgs args) { - if (bot == null) { throw new ArgumentNullException(nameof(bot)); } - if (args == null) { throw new ArgumentNullException(nameof(args)); } - - return bot.RPCF(MethodNames.SendAnimation, args); + if (client is null) + throw new ArgumentNullException(nameof(client)); + if (args is null) + throw new ArgumentNullException(nameof(args)); + return client.CallMethod(MethodNames.SendAnimation, args); } /// Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. - /// BotClient + /// The bot client /// Parameters. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message Object. - public static async Task SendAnimationAsync(this BotClient? bot, SendAnimationArgs args, [Optional] CancellationToken cancellationToken) + public static Task SendAnimationAsync(this ITelegramBotClient client, SendAnimationArgs args, CancellationToken cancellationToken = default) { - if (bot == null) { throw new ArgumentNullException(nameof(bot)); } - if (args == null) { throw new ArgumentNullException(nameof(args)); } - - return await bot.RPCAF(MethodNames.SendAnimation, args, cancellationToken).ConfigureAwait(false); + if (client is null) + throw new ArgumentNullException(nameof(client)); + if (args is null) + throw new ArgumentNullException(nameof(args)); + return client.CallMethodAsync(MethodNames.SendAnimation, args, cancellationToken); } /// /// Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. @@ -55,14 +57,14 @@ public static async Task SendAnimationAsync(this BotClient? bot, SendAn /// Pass True if the animation needs to be covered with a spoiler animation. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendAnimation(this BotClient? api, long chatId, InputFile animation, [Optional] int? messageThreadId, [Optional] uint? duration, [Optional] uint? width, [Optional] uint? height, [Optional] InputFile? thumbnail, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable captionEntities, [Optional] bool? hasSpoiler, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendAnimation(this ITelegramBotClient client, long chatId, InputFile animation, int? messageThreadId = null, uint? duration = null, uint? width = null, uint? height = null, InputFile? thumbnail = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? hasSpoiler = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendAnimationArgs(chatId, animation) { MessageThreadId = messageThreadId, @@ -76,17 +78,16 @@ public static Message SendAnimation(this BotClient? api, long chatId, InputFile HasSpoiler = hasSpoiler, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPCF(MethodNames.SendAnimation, args); + return client.CallMethod(MethodNames.SendAnimation, args); } /// /// Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. @@ -100,15 +101,15 @@ public static Message SendAnimation(this BotClient? api, long chatId, InputFile /// Pass True if the animation needs to be covered with a spoiler animation. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Attached files. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendAnimation(this BotClient? api, long chatId, string animation, [Optional] int? messageThreadId, [Optional] uint? duration, [Optional] uint? width, [Optional] uint? height, [Optional] string? thumbnail, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable captionEntities, [Optional] bool? hasSpoiler, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] IEnumerable attachedFiles) + public static Message SendAnimation(this ITelegramBotClient client, long chatId, string animation, int? messageThreadId = null, uint? duration = null, uint? width = null, uint? height = null, string? thumbnail = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? hasSpoiler = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, IEnumerable? attachedFiles = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendAnimationArgs(chatId, animation) { MessageThreadId = messageThreadId, @@ -122,19 +123,17 @@ public static Message SendAnimation(this BotClient? api, long chatId, string ani HasSpoiler = hasSpoiler, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup, - AttachedFiles = attachedFiles ?? Array.Empty() + AttachedFiles = attachedFiles ?? [] }; - - return api.RPCF(MethodNames.SendAnimation, args); + return client.CallMethod(MethodNames.SendAnimation, args); } /// /// Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. @@ -148,14 +147,14 @@ public static Message SendAnimation(this BotClient? api, long chatId, string ani /// Pass True if the animation needs to be covered with a spoiler animation. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendAnimation(this BotClient? api, string chatId, InputFile animation, [Optional] int? messageThreadId, [Optional] uint? duration, [Optional] uint? width, [Optional] uint? height, [Optional] InputFile? thumbnail, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? hasSpoiler, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendAnimation(this ITelegramBotClient client, string chatId, InputFile animation, int? messageThreadId = null, uint? duration = null, uint? width = null, uint? height = null, InputFile? thumbnail = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? hasSpoiler = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendAnimationArgs(chatId, animation) { MessageThreadId = messageThreadId, @@ -169,17 +168,16 @@ public static Message SendAnimation(this BotClient? api, string chatId, InputFil HasSpoiler = hasSpoiler, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPCF(MethodNames.SendAnimation, args); + return client.CallMethod(MethodNames.SendAnimation, args); } /// /// Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. @@ -193,15 +191,15 @@ public static Message SendAnimation(this BotClient? api, string chatId, InputFil /// Pass True if the animation needs to be covered with a spoiler animation. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Attached files. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendAnimation(this BotClient? api, string chatId, string animation, [Optional] int? messageThreadId, [Optional] uint? duration, [Optional] uint? width, [Optional] uint? height, [Optional] string? thumbnail, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? hasSpoiler, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] IEnumerable? attachedFiles) + public static Message SendAnimation(this ITelegramBotClient client, string chatId, string animation, int? messageThreadId = null, uint? duration = null, uint? width = null, uint? height = null, string? thumbnail = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? hasSpoiler = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, IEnumerable? attachedFiles = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendAnimationArgs(chatId, animation) { MessageThreadId = messageThreadId, @@ -215,18 +213,17 @@ public static Message SendAnimation(this BotClient? api, string chatId, string a HasSpoiler = hasSpoiler, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup, - AttachedFiles = attachedFiles ?? Array.Empty(), + AttachedFiles = attachedFiles ?? [] }; - return api.RPCF(MethodNames.SendAnimation, args); + return client.CallMethod(MethodNames.SendAnimation, args); } /// /// Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. @@ -240,15 +237,15 @@ public static Message SendAnimation(this BotClient? api, string chatId, string a /// Pass True if the animation needs to be covered with a spoiler animation. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendAnimationAsync(this BotClient? api, long chatId, InputFile animation, [Optional] int? messageThreadId, [Optional] uint? duration, [Optional] uint? width, [Optional] uint? height, [Optional] InputFile? thumbnail, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? hasSpoiler, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendAnimationAsync(this ITelegramBotClient client, long chatId, InputFile animation, int? messageThreadId = null, uint? duration = null, uint? width = null, uint? height = null, InputFile? thumbnail = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? hasSpoiler = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendAnimationArgs(chatId, animation) { MessageThreadId = messageThreadId, @@ -262,17 +259,16 @@ public static async Task SendAnimationAsync(this BotClient? api, long c HasSpoiler = hasSpoiler, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCAF(MethodNames.SendAnimation, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendAnimation, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. @@ -286,16 +282,16 @@ public static async Task SendAnimationAsync(this BotClient? api, long c /// Pass True if the animation needs to be covered with a spoiler animation. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Attached files. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendAnimationAsync(this BotClient? api, long chatId, string animation, [Optional] int? messageThreadId, [Optional] uint? duration, [Optional] uint? width, [Optional] uint? height, [Optional] string? thumbnail, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? hasSpoiler, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] IEnumerable? attachedFiles, [Optional] CancellationToken cancellationToken) + public static async Task SendAnimationAsync(this ITelegramBotClient client, long chatId, string animation, int? messageThreadId = null, uint? duration = null, uint? width = null, uint? height = null, string? thumbnail = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? hasSpoiler = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, IEnumerable? attachedFiles = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendAnimationArgs(chatId, animation) { MessageThreadId = messageThreadId, @@ -309,18 +305,17 @@ public static async Task SendAnimationAsync(this BotClient? api, long c HasSpoiler = hasSpoiler, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup, - AttachedFiles = attachedFiles ?? Array.Empty() + AttachedFiles = attachedFiles ?? [] }; - return await api.RPCAF(MethodNames.SendAnimation, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendAnimation, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. @@ -334,15 +329,15 @@ public static async Task SendAnimationAsync(this BotClient? api, long c /// Pass True if the animation needs to be covered with a spoiler animation. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendAnimationAsync(this BotClient? api, string chatId, InputFile animation, [Optional] int? messageThreadId, [Optional] uint? duration, [Optional] uint? width, [Optional] uint? height, [Optional] InputFile? thumbnail, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? hasSpoiler, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendAnimationAsync(this ITelegramBotClient client, string chatId, InputFile animation, int? messageThreadId = null, uint? duration = null, uint? width = null, uint? height = null, InputFile? thumbnail = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? hasSpoiler = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendAnimationArgs(chatId, animation) { MessageThreadId = messageThreadId, @@ -356,17 +351,16 @@ public static async Task SendAnimationAsync(this BotClient? api, string HasSpoiler = hasSpoiler, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCAF(MethodNames.SendAnimation, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendAnimation, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. @@ -380,16 +374,16 @@ public static async Task SendAnimationAsync(this BotClient? api, string /// Pass True if the animation needs to be covered with a spoiler animation. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Attached files. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendAnimationAsync(this BotClient? api, string chatId, string animation, [Optional] int? messageThreadId, [Optional] uint? duration, [Optional] uint? width, [Optional] uint? height, [Optional] string? thumbnail, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? hasSpoiler, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] IEnumerable? attachedFiles, [Optional] CancellationToken cancellationToken) + public static async Task SendAnimationAsync(this ITelegramBotClient client, string chatId, string animation, int? messageThreadId = null, uint? duration = null, uint? width = null, uint? height = null, string? thumbnail = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? hasSpoiler = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, IEnumerable? attachedFiles = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendAnimationArgs(chatId, animation) { MessageThreadId = messageThreadId, @@ -403,11 +397,10 @@ public static async Task SendAnimationAsync(this BotClient? api, string HasSpoiler = hasSpoiler, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup, - AttachedFiles = attachedFiles ?? Array.Empty() + AttachedFiles = attachedFiles ?? [] }; - return await api.RPCAF(MethodNames.SendAnimation, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendAnimation, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/sendAudio.cs b/src/library/Telegram.BotAPI/Available Methods/sendAudio.cs similarity index 66% rename from src/Telegram.BotAPI/Available Methods/sendAudio.cs rename to src/library/Telegram.BotAPI/Available Methods/sendAudio.cs index 4b35f915..6461d637 100644 --- a/src/Telegram.BotAPI/Available Methods/sendAudio.cs +++ b/src/library/Telegram.BotAPI/Available Methods/sendAudio.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -11,53 +11,39 @@ namespace Telegram.BotAPI.AvailableMethods; public static partial class AvailableMethodsExtensions { /// Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .mp3 format. On success, the sent Message is returned. - /// BotClient + /// The bot client. /// Parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message Object. - public static Message SendAudio(this BotClient? bot, SendAudioArgs args) + public static Message SendAudio(this ITelegramBotClient client, SendAudioArgs args) { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } + return client is null + ? throw new ArgumentNullException(nameof(client)) + : client.CallMethod(MethodNames.SendAudio, args); + } - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - return bot.RPCF(MethodNames.SendAudio, args); - } /// Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .mp3 format. On success, the sent Message is returned. - /// BotClient + /// The bot client /// Parameters. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message Object. - public static async Task SendAudioAsync(this BotClient? bot, SendAudioArgs args, [Optional] CancellationToken cancellationToken) + public static Task SendAudioAsync(this ITelegramBotClient client, SendAudioArgs args, CancellationToken cancellationToken = default) { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - - return await bot.RPCAF(MethodNames.SendAudio, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return client is null + ? throw new ArgumentNullException(nameof(client)) + : client.CallMethodAsync(MethodNames.SendAudio, args, cancellationToken); } /// /// Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Audio caption, 0-1024 characters after entities parsing. /// Mode for parsing entities in the audio caption. See formatting options for more details. @@ -65,17 +51,17 @@ public static async Task SendAudioAsync(this BotClient? bot, SendAudioA /// Duration of the audio in seconds. /// Performer. /// Track name. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass ÔÇ£attach://<file_attach_name>ÔÇØ if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ┬╗. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendAudio(this BotClient? api, long chatId, InputFile audio, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] uint? duration, [Optional] string? performer, [Optional] string? title, [Optional] InputFile? thumbnail, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendAudio(this ITelegramBotClient client, long chatId, InputFile audio, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, uint? duration = null, string? performer = null, string? title = null, InputFile? thumbnail = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client == null) + throw new ArgumentNullException(nameof(client)); var args = new SendAudioArgs(chatId, audio) { MessageThreadId = messageThreadId, @@ -88,19 +74,18 @@ public static Message SendAudio(this BotClient? api, long chatId, InputFile audi Thumbnail = thumbnail, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPCF(MethodNames.SendAudio, args); + return client.CallMethod(MethodNames.SendAudio, args); } /// /// Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Audio caption, 0-1024 characters after entities parsing. /// Mode for parsing entities in the audio caption. See formatting options for more details. @@ -108,18 +93,18 @@ public static Message SendAudio(this BotClient? api, long chatId, InputFile audi /// Duration of the audio in seconds. /// Performer. /// Track name. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass ÔÇ£attach://<file_attach_name>ÔÇØ if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ┬╗. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Attached files. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendAudio(this BotClient? api, long chatId, string audio, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] uint? duration, [Optional] string? performer, [Optional] string? title, [Optional] string? thumbnail, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] IEnumerable? attachedFiles) + public static Message SendAudio(this ITelegramBotClient client, long chatId, string audio, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, uint? duration = null, string? performer = null, string? title = null, string? thumbnail = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, IEnumerable? attachedFiles = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client == null) + throw new ArgumentNullException(nameof(client)); var args = new SendAudioArgs(chatId, audio) { MessageThreadId = messageThreadId, @@ -132,20 +117,19 @@ public static Message SendAudio(this BotClient? api, long chatId, string audio, Thumbnail = thumbnail, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup, - AttachedFiles = attachedFiles ?? Array.Empty() + AttachedFiles = attachedFiles ?? [] }; - return api.RPCF(MethodNames.SendAudio, args); + return client.CallMethod(MethodNames.SendAudio, args); } /// /// Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Audio caption, 0-1024 characters after entities parsing. /// Mode for parsing entities in the audio caption. See formatting options for more details. @@ -153,17 +137,17 @@ public static Message SendAudio(this BotClient? api, long chatId, string audio, /// Duration of the audio in seconds. /// Performer. /// Track name. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass ÔÇ£attach://<file_attach_name>ÔÇØ if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ┬╗. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendAudio(this BotClient? api, string chatId, InputFile audio, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] uint? duration, [Optional] string? performer, [Optional] string? title, [Optional] InputFile? thumbnail, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendAudio(this ITelegramBotClient client, string chatId, InputFile audio, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, uint? duration = null, string? performer = null, string? title = null, InputFile? thumbnail = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client == null) + throw new ArgumentNullException(nameof(client)); var args = new SendAudioArgs(chatId, audio) { MessageThreadId = messageThreadId, @@ -176,19 +160,18 @@ public static Message SendAudio(this BotClient? api, string chatId, InputFile au Thumbnail = thumbnail, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPCF(MethodNames.SendAudio, args); + return client.CallMethod(MethodNames.SendAudio, args); } /// /// Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Audio caption, 0-1024 characters after entities parsing. /// Mode for parsing entities in the audio caption. See formatting options for more details. @@ -196,18 +179,18 @@ public static Message SendAudio(this BotClient? api, string chatId, InputFile au /// Duration of the audio in seconds. /// Performer. /// Track name. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass ÔÇ£attach://<file_attach_name>ÔÇØ if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ┬╗. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Attached files. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendAudio(this BotClient? api, string chatId, string audio, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] uint? duration, [Optional] string? performer, [Optional] string? title, [Optional] string? thumbnail, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] IEnumerable? attachedFiles) + public static Message SendAudio(this ITelegramBotClient client, string chatId, string audio, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, uint? duration = null, string? performer = null, string? title = null, string? thumbnail = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, IEnumerable? attachedFiles = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client == null) + throw new ArgumentNullException(nameof(client)); var args = new SendAudioArgs(chatId, audio) { MessageThreadId = messageThreadId, @@ -220,20 +203,19 @@ public static Message SendAudio(this BotClient? api, string chatId, string audio Thumbnail = thumbnail, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup, - AttachedFiles = attachedFiles ?? Array.Empty() + AttachedFiles = attachedFiles ?? [] }; - return api.RPCF(MethodNames.SendAudio, args); + return client.CallMethod(MethodNames.SendAudio, args); } /// /// Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Audio caption, 0-1024 characters after entities parsing. /// Mode for parsing entities in the audio caption. See formatting options for more details. @@ -241,18 +223,18 @@ public static Message SendAudio(this BotClient? api, string chatId, string audio /// Duration of the audio in seconds. /// Performer. /// Track name. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass ÔÇ£attach://<file_attach_name>ÔÇØ if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ┬╗. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendAudioAsync(this BotClient? api, long chatId, InputFile audio, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] uint? duration, [Optional] string? performer, [Optional] string? title, [Optional] InputFile? thumbnail, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendAudioAsync(this ITelegramBotClient client, long chatId, InputFile audio, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, uint? duration = null, string? performer = null, string? title = null, InputFile? thumbnail = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client == null) + throw new ArgumentNullException(nameof(client)); var args = new SendAudioArgs(chatId, audio) { MessageThreadId = messageThreadId, @@ -265,19 +247,18 @@ public static async Task SendAudioAsync(this BotClient? api, long chatI Thumbnail = thumbnail, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCAF(MethodNames.SendAudio, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendAudio, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Audio caption, 0-1024 characters after entities parsing. /// Mode for parsing entities in the audio caption. See formatting options for more details. @@ -285,19 +266,19 @@ public static async Task SendAudioAsync(this BotClient? api, long chatI /// Duration of the audio in seconds. /// Performer. /// Track name. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass ÔÇ£attach://<file_attach_name>ÔÇØ if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ┬╗. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Attached files. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendAudioAsync(this BotClient? api, long chatId, string audio, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] uint? duration, [Optional] string? performer, [Optional] string? title, [Optional] string? thumbnail, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] IEnumerable? attachedFiles, [Optional] CancellationToken cancellationToken) + public static async Task SendAudioAsync(this ITelegramBotClient client, long chatId, string audio, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, uint? duration = null, string? performer = null, string? title = null, string? thumbnail = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, IEnumerable? attachedFiles = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client == null) + throw new ArgumentNullException(nameof(client)); var args = new SendAudioArgs(chatId, audio) { MessageThreadId = messageThreadId, @@ -310,20 +291,19 @@ public static async Task SendAudioAsync(this BotClient? api, long chatI Thumbnail = thumbnail, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup, - AttachedFiles = attachedFiles ?? Array.Empty() + AttachedFiles = attachedFiles ?? [] }; - return await api.RPCAF(MethodNames.SendAudio, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendAudio, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Audio caption, 0-1024 characters after entities parsing. /// Mode for parsing entities in the audio caption. See formatting options for more details. @@ -331,18 +311,18 @@ public static async Task SendAudioAsync(this BotClient? api, long chatI /// Duration of the audio in seconds. /// Performer. /// Track name. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass ÔÇ£attach://<file_attach_name>ÔÇØ if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ┬╗. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendAudioAsync(this BotClient? api, string chatId, InputFile audio, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] uint? duration, [Optional] string? performer, [Optional] string? title, [Optional] InputFile? thumbnail, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendAudioAsync(this ITelegramBotClient client, string chatId, InputFile audio, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, uint? duration = null, string? performer = null, string? title = null, InputFile? thumbnail = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client == null) + throw new ArgumentNullException(nameof(client)); var args = new SendAudioArgs(chatId, audio) { MessageThreadId = messageThreadId, @@ -355,19 +335,18 @@ public static async Task SendAudioAsync(this BotClient? api, string cha Thumbnail = thumbnail, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCAF(MethodNames.SendAudio, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendAudio, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Audio caption, 0-1024 characters after entities parsing. /// Mode for parsing entities in the audio caption. See formatting options for more details. @@ -375,19 +354,19 @@ public static async Task SendAudioAsync(this BotClient? api, string cha /// Duration of the audio in seconds. /// Performer. /// Track name. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass ÔÇ£attach://<file_attach_name>ÔÇØ if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ┬╗. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Attached files. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendAudioAsync(this BotClient? api, string chatId, string audio, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] uint? duration, [Optional] string? performer, [Optional] string? title, [Optional] string? thumbnail, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] IEnumerable? attachedFiles, [Optional] CancellationToken cancellationToken) + public static async Task SendAudioAsync(this ITelegramBotClient client, string chatId, string audio, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, uint? duration = null, string? performer = null, string? title = null, string? thumbnail = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, IEnumerable? attachedFiles = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client == null) + throw new ArgumentNullException(nameof(client)); var args = new SendAudioArgs(chatId, audio) { MessageThreadId = messageThreadId, @@ -400,11 +379,10 @@ public static async Task SendAudioAsync(this BotClient? api, string cha Thumbnail = thumbnail, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup, - AttachedFiles = attachedFiles ?? Array.Empty() + AttachedFiles = attachedFiles ?? [] }; - return await api.RPCAF(MethodNames.SendAudio, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendAudio, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/sendChatAction.cs b/src/library/Telegram.BotAPI/Available Methods/sendChatAction.cs similarity index 89% rename from src/Telegram.BotAPI/Available Methods/sendChatAction.cs rename to src/library/Telegram.BotAPI/Available Methods/sendChatAction.cs index 0b4ac599..056e700c 100644 --- a/src/Telegram.BotAPI/Available Methods/sendChatAction.cs +++ b/src/library/Telegram.BotAPI/Available Methods/sendChatAction.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -21,7 +21,7 @@ public static partial class AvailableMethodsExtensions /// Unique identifier for the target message thread; supergroups only. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool SendChatAction(this BotClient? api, long chatId, string action, [Optional] int? messageThreadId) + public static bool SendChatAction(this ITelegramBotClient api, long chatId, string action, [Optional] int? messageThreadId) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -36,7 +36,7 @@ public static bool SendChatAction(this BotClient? api, long chatId, string actio json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.SendChatAction, stream); + return api.CallMethod(MethodNames.SendChatAction, stream); } /// @@ -48,7 +48,7 @@ public static bool SendChatAction(this BotClient? api, long chatId, string actio /// Unique identifier for the target message thread; supergroups only. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool SendChatAction(this BotClient? api, string chatId, string action, [Optional] int? messageThreadId) + public static bool SendChatAction(this ITelegramBotClient api, string chatId, string action, [Optional] int? messageThreadId) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -63,7 +63,7 @@ public static bool SendChatAction(this BotClient? api, string chatId, string act json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.SendChatAction, stream); + return api.CallMethod(MethodNames.SendChatAction, stream); } /// @@ -76,7 +76,7 @@ public static bool SendChatAction(this BotClient? api, string chatId, string act /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendChatActionAsync(this BotClient? api, long chatId, string action, [Optional] int? messageThreadId, [Optional] CancellationToken cancellationToken) + public static async Task SendChatActionAsync(this ITelegramBotClient api, long chatId, string action, [Optional] int? messageThreadId, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -92,7 +92,7 @@ public static async Task SendChatActionAsync(this BotClient? api, long cha await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.SendChatAction, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.SendChatAction, stream, cancellationToken).ConfigureAwait(false); } /// @@ -105,7 +105,7 @@ public static async Task SendChatActionAsync(this BotClient? api, long cha /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendChatActionAsync(this BotClient? api, string chatId, string action, [Optional] int? messageThreadId, [Optional] CancellationToken cancellationToken) + public static async Task SendChatActionAsync(this ITelegramBotClient api, string chatId, string action, [Optional] int? messageThreadId, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -121,7 +121,7 @@ public static async Task SendChatActionAsync(this BotClient? api, string c await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.SendChatAction, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.SendChatAction, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/sendContact.cs b/src/library/Telegram.BotAPI/Available Methods/sendContact.cs similarity index 65% rename from src/Telegram.BotAPI/Available Methods/sendContact.cs rename to src/library/Telegram.BotAPI/Available Methods/sendContact.cs index 0b6b52cb..6cfcd1f8 100644 --- a/src/Telegram.BotAPI/Available Methods/sendContact.cs +++ b/src/library/Telegram.BotAPI/Available Methods/sendContact.cs @@ -1,11 +1,10 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; using System.Threading.Tasks; using Telegram.BotAPI.AvailableTypes; - namespace Telegram.BotAPI.AvailableMethods; public static partial class AvailableMethodsExtensions @@ -16,14 +15,14 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message Object. - public static Message SendContact(this BotClient? bot, SendContactArgs args) + public static Message SendContact(this ITelegramBotClient bot, SendContactArgs args) { - if (bot == default) + if (bot is null) { throw new ArgumentNullException(nameof(bot)); } - return bot.RPC(MethodNames.SendContact, args); + return bot.CallMethod(MethodNames.SendContact, args); } /// Use this method to send phone contacts. On success, the sent Message is returned. /// BotClient @@ -32,25 +31,25 @@ public static Message SendContact(this BotClient? bot, SendContactArgs args) /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message Object. - public static async Task SendContactAsync(this BotClient? bot, SendContactArgs args, [Optional] CancellationToken cancellationToken) + public static async Task SendContactAsync(this ITelegramBotClient bot, SendContactArgs args, CancellationToken cancellationToken = default) { - if (bot == default) + if (bot is null) { throw new ArgumentNullException(nameof(bot)); } - if (args == default) + if (args is null) { throw new ArgumentNullException(nameof(args)); } - return await bot.RPCA(MethodNames.SendContact, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SendContact, args, cancellationToken: cancellationToken).ConfigureAwait(false); } /// /// Use this method to send phone contacts. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Contact's phone number. /// Contact's first name. @@ -59,14 +58,14 @@ public static async Task SendContactAsync(this BotClient? bot, SendCont /// Additional data about the contact in the form of a vCard, 0-2048 bytes. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendContact(this BotClient? api, long chatId, string phoneNumber, string firstName, [Optional] int? messageThreadId, [Optional] string? lastName, [Optional] string? vcard, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendContact(this ITelegramBotClient client, long chatId, string phoneNumber, string firstName, int? messageThreadId = null, string? lastName = null, string? vcard = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendContactArgs(chatId, phoneNumber, firstName) { MessageThreadId = messageThreadId, @@ -74,17 +73,16 @@ public static Message SendContact(this BotClient? api, long chatId, string phone Vcard = vcard, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPC(MethodNames.SendContact, args); + return client.CallMethod(MethodNames.SendContact, args); } /// /// Use this method to send phone contacts. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Contact's phone number. /// Contact's first name. @@ -93,14 +91,14 @@ public static Message SendContact(this BotClient? api, long chatId, string phone /// Additional data about the contact in the form of a vCard, 0-2048 bytes. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendContact(this BotClient? api, string chatId, string phoneNumber, string firstName, [Optional] int? messageThreadId, [Optional] string? lastName, [Optional] string? vcard, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendContact(this ITelegramBotClient client, string chatId, string phoneNumber, string firstName, int? messageThreadId = null, string? lastName = null, string? vcard = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendContactArgs(chatId, phoneNumber, firstName) { MessageThreadId = messageThreadId, @@ -108,17 +106,16 @@ public static Message SendContact(this BotClient? api, string chatId, string pho Vcard = vcard, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPC(MethodNames.SendContact, args); + return client.CallMethod(MethodNames.SendContact, args); } /// /// Use this method to send phone contacts. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Contact's phone number. /// Contact's first name. @@ -127,15 +124,15 @@ public static Message SendContact(this BotClient? api, string chatId, string pho /// Additional data about the contact in the form of a vCard, 0-2048 bytes. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendContactAsync(this BotClient? api, long chatId, string phoneNumber, string firstName, [Optional] int? messageThreadId, [Optional] string? lastName, [Optional] string? vcard, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendContactAsync(this ITelegramBotClient client, long chatId, string phoneNumber, string firstName, int? messageThreadId = null, string? lastName = null, string? vcard = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendContactArgs(chatId, phoneNumber, firstName) { MessageThreadId = messageThreadId, @@ -143,17 +140,16 @@ public static async Task SendContactAsync(this BotClient? api, long cha Vcard = vcard, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCA(MethodNames.SendContact, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendContact, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send phone contacts. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Contact's phone number. /// Contact's first name. @@ -162,15 +158,15 @@ public static async Task SendContactAsync(this BotClient? api, long cha /// Additional data about the contact in the form of a vCard, 0-2048 bytes. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendContactAsync(this BotClient? api, string chatId, string phoneNumber, string firstName, [Optional] int? messageThreadId, [Optional] string? lastName, [Optional] string? vcard, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendContactAsync(this ITelegramBotClient client, string chatId, string phoneNumber, string firstName, int? messageThreadId = null, string? lastName = null, string? vcard = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendContactArgs(chatId, phoneNumber, firstName) { MessageThreadId = messageThreadId, @@ -178,10 +174,9 @@ public static async Task SendContactAsync(this BotClient? api, string c Vcard = vcard, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCA(MethodNames.SendContact, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendContact, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/sendDice.cs b/src/library/Telegram.BotAPI/Available Methods/sendDice.cs similarity index 58% rename from src/Telegram.BotAPI/Available Methods/sendDice.cs rename to src/library/Telegram.BotAPI/Available Methods/sendDice.cs index 0c1dc04c..326c37b0 100644 --- a/src/Telegram.BotAPI/Available Methods/sendDice.cs +++ b/src/library/Telegram.BotAPI/Available Methods/sendDice.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -16,19 +16,19 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message Object. - public static Message SendDice(this BotClient? bot, SendDiceArgs args) + public static Message SendDice(this ITelegramBotClient bot, SendDiceArgs args) { - if (bot == default) + if (bot is null) { throw new ArgumentNullException(nameof(bot)); } - if (args == default) + if (args is null) { throw new ArgumentNullException(nameof(args)); } - return bot.RPC(MethodNames.SendDice, args); + return bot.CallMethod(MethodNames.SendDice, args); } /// Use this method to send a dice, which will have a random value from 1 to 6. On success, the sent Message is returned. (Yes, we're aware of the “proper” singular of die. But it's awkward, and we decided to help it change. One dice at a time!) @@ -38,140 +38,136 @@ public static Message SendDice(this BotClient? bot, SendDiceArgs args) /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message Object. - public static async Task SendDiceAsync(this BotClient? bot, SendDiceArgs args, [Optional] CancellationToken cancellationToken) + public static async Task SendDiceAsync(this ITelegramBotClient bot, SendDiceArgs args, CancellationToken cancellationToken = default) { - if (bot == default) + if (bot is null) { throw new ArgumentNullException(nameof(bot)); } - if (args == default) + if (args is null) { throw new ArgumentNullException(nameof(args)); } - return await bot.RPCA(MethodNames.SendDice, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SendDice, args, cancellationToken: cancellationToken).ConfigureAwait(false); } /// /// Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. - /// Emoji on which the dice throw animation is based. Currently, must be one of ÔÇ£ÔÇØ, ÔÇ£ÔÇØ, ÔÇ£ÔÇØ, ÔÇ£ÔÇØ, ÔÇ£ÔÇØ, or ÔÇ£ÔÇØ. Dice can have values 1-6 for ÔÇ£ÔÇØ, ÔÇ£ÔÇØ and ÔÇ£ÔÇØ, values 1-5 for ÔÇ£ÔÇØ and ÔÇ£ÔÇØ, and values 1-64 for ÔÇ£ÔÇØ. Defaults to ÔÇ£ÔÇØ. + /// Emoji on which the dice throw animation is based. Currently, must be one of “”, “”, “”, “”, “”, or “”. Dice can have values 1-6 for “”, “” and “”, values 1-5 for “” and “”, and values 1-64 for “”. Defaults to “”. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendDice(this BotClient? api, long chatId, [Optional] int? messageThreadId, [Optional] string? emoji, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendDice(this ITelegramBotClient client, long chatId, int? messageThreadId = null, string? emoji = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendDiceArgs(chatId) { MessageThreadId = messageThreadId, Emoji = emoji, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPC(MethodNames.SendDice, args); + return client.CallMethod(MethodNames.SendDice, args); } /// /// Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. - /// Emoji on which the dice throw animation is based. Currently, must be one of ÔÇ£ÔÇØ, ÔÇ£ÔÇØ, ÔÇ£ÔÇØ, ÔÇ£ÔÇØ, ÔÇ£ÔÇØ, or ÔÇ£ÔÇØ. Dice can have values 1-6 for ÔÇ£ÔÇØ, ÔÇ£ÔÇØ and ÔÇ£ÔÇØ, values 1-5 for ÔÇ£ÔÇØ and ÔÇ£ÔÇØ, and values 1-64 for ÔÇ£ÔÇØ. Defaults to ÔÇ£ÔÇØ. + /// Emoji on which the dice throw animation is based. Currently, must be one of “”, “”, “”, “”, “”, or “”. Dice can have values 1-6 for “”, “” and “”, values 1-5 for “” and “”, and values 1-64 for “”. Defaults to “”. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendDice(this BotClient? api, string chatId, [Optional] int? messageThreadId, [Optional] string? emoji, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendDice(this ITelegramBotClient client, string chatId, int? messageThreadId = null, string? emoji = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendDiceArgs(chatId) { MessageThreadId = messageThreadId, Emoji = emoji, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPC(MethodNames.SendDice, args); + return client.CallMethod(MethodNames.SendDice, args); } /// /// Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. - /// Emoji on which the dice throw animation is based. Currently, must be one of ÔÇ£ÔÇØ, ÔÇ£ÔÇØ, ÔÇ£ÔÇØ, ÔÇ£ÔÇØ, ÔÇ£ÔÇØ, or ÔÇ£ÔÇØ. Dice can have values 1-6 for ÔÇ£ÔÇØ, ÔÇ£ÔÇØ and ÔÇ£ÔÇØ, values 1-5 for ÔÇ£ÔÇØ and ÔÇ£ÔÇØ, and values 1-64 for ÔÇ£ÔÇØ. Defaults to ÔÇ£ÔÇØ. + /// Emoji on which the dice throw animation is based. Currently, must be one of “”, “”, “”, “”, “”, or “”. Dice can have values 1-6 for “”, “” and “”, values 1-5 for “” and “”, and values 1-64 for “”. Defaults to “”. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendDiceAsync(this BotClient? api, long chatId, [Optional] int? messageThreadId, [Optional] string? emoji, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendDiceAsync(this ITelegramBotClient client, long chatId, int? messageThreadId = null, string? emoji = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendDiceArgs(chatId) { MessageThreadId = messageThreadId, Emoji = emoji, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCA(MethodNames.SendDice, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendDice, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. - /// Emoji on which the dice throw animation is based. Currently, must be one of ÔÇ£ÔÇØ, ÔÇ£ÔÇØ, ÔÇ£ÔÇØ, ÔÇ£ÔÇØ, ÔÇ£ÔÇØ, or ÔÇ£ÔÇØ. Dice can have values 1-6 for ÔÇ£ÔÇØ, ÔÇ£ÔÇØ and ÔÇ£ÔÇØ, values 1-5 for ÔÇ£ÔÇØ and ÔÇ£ÔÇØ, and values 1-64 for ÔÇ£ÔÇØ. Defaults to ÔÇ£ÔÇØ. + /// Emoji on which the dice throw animation is based. Currently, must be one of “”, “”, “”, “”, “”, or “”. Dice can have values 1-6 for “”, “” and “”, values 1-5 for “” and “”, and values 1-64 for “”. Defaults to “”. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendDiceAsync(this BotClient? api, string chatId, [Optional] int? messageThreadId, [Optional] string? emoji, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendDiceAsync(this ITelegramBotClient client, string chatId, int? messageThreadId = null, string? emoji = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendDiceArgs(chatId) { MessageThreadId = messageThreadId, Emoji = emoji, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCA(MethodNames.SendDice, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendDice, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/sendDocument.cs b/src/library/Telegram.BotAPI/Available Methods/sendDocument.cs similarity index 65% rename from src/Telegram.BotAPI/Available Methods/sendDocument.cs rename to src/library/Telegram.BotAPI/Available Methods/sendDocument.cs index e4769c75..1e168b39 100644 --- a/src/Telegram.BotAPI/Available Methods/sendDocument.cs +++ b/src/library/Telegram.BotAPI/Available Methods/sendDocument.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -10,70 +10,60 @@ namespace Telegram.BotAPI.AvailableMethods; public static partial class AvailableMethodsExtensions { /// Use this method to send general files. On success, the sent Message is returned. - /// BotClient + /// The bot client /// Parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message Object. - public static Message SendDocument(this BotClient? bot, SendDocumentArgs args) + public static Message SendDocument(this ITelegramBotClient client, SendDocumentArgs args) { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - - if (args == default) - { + if (client is null) + throw new ArgumentNullException(nameof(client)); + if (args is null) throw new ArgumentNullException(nameof(args)); - } - return bot.RPCF(MethodNames.SendDocument, args); + return client.CallMethod(MethodNames.SendDocument, args); } /// Use this method to send general files. On success, the sent Message is returned. - /// BotClient + /// The bot client /// Parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// The cancellation token to cancel operation. /// Message Object. - public static async Task SendDocumentAsync(this BotClient? bot, SendDocumentArgs args, [Optional] CancellationToken cancellationToken) + public static Task SendDocumentAsync(this ITelegramBotClient client, SendDocumentArgs args, CancellationToken cancellationToken = default) { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - - if (args == default) - { + if (client is null) + throw new ArgumentNullException(nameof(client)); + if (args is null) throw new ArgumentNullException(nameof(args)); - } - return await bot.RPCAF(MethodNames.SendDocument, args, cancellationToken).ConfigureAwait(false); + return client.CallMethodAsync(MethodNames.SendDocument, args, cancellationToken); } /// /// Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass ÔÇ£attach://<file_attach_name>ÔÇØ if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ┬╗. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Document caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing. /// Mode for parsing entities in the document caption. See formatting options for more details. /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. /// Disables automatic server-side content type detection for files uploaded using multipart/form-data. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendDocument(this BotClient? api, long chatId, InputFile document, [Optional] int? messageThreadId, [Optional] InputFile? thumbnail, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? disableContentTypeDetection, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendDocument(this ITelegramBotClient client, long chatId, InputFile document, int? messageThreadId = null, InputFile? thumbnail = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? disableContentTypeDetection = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendDocumentArgs(chatId, document) { MessageThreadId = messageThreadId, @@ -84,36 +74,35 @@ public static Message SendDocument(this BotClient? api, long chatId, InputFile d DisableContentTypeDetection = disableContentTypeDetection, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPCF(MethodNames.SendDocument, args); + return client.CallMethod(MethodNames.SendDocument, args); } /// /// Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass ÔÇ£attach://<file_attach_name>ÔÇØ if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ┬╗. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Document caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing. /// Mode for parsing entities in the document caption. See formatting options for more details. /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. /// Disables automatic server-side content type detection for files uploaded using multipart/form-data. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Attached files. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendDocument(this BotClient? api, long chatId, string document, [Optional] int? messageThreadId, [Optional] string? thumbnail, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? disableContentTypeDetection, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] IEnumerable? attachedFiles) + public static Message SendDocument(this ITelegramBotClient client, long chatId, string document, int? messageThreadId = null, string? thumbnail = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? disableContentTypeDetection = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, IEnumerable? attachedFiles = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendDocumentArgs(chatId, document) { MessageThreadId = messageThreadId, @@ -124,36 +113,35 @@ public static Message SendDocument(this BotClient? api, long chatId, string docu DisableContentTypeDetection = disableContentTypeDetection, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup, - AttachedFiles = attachedFiles ?? Array.Empty() + AttachedFiles = attachedFiles ?? [] }; - return api.RPCF(MethodNames.SendDocument, args); + return client.CallMethod(MethodNames.SendDocument, args); } /// /// Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass ÔÇ£attach://<file_attach_name>ÔÇØ if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ┬╗. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Document caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing. /// Mode for parsing entities in the document caption. See formatting options for more details. /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. /// Disables automatic server-side content type detection for files uploaded using multipart/form-data. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendDocument(this BotClient? api, string chatId, InputFile document, [Optional] int? messageThreadId, [Optional] InputFile? thumbnail, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? disableContentTypeDetection, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendDocument(this ITelegramBotClient client, string chatId, InputFile document, int? messageThreadId = null, InputFile? thumbnail = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? disableContentTypeDetection = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendDocumentArgs(chatId, document) { MessageThreadId = messageThreadId, @@ -164,36 +152,35 @@ public static Message SendDocument(this BotClient? api, string chatId, InputFile DisableContentTypeDetection = disableContentTypeDetection, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPCF(MethodNames.SendDocument, args); + return client.CallMethod(MethodNames.SendDocument, args); } /// /// Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass ÔÇ£attach://<file_attach_name>ÔÇØ if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ┬╗. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Document caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing. /// Mode for parsing entities in the document caption. See formatting options for more details. /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. /// Disables automatic server-side content type detection for files uploaded using multipart/form-data. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Attached files. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendDocument(this BotClient? api, string chatId, string document, [Optional] int? messageThreadId, [Optional] string? thumbnail, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? disableContentTypeDetection, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] IEnumerable? attachedFiles) + public static Message SendDocument(this ITelegramBotClient client, string chatId, string document, int? messageThreadId = null, string? thumbnail = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? disableContentTypeDetection = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, IEnumerable? attachedFiles = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendDocumentArgs(chatId, document) { MessageThreadId = messageThreadId, @@ -204,37 +191,36 @@ public static Message SendDocument(this BotClient? api, string chatId, string do DisableContentTypeDetection = disableContentTypeDetection, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup, - AttachedFiles = attachedFiles ?? Array.Empty() + AttachedFiles = attachedFiles ?? [] }; - return api.RPCF(MethodNames.SendDocument, args); + return client.CallMethod(MethodNames.SendDocument, args); } /// /// Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass ÔÇ£attach://<file_attach_name>ÔÇØ if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ┬╗. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Document caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing. /// Mode for parsing entities in the document caption. See formatting options for more details. /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. /// Disables automatic server-side content type detection for files uploaded using multipart/form-data. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendDocumentAsync(this BotClient? api, long chatId, InputFile document, [Optional] int? messageThreadId, [Optional] InputFile? thumbnail, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? disableContentTypeDetection, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendDocumentAsync(this ITelegramBotClient client, long chatId, InputFile document, int? messageThreadId = null, InputFile? thumbnail = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? disableContentTypeDetection = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendDocumentArgs(chatId, document) { MessageThreadId = messageThreadId, @@ -245,37 +231,36 @@ public static async Task SendDocumentAsync(this BotClient? api, long ch DisableContentTypeDetection = disableContentTypeDetection, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCAF(MethodNames.SendDocument, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendDocument, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass ÔÇ£attach://<file_attach_name>ÔÇØ if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ┬╗. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Document caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing. /// Mode for parsing entities in the document caption. See formatting options for more details. /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. /// Disables automatic server-side content type detection for files uploaded using multipart/form-data. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Attached files. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendDocumentAsync(this BotClient? api, long chatId, string document, [Optional] int? messageThreadId, [Optional] string? thumbnail, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? disableContentTypeDetection, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] IEnumerable? attachedFiles, [Optional] CancellationToken cancellationToken) + public static async Task SendDocumentAsync(this ITelegramBotClient client, long chatId, string document, int? messageThreadId = null, string? thumbnail = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? disableContentTypeDetection = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, IEnumerable? attachedFiles = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendDocumentArgs(chatId, document) { MessageThreadId = messageThreadId, @@ -286,37 +271,36 @@ public static async Task SendDocumentAsync(this BotClient? api, long ch DisableContentTypeDetection = disableContentTypeDetection, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup, - AttachedFiles = attachedFiles ?? Array.Empty() + AttachedFiles = attachedFiles ?? [] }; - return await api.RPCAF(MethodNames.SendDocument, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendDocument, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass ÔÇ£attach://<file_attach_name>ÔÇØ if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ┬╗. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Document caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing. /// Mode for parsing entities in the document caption. See formatting options for more details. /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. /// Disables automatic server-side content type detection for files uploaded using multipart/form-data. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendDocumentAsync(this BotClient? api, string chatId, InputFile document, [Optional] int? messageThreadId, [Optional] InputFile? thumbnail, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? disableContentTypeDetection, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendDocumentAsync(this ITelegramBotClient client, string chatId, InputFile document, int? messageThreadId = null, InputFile? thumbnail = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? disableContentTypeDetection = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendDocumentArgs(chatId, document) { MessageThreadId = messageThreadId, @@ -327,37 +311,36 @@ public static async Task SendDocumentAsync(this BotClient? api, string DisableContentTypeDetection = disableContentTypeDetection, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCAF(MethodNames.SendDocument, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendDocument, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass ÔÇ£attach://<file_attach_name>ÔÇØ if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ┬╗. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Document caption (may also be used when resending documents by file_id), 0-1024 characters after entities parsing. /// Mode for parsing entities in the document caption. See formatting options for more details. /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. /// Disables automatic server-side content type detection for files uploaded using multipart/form-data. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Attached files. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendDocumentAsync(this BotClient? api, string chatId, string document, [Optional] int? messageThreadId, [Optional] string? thumbnail, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? disableContentTypeDetection, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] IEnumerable? attachedFiles, [Optional] CancellationToken cancellationToken) + public static async Task SendDocumentAsync(this ITelegramBotClient client, string chatId, string document, int? messageThreadId = null, string? thumbnail = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? disableContentTypeDetection = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, IEnumerable? attachedFiles = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendDocumentArgs(chatId, document) { MessageThreadId = messageThreadId, @@ -368,11 +351,10 @@ public static async Task SendDocumentAsync(this BotClient? api, string DisableContentTypeDetection = disableContentTypeDetection, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup, - AttachedFiles = attachedFiles ?? Array.Empty() + AttachedFiles = attachedFiles ?? [] }; - return await api.RPCAF(MethodNames.SendDocument, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendDocument, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/sendLocation.cs b/src/library/Telegram.BotAPI/Available Methods/sendLocation.cs similarity index 69% rename from src/Telegram.BotAPI/Available Methods/sendLocation.cs rename to src/library/Telegram.BotAPI/Available Methods/sendLocation.cs index 97efcef0..76a9395b 100644 --- a/src/Telegram.BotAPI/Available Methods/sendLocation.cs +++ b/src/library/Telegram.BotAPI/Available Methods/sendLocation.cs @@ -1,11 +1,10 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; using System.Threading.Tasks; using Telegram.BotAPI.AvailableTypes; - namespace Telegram.BotAPI.AvailableMethods; public static partial class AvailableMethodsExtensions @@ -16,14 +15,14 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message Object. - public static Message SendLocation(this BotClient? bot, SendLocationArgs args) + public static Message SendLocation(this ITelegramBotClient bot, SendLocationArgs args) { - if (bot == default) + if (bot is null) { throw new ArgumentNullException(nameof(bot)); } - return bot.RPC(MethodNames.SendLocation, args); + return bot.CallMethod(MethodNames.SendLocation, args); } /// Use this method to send point on the map. On success, the sent Message is returned. /// BotClient @@ -32,25 +31,25 @@ public static Message SendLocation(this BotClient? bot, SendLocationArgs args) /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message Object. - public static async Task SendLocationAsync(this BotClient? bot, SendLocationArgs args, [Optional] CancellationToken cancellationToken) + public static async Task SendLocationAsync(this ITelegramBotClient bot, SendLocationArgs args, CancellationToken cancellationToken = default) { - if (bot == default) + if (bot is null) { throw new ArgumentNullException(nameof(bot)); } - if (args == default) + if (args is null) { throw new ArgumentNullException(nameof(args)); } - return await bot.RPCA(MethodNames.SendLocation, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SendLocation, args, cancellationToken: cancellationToken).ConfigureAwait(false); } /// /// Use this method to send point on the map. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Latitude of the location. /// Longitude of the location. @@ -61,14 +60,14 @@ public static async Task SendLocationAsync(this BotClient? bot, SendLoc /// For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendLocation(this BotClient? api, long chatId, float latitude, float longitude, [Optional] int? messageThreadId, [Optional] float? horizontalAccuracy, [Optional] uint? livePeriod, [Optional] ushort? heading, [Optional] uint? proximityAlertRadius, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendLocation(this ITelegramBotClient client, long chatId, float latitude, float longitude, int? messageThreadId = null, float? horizontalAccuracy = null, uint? livePeriod = null, ushort? heading = null, uint? proximityAlertRadius = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendLocationArgs(chatId, latitude, longitude) { MessageThreadId = messageThreadId, @@ -78,17 +77,16 @@ public static Message SendLocation(this BotClient? api, long chatId, float latit ProximityAlertRadius = proximityAlertRadius, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPC(MethodNames.SendLocation, args); + return client.CallMethod(MethodNames.SendLocation, args); } /// /// Use this method to send point on the map. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Latitude of the location. /// Longitude of the location. @@ -99,14 +97,14 @@ public static Message SendLocation(this BotClient? api, long chatId, float latit /// For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendLocation(this BotClient? api, string chatId, float latitude, float longitude, [Optional] int? messageThreadId, [Optional] float? horizontalAccuracy, [Optional] uint? livePeriod, [Optional] ushort? heading, [Optional] uint? proximityAlertRadius, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendLocation(this ITelegramBotClient client, string chatId, float latitude, float longitude, int? messageThreadId = null, float? horizontalAccuracy = null, uint? livePeriod = null, ushort? heading = null, uint? proximityAlertRadius = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendLocationArgs(chatId, latitude, longitude) { MessageThreadId = messageThreadId, @@ -116,17 +114,16 @@ public static Message SendLocation(this BotClient? api, string chatId, float lat ProximityAlertRadius = proximityAlertRadius, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPC(MethodNames.SendLocation, args); + return client.CallMethod(MethodNames.SendLocation, args); } /// /// Use this method to send point on the map. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Latitude of the location. /// Longitude of the location. @@ -137,15 +134,15 @@ public static Message SendLocation(this BotClient? api, string chatId, float lat /// For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendLocationAsync(this BotClient? api, long chatId, float latitude, float longitude, [Optional] int? messageThreadId, [Optional] float? horizontalAccuracy, [Optional] uint? livePeriod, [Optional] ushort? heading, [Optional] uint? proximityAlertRadius, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendLocationAsync(this ITelegramBotClient client, long chatId, float latitude, float longitude, int? messageThreadId = null, float? horizontalAccuracy = null, uint? livePeriod = null, ushort? heading = null, uint? proximityAlertRadius = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendLocationArgs(chatId, latitude, longitude) { MessageThreadId = messageThreadId, @@ -155,17 +152,16 @@ public static async Task SendLocationAsync(this BotClient? api, long ch ProximityAlertRadius = proximityAlertRadius, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCA(MethodNames.SendLocation, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendLocation, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send point on the map. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Latitude of the location. /// Longitude of the location. @@ -176,15 +172,15 @@ public static async Task SendLocationAsync(this BotClient? api, long ch /// For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendLocationAsync(this BotClient? api, string chatId, float latitude, float longitude, [Optional] int? messageThreadId, [Optional] float? horizontalAccuracy, [Optional] uint? livePeriod, [Optional] ushort? heading, [Optional] uint? proximityAlertRadius, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendLocationAsync(this ITelegramBotClient client, string chatId, float latitude, float longitude, int? messageThreadId = null, float? horizontalAccuracy = null, uint? livePeriod = null, ushort? heading = null, uint? proximityAlertRadius = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendLocationArgs(chatId, latitude, longitude) { MessageThreadId = messageThreadId, @@ -194,10 +190,9 @@ public static async Task SendLocationAsync(this BotClient? api, string ProximityAlertRadius = proximityAlertRadius, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCA(MethodNames.SendLocation, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendLocation, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/sendMediaGroup.cs b/src/library/Telegram.BotAPI/Available Methods/sendMediaGroup.cs similarity index 62% rename from src/Telegram.BotAPI/Available Methods/sendMediaGroup.cs rename to src/library/Telegram.BotAPI/Available Methods/sendMediaGroup.cs index 0cce10ef..eae21b77 100644 --- a/src/Telegram.BotAPI/Available Methods/sendMediaGroup.cs +++ b/src/library/Telegram.BotAPI/Available Methods/sendMediaGroup.cs @@ -1,6 +1,7 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Telegram.BotAPI.AvailableTypes; @@ -15,19 +16,19 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message enumerable. - public static Message[] SendMediaGroup(this BotClient? bot, SendMediaGroupArgs args) + public static IEnumerable SendMediaGroup(this ITelegramBotClient bot, SendMediaGroupArgs args) { - if (bot == default) + if (bot is null) { throw new ArgumentNullException(nameof(bot)); } - if (args == default) + if (args is null) { throw new ArgumentNullException(nameof(args)); } - return bot.RPCF(MethodNames.SendMediaGroup, args); + return bot.CallMethod>(MethodNames.SendMediaGroup, args); } /// Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only group in an album with messages of the same type. On success, an array of Messages that were sent is returned. /// BotClient @@ -36,136 +37,131 @@ public static Message[] SendMediaGroup(this BotClient? bot, SendMediaGroupArgs a /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message enumerable. - public static async Task SendMediaGroupAsync(this BotClient? bot, SendMediaGroupArgs args, [Optional] CancellationToken cancellationToken) + public static async Task> SendMediaGroupAsync(this ITelegramBotClient bot, SendMediaGroupArgs args, CancellationToken cancellationToken = default) { - if (bot == default) + if (bot is null) { throw new ArgumentNullException(nameof(bot)); } - if (args == default) + if (args is null) { throw new ArgumentNullException(nameof(args)); } - return await bot.RPCAF(MethodNames.SendMediaGroup, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync>(MethodNames.SendMediaGroup, args, cancellationToken: cancellationToken).ConfigureAwait(false); } /// /// Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of Messages that were sent is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// A JSON-serialized array describing messages to be sent, must include 2-10 items. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Sends messages silently. Users will receive a notification with no sound. /// Protects the contents of the sent messages from forwarding and saving. - /// If the messages are a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Attached files. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message[] SendMediaGroup(this BotClient? api, long chatId, IEnumerable media, [Optional] int? messageThreadId, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] IEnumerable? attachedFiles) + public static IEnumerable SendMediaGroup(this ITelegramBotClient client, long chatId, IEnumerable media, int? messageThreadId = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, IEnumerable? attachedFiles = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendMediaGroupArgs(chatId, media) { MessageThreadId = messageThreadId, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, - AttachedFiles = attachedFiles ?? Array.Empty() + ReplyParameters = replyParameters, + AttachedFiles = attachedFiles ?? [] }; - return api.RPCF(MethodNames.SendMediaGroup, args); + return client.CallMethod>(MethodNames.SendMediaGroup, args); } - /// /// Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of Messages that were sent is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// A JSON-serialized array describing messages to be sent, must include 2-10 items. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Sends messages silently. Users will receive a notification with no sound. /// Protects the contents of the sent messages from forwarding and saving. - /// If the messages are a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Attached files. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message[] SendMediaGroup(this BotClient? api, string chatId, IEnumerable media, [Optional] int? messageThreadId, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] IEnumerable? attachedFiles) + public static IEnumerable SendMediaGroup(this ITelegramBotClient client, string chatId, IEnumerable media, int? messageThreadId = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, IEnumerable? attachedFiles = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendMediaGroupArgs(chatId, media) { MessageThreadId = messageThreadId, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, - AttachedFiles = attachedFiles ?? Array.Empty() + ReplyParameters = replyParameters, + AttachedFiles = attachedFiles ?? [] }; - return api.RPCF(MethodNames.SendMediaGroup, args); + return client.CallMethod>(MethodNames.SendMediaGroup, args); } /// /// Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of Messages that were sent is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// A JSON-serialized array describing messages to be sent, must include 2-10 items. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Sends messages silently. Users will receive a notification with no sound. /// Protects the contents of the sent messages from forwarding and saving. - /// If the messages are a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Attached files. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendMediaGroupAsync(this BotClient? api, long chatId, IEnumerable media, [Optional] int? messageThreadId, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] IEnumerable? attachedFiles, [Optional] CancellationToken cancellationToken) + public static async Task> SendMediaGroupAsync(this ITelegramBotClient client, long chatId, IEnumerable media, int? messageThreadId = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, IEnumerable? attachedFiles = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendMediaGroupArgs(chatId, media) { MessageThreadId = messageThreadId, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, - AttachedFiles = attachedFiles ?? Array.Empty() + ReplyParameters = replyParameters, + AttachedFiles = attachedFiles ?? [] }; - return await api.RPCAF(MethodNames.SendMediaGroup, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync>(MethodNames.SendMediaGroup, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of Messages that were sent is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// A JSON-serialized array describing messages to be sent, must include 2-10 items. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Sends messages silently. Users will receive a notification with no sound. /// Protects the contents of the sent messages from forwarding and saving. - /// If the messages are a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Attached files. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendMediaGroupAsync(this BotClient? api, string chatId, IEnumerable media, [Optional] int? messageThreadId, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] IEnumerable? attachedFiles, [Optional] CancellationToken cancellationToken) + public static async Task> SendMediaGroupAsync(this ITelegramBotClient client, string chatId, IEnumerable media, int? messageThreadId = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, IEnumerable? attachedFiles = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendMediaGroupArgs(chatId, media) { MessageThreadId = messageThreadId, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, - AttachedFiles = attachedFiles ?? Array.Empty() + ReplyParameters = replyParameters, + AttachedFiles = attachedFiles ?? [] }; - return await api.RPCAF(MethodNames.SendMediaGroup, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync>(MethodNames.SendMediaGroup, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/sendMessage.cs b/src/library/Telegram.BotAPI/Available Methods/sendMessage.cs similarity index 61% rename from src/Telegram.BotAPI/Available Methods/sendMessage.cs rename to src/library/Telegram.BotAPI/Available Methods/sendMessage.cs index 0d322c6b..65592914 100644 --- a/src/Telegram.BotAPI/Available Methods/sendMessage.cs +++ b/src/library/Telegram.BotAPI/Available Methods/sendMessage.cs @@ -1,197 +1,182 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; using System.Threading.Tasks; using Telegram.BotAPI.AvailableTypes; - - namespace Telegram.BotAPI.AvailableMethods; public static partial class AvailableMethodsExtensions { /// Use this method to send text messages. On success, the sent Message is returned. - /// BotClient + /// The bot client /// Parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message Object. - public static Message SendMessage(this BotClient? bot, SendMessageArgs args) + public static Message SendMessage(this ITelegramBotClient client, SendMessageArgs args) { - if (bot == null) - { - throw new ArgumentNullException(nameof(bot)); - } - - if (args == default) - { + if (client is null) + throw new ArgumentNullException(nameof(client)); + if (args is null) throw new ArgumentNullException(nameof(args)); - } - - return bot.RPC(MethodNames.SendMessage, args); + return client.CallMethod(MethodNames.SendMessage, args); } + + /// Use this method to send text messages. On success, the sent Message is returned. - /// BotClient + /// The bot client /// Parameters. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message Object. - public static async Task SendMessageAsync(this BotClient? bot, SendMessageArgs args, [Optional] CancellationToken cancellationToken) + public static Task SendMessageAsync(this ITelegramBotClient client, SendMessageArgs args, CancellationToken cancellationToken = default) { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - - if (args == default) - { + if (client is null) + throw new ArgumentNullException(nameof(client)); + if (args is null) throw new ArgumentNullException(nameof(args)); - } - - return await bot.RPCA(MethodNames.SendMessage, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return client.CallMethodAsync(MethodNames.SendMessage, args, cancellationToken: cancellationToken); } + /// /// Use this method to send text messages. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Text of the message to be sent, 1-4096 characters after entities parsing. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Mode for parsing entities in the message text. See formatting options for more details. /// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode. - /// Disables link previews for links in this message. + /// Link preview generation options for the message. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendMessage(this BotClient? api, long chatId, string text, [Optional] int? messageThreadId, [Optional] string parseMode, [Optional] IEnumerable? entities, [Optional] bool? disableWebPagePreview, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendMessage(this ITelegramBotClient client, long chatId, string text, int? messageThreadId = null, string? parseMode = null, IEnumerable? entities = null, LinkPreviewOptions? linkPreviewOptions = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendMessageArgs(chatId, text) { MessageThreadId = messageThreadId, ParseMode = parseMode, Entities = entities, - DisableWebPagePreview = disableWebPagePreview, + LinkPreviewOptions = linkPreviewOptions, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPC(MethodNames.SendMessage, args); + return client.CallMethod(MethodNames.SendMessage, args); } /// /// Use this method to send text messages. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Text of the message to be sent, 1-4096 characters after entities parsing. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Mode for parsing entities in the message text. See formatting options for more details. /// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode. - /// Disables link previews for links in this message. + /// Link preview generation options for the message. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendMessage(this BotClient? api, string chatId, string text, [Optional] int? messageThreadId, [Optional] string parseMode, [Optional] IEnumerable? entities, [Optional] bool? disableWebPagePreview, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendMessage(this ITelegramBotClient client, string chatId, string text, int? messageThreadId = null, string? parseMode = null, IEnumerable? entities = null, LinkPreviewOptions? linkPreviewOptions = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendMessageArgs(chatId, text) { MessageThreadId = messageThreadId, ParseMode = parseMode, Entities = entities, - DisableWebPagePreview = disableWebPagePreview, + LinkPreviewOptions = linkPreviewOptions, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPC(MethodNames.SendMessage, args); + return client.CallMethod(MethodNames.SendMessage, args); } /// /// Use this method to send text messages. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Text of the message to be sent, 1-4096 characters after entities parsing. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Mode for parsing entities in the message text. See formatting options for more details. /// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode. - /// Disables link previews for links in this message. + /// Link preview generation options for the message. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendMessageAsync(this BotClient? api, long chatId, string text, [Optional] int? messageThreadId, [Optional] string parseMode, [Optional] IEnumerable? entities, [Optional] bool? disableWebPagePreview, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendMessageAsync(this ITelegramBotClient client, long chatId, string text, int? messageThreadId = null, string? parseMode = null, IEnumerable? entities = null, LinkPreviewOptions? linkPreviewOptions = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendMessageArgs(chatId, text) { MessageThreadId = messageThreadId, ParseMode = parseMode, Entities = entities, - DisableWebPagePreview = disableWebPagePreview, + LinkPreviewOptions = linkPreviewOptions, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCA(MethodNames.SendMessage, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendMessage, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send text messages. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Text of the message to be sent, 1-4096 characters after entities parsing. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Mode for parsing entities in the message text. See formatting options for more details. /// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode. - /// Disables link previews for links in this message. + /// Link preview generation options for the message. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendMessageAsync(this BotClient? api, string chatId, string text, [Optional] int? messageThreadId, [Optional] string parseMode, [Optional] IEnumerable? entities, [Optional] bool? disableWebPagePreview, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendMessageAsync(this ITelegramBotClient client, string chatId, string text, int? messageThreadId = null, string? parseMode = null, IEnumerable? entities = null, LinkPreviewOptions? linkPreviewOptions = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendMessageArgs(chatId, text) { MessageThreadId = messageThreadId, ParseMode = parseMode, Entities = entities, - DisableWebPagePreview = disableWebPagePreview, + LinkPreviewOptions = linkPreviewOptions, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCA(MethodNames.SendMessage, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendMessage, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/sendPhoto.cs b/src/library/Telegram.BotAPI/Available Methods/sendPhoto.cs similarity index 68% rename from src/Telegram.BotAPI/Available Methods/sendPhoto.cs rename to src/library/Telegram.BotAPI/Available Methods/sendPhoto.cs index f6b01a49..1a7d4206 100644 --- a/src/Telegram.BotAPI/Available Methods/sendPhoto.cs +++ b/src/library/Telegram.BotAPI/Available Methods/sendPhoto.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -11,30 +11,25 @@ namespace Telegram.BotAPI.AvailableMethods; public static partial class AvailableMethodsExtensions { /// Use this method to send photos. On success, the sent Message is returned. - /// BotClient + /// BotClient /// Parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message Object. - public static Message SendPhoto(this BotClient? bot, SendPhotoArgs args) + public static Message SendPhoto(this ITelegramBotClient client, SendPhotoArgs args) { - if (bot == null) - { - throw new ArgumentNullException(nameof(bot)); - } - - if (args == null) - { + if (client is null) + throw new ArgumentNullException(nameof(client)); + if (args is null) throw new ArgumentNullException(nameof(args)); - } - return bot.RPCF(MethodNames.SendPhoto, args); + return client.CallMethod(MethodNames.SendPhoto, args); } /// Use this method to send photos. On success, the sent Message is returned. - /// BotClient + /// BotClient /// Parameters. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. @@ -42,27 +37,23 @@ public static Message SendPhoto(this BotClient? bot, SendPhotoArgs args) /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message Object. - public static async Task SendPhotoAsync(this BotClient? bot, SendPhotoArgs args, [Optional] CancellationToken cancellationToken) + public static Task SendPhotoAsync(this ITelegramBotClient client, SendPhotoArgs args, CancellationToken cancellationToken = default) { - if (bot == null) - { - throw new ArgumentNullException(nameof(bot)); - } - - if (args == null) - { + if (client is null) + throw new ArgumentNullException(nameof(client)); + if (args is null) throw new ArgumentNullException(nameof(args)); - } - return await bot.RPCAF(MethodNames.SendPhoto, args, cancellationToken).ConfigureAwait(false); + return client.CallMethodAsync(MethodNames.SendPhoto, args, cancellationToken); } + /// /// Use this method to send photos. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More information on Sending Files ». + /// Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Photo caption (may also be used when resending photos by file_id), 0-1024 characters after entities parsing. /// Mode for parsing entities in the photo caption. See formatting options for more details. @@ -70,14 +61,14 @@ public static async Task SendPhotoAsync(this BotClient? bot, SendPhotoA /// Pass True if the photo needs to be covered with a spoiler animation. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendPhoto(this BotClient? api, long chatId, InputFile photo, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? hasSpoiler, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendPhoto(this ITelegramBotClient client, long chatId, InputFile photo, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? hasSpoiler = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendPhotoArgs(chatId, photo) { MessageThreadId = messageThreadId, @@ -87,19 +78,18 @@ public static Message SendPhoto(this BotClient? api, long chatId, InputFile phot HasSpoiler = hasSpoiler, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPCF(MethodNames.SendPhoto, args); + return client.CallMethod(MethodNames.SendPhoto, args); } /// /// Use this method to send photos. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More information on Sending Files ». + /// Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Photo caption (may also be used when resending photos by file_id), 0-1024 characters after entities parsing. /// Mode for parsing entities in the photo caption. See formatting options for more details. @@ -107,14 +97,14 @@ public static Message SendPhoto(this BotClient? api, long chatId, InputFile phot /// Pass True if the photo needs to be covered with a spoiler animation. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendPhoto(this BotClient? api, long chatId, string photo, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? hasSpoiler, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendPhoto(this ITelegramBotClient client, long chatId, string photo, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? hasSpoiler = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendPhotoArgs(chatId, photo) { MessageThreadId = messageThreadId, @@ -124,19 +114,18 @@ public static Message SendPhoto(this BotClient? api, long chatId, string photo, HasSpoiler = hasSpoiler, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPCF(MethodNames.SendPhoto, args); + return client.CallMethod(MethodNames.SendPhoto, args); } /// /// Use this method to send photos. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More information on Sending Files ». + /// Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Photo caption (may also be used when resending photos by file_id), 0-1024 characters after entities parsing. /// Mode for parsing entities in the photo caption. See formatting options for more details. @@ -144,14 +133,14 @@ public static Message SendPhoto(this BotClient? api, long chatId, string photo, /// Pass True if the photo needs to be covered with a spoiler animation. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendPhoto(this BotClient? api, string chatId, InputFile photo, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? hasSpoiler, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendPhoto(this ITelegramBotClient client, string chatId, InputFile photo, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? hasSpoiler = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendPhotoArgs(chatId, photo) { MessageThreadId = messageThreadId, @@ -161,19 +150,18 @@ public static Message SendPhoto(this BotClient? api, string chatId, InputFile ph HasSpoiler = hasSpoiler, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPCF(MethodNames.SendPhoto, args); + return client.CallMethod(MethodNames.SendPhoto, args); } /// /// Use this method to send photos. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More information on Sending Files ». + /// Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Photo caption (may also be used when resending photos by file_id), 0-1024 characters after entities parsing. /// Mode for parsing entities in the photo caption. See formatting options for more details. @@ -181,14 +169,14 @@ public static Message SendPhoto(this BotClient? api, string chatId, InputFile ph /// Pass True if the photo needs to be covered with a spoiler animation. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendPhoto(this BotClient? api, string chatId, string photo, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? hasSpoiler, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendPhoto(this ITelegramBotClient client, string chatId, string photo, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? hasSpoiler = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendPhotoArgs(chatId, photo) { MessageThreadId = messageThreadId, @@ -198,19 +186,18 @@ public static Message SendPhoto(this BotClient? api, string chatId, string photo HasSpoiler = hasSpoiler, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPCF(MethodNames.SendPhoto, args); + return client.CallMethod(MethodNames.SendPhoto, args); } /// /// Use this method to send photos. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More information on Sending Files ». + /// Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Photo caption (may also be used when resending photos by file_id), 0-1024 characters after entities parsing. /// Mode for parsing entities in the photo caption. See formatting options for more details. @@ -218,15 +205,15 @@ public static Message SendPhoto(this BotClient? api, string chatId, string photo /// Pass True if the photo needs to be covered with a spoiler animation. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendPhotoAsync(this BotClient? api, long chatId, InputFile photo, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? hasSpoiler, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendPhotoAsync(this ITelegramBotClient client, long chatId, InputFile photo, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? hasSpoiler = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendPhotoArgs(chatId, photo) { MessageThreadId = messageThreadId, @@ -236,19 +223,18 @@ public static async Task SendPhotoAsync(this BotClient? api, long chatI HasSpoiler = hasSpoiler, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCAF(MethodNames.SendPhoto, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendPhoto, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send photos. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More information on Sending Files ». + /// Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Photo caption (may also be used when resending photos by file_id), 0-1024 characters after entities parsing. /// Mode for parsing entities in the photo caption. See formatting options for more details. @@ -256,15 +242,15 @@ public static async Task SendPhotoAsync(this BotClient? api, long chatI /// Pass True if the photo needs to be covered with a spoiler animation. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendPhotoAsync(this BotClient? api, long chatId, string photo, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? hasSpoiler, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendPhotoAsync(this ITelegramBotClient client, long chatId, string photo, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? hasSpoiler = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendPhotoArgs(chatId, photo) { MessageThreadId = messageThreadId, @@ -274,19 +260,18 @@ public static async Task SendPhotoAsync(this BotClient? api, long chatI HasSpoiler = hasSpoiler, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCAF(MethodNames.SendPhoto, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendPhoto, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send photos. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More information on Sending Files ». + /// Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Photo caption (may also be used when resending photos by file_id), 0-1024 characters after entities parsing. /// Mode for parsing entities in the photo caption. See formatting options for more details. @@ -294,15 +279,15 @@ public static async Task SendPhotoAsync(this BotClient? api, long chatI /// Pass True if the photo needs to be covered with a spoiler animation. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendPhotoAsync(this BotClient? api, string chatId, InputFile photo, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? hasSpoiler, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendPhotoAsync(this ITelegramBotClient client, string chatId, InputFile photo, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? hasSpoiler = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendPhotoArgs(chatId, photo) { MessageThreadId = messageThreadId, @@ -312,19 +297,18 @@ public static async Task SendPhotoAsync(this BotClient? api, string cha HasSpoiler = hasSpoiler, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCAF(MethodNames.SendPhoto, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendPhoto, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send photos. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More information on Sending Files ». + /// Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Photo caption (may also be used when resending photos by file_id), 0-1024 characters after entities parsing. /// Mode for parsing entities in the photo caption. See formatting options for more details. @@ -332,15 +316,15 @@ public static async Task SendPhotoAsync(this BotClient? api, string cha /// Pass True if the photo needs to be covered with a spoiler animation. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendPhotoAsync(this BotClient? api, string chatId, string photo, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? hasSpoiler, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendPhotoAsync(this ITelegramBotClient client, string chatId, string photo, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? hasSpoiler = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendPhotoArgs(chatId, photo) { MessageThreadId = messageThreadId, @@ -350,10 +334,9 @@ public static async Task SendPhotoAsync(this BotClient? api, string cha HasSpoiler = hasSpoiler, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCAF(MethodNames.SendPhoto, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendPhoto, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/sendPoll.cs b/src/library/Telegram.BotAPI/Available Methods/sendPoll.cs similarity index 70% rename from src/Telegram.BotAPI/Available Methods/sendPoll.cs rename to src/library/Telegram.BotAPI/Available Methods/sendPoll.cs index 2609f3b1..feb85d0e 100644 --- a/src/Telegram.BotAPI/Available Methods/sendPoll.cs +++ b/src/library/Telegram.BotAPI/Available Methods/sendPoll.cs @@ -1,11 +1,10 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; using System.Threading.Tasks; using Telegram.BotAPI.AvailableTypes; - namespace Telegram.BotAPI.AvailableMethods; public static partial class AvailableMethodsExtensions @@ -15,19 +14,19 @@ public static partial class AvailableMethodsExtensions /// Parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendPoll(this BotClient? bot, SendPollArgs args) + public static Message SendPoll(this ITelegramBotClient bot, SendPollArgs args) { - if (bot == default) + if (bot is null) { throw new ArgumentNullException(nameof(bot)); } - if (args == default) + if (args is null) { throw new ArgumentNullException(nameof(args)); } - return bot.RPC(MethodNames.SendPoll, args); + return bot.CallMethod(MethodNames.SendPoll, args); } /// Use this method to send a native poll. A native poll can't be sent to a private chat. On success, the sent Message is returned. @@ -36,31 +35,31 @@ public static Message SendPoll(this BotClient? bot, SendPollArgs args) /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendPollAsync(this BotClient? bot, SendPollArgs args, [Optional] CancellationToken cancellationToken) + public static async Task SendPollAsync(this ITelegramBotClient bot, SendPollArgs args, CancellationToken cancellationToken = default) { - if (bot == default) + if (bot is null) { throw new ArgumentNullException(nameof(bot)); } - if (args == default) + if (args is null) { throw new ArgumentNullException(nameof(args)); } - return await bot.RPCA(MethodNames.SendPoll, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SendPoll, args, cancellationToken: cancellationToken).ConfigureAwait(false); } /// /// Use this method to send a native poll. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Poll question, 1-300 characters. /// A JSON-serialized list of answer options, 2-10 strings 1-100 characters each. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// True, if the poll needs to be anonymous, defaults to True. - /// Poll type, ÔÇ£quizÔÇØ or ÔÇ£regularÔÇØ, defaults to ÔÇ£regularÔÇØ. + /// Poll type, “quiz” or “regular”, defaults to “regular”. /// True, if the poll allows multiple answers, ignored for polls in quiz mode, defaults to False. /// 0-based identifier of the correct answer option, required for polls in quiz mode. /// Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing. @@ -71,14 +70,14 @@ public static async Task SendPollAsync(this BotClient? bot, SendPollArg /// Pass True if the poll needs to be immediately closed. This can be useful for poll preview. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendPoll(this BotClient? api, long chatId, string question, IEnumerable options, [Optional] int? messageThreadId, [Optional] bool? isAnonymous, [Optional] string? type, [Optional] bool? allowsMultipleAnswers, [Optional] uint? correctOptionId, [Optional] string? explanation, [Optional] string? explanationParseMode, [Optional] IEnumerable? explanationEntities, [Optional] ushort? openPeriod, [Optional] uint? closeDate, [Optional] bool? isClosed, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendPoll(this ITelegramBotClient client, long chatId, string question, IEnumerable options, int? messageThreadId = null, bool? isAnonymous = null, string? type = null, bool? allowsMultipleAnswers = null, uint? correctOptionId = null, string? explanation = null, string? explanationParseMode = null, IEnumerable? explanationEntities = null, ushort? openPeriod = null, uint? closeDate = null, bool? isClosed = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendPollArgs(chatId, question, options) { MessageThreadId = messageThreadId, @@ -94,23 +93,22 @@ public static Message SendPoll(this BotClient? api, long chatId, string question IsClosed = isClosed, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPC(MethodNames.SendPoll, args); + return client.CallMethod(MethodNames.SendPoll, args); } /// /// Use this method to send a native poll. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Poll question, 1-300 characters. /// A JSON-serialized list of answer options, 2-10 strings 1-100 characters each. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// True, if the poll needs to be anonymous, defaults to True. - /// Poll type, ÔÇ£quizÔÇØ or ÔÇ£regularÔÇØ, defaults to ÔÇ£regularÔÇØ. + /// Poll type, “quiz” or “regular”, defaults to “regular”. /// True, if the poll allows multiple answers, ignored for polls in quiz mode, defaults to False. /// 0-based identifier of the correct answer option, required for polls in quiz mode. /// Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing. @@ -121,14 +119,14 @@ public static Message SendPoll(this BotClient? api, long chatId, string question /// Pass True if the poll needs to be immediately closed. This can be useful for poll preview. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendPoll(this BotClient? api, string chatId, string question, IEnumerable options, [Optional] int? messageThreadId, [Optional] bool? isAnonymous, [Optional] string? type, [Optional] bool? allowsMultipleAnswers, [Optional] uint? correctOptionId, [Optional] string? explanation, [Optional] string? explanationParseMode, [Optional] IEnumerable? explanationEntities, [Optional] ushort? openPeriod, [Optional] uint? closeDate, [Optional] bool? isClosed, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendPoll(this ITelegramBotClient client, string chatId, string question, IEnumerable options, int? messageThreadId = null, bool? isAnonymous = null, string? type = null, bool? allowsMultipleAnswers = null, uint? correctOptionId = null, string? explanation = null, string? explanationParseMode = null, IEnumerable? explanationEntities = null, ushort? openPeriod = null, uint? closeDate = null, bool? isClosed = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendPollArgs(chatId, question, options) { MessageThreadId = messageThreadId, @@ -144,23 +142,22 @@ public static Message SendPoll(this BotClient? api, string chatId, string questi IsClosed = isClosed, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPC(MethodNames.SendPoll, args); + return client.CallMethod(MethodNames.SendPoll, args); } /// /// Use this method to send a native poll. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Poll question, 1-300 characters. /// A JSON-serialized list of answer options, 2-10 strings 1-100 characters each. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// True, if the poll needs to be anonymous, defaults to True. - /// Poll type, ÔÇ£quizÔÇØ or ÔÇ£regularÔÇØ, defaults to ÔÇ£regularÔÇØ. + /// Poll type, “quiz” or “regular”, defaults to “regular”. /// True, if the poll allows multiple answers, ignored for polls in quiz mode, defaults to False. /// 0-based identifier of the correct answer option, required for polls in quiz mode. /// Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing. @@ -171,15 +168,15 @@ public static Message SendPoll(this BotClient? api, string chatId, string questi /// Pass True if the poll needs to be immediately closed. This can be useful for poll preview. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendPollAsync(this BotClient? api, long chatId, string question, IEnumerable options, [Optional] int? messageThreadId, [Optional] bool? isAnonymous, [Optional] string? type, [Optional] bool? allowsMultipleAnswers, [Optional] uint? correctOptionId, [Optional] string? explanation, [Optional] string? explanationParseMode, [Optional] IEnumerable? explanationEntities, [Optional] ushort? openPeriod, [Optional] uint? closeDate, [Optional] bool? isClosed, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendPollAsync(this ITelegramBotClient client, long chatId, string question, IEnumerable options, int? messageThreadId = null, bool? isAnonymous = null, string? type = null, bool? allowsMultipleAnswers = null, uint? correctOptionId = null, string? explanation = null, string? explanationParseMode = null, IEnumerable? explanationEntities = null, ushort? openPeriod = null, uint? closeDate = null, bool? isClosed = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendPollArgs(chatId, question, options) { MessageThreadId = messageThreadId, @@ -195,23 +192,22 @@ public static async Task SendPollAsync(this BotClient? api, long chatId IsClosed = isClosed, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCA(MethodNames.SendPoll, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendPoll, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send a native poll. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Poll question, 1-300 characters. /// A JSON-serialized list of answer options, 2-10 strings 1-100 characters each. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// True, if the poll needs to be anonymous, defaults to True. - /// Poll type, ÔÇ£quizÔÇØ or ÔÇ£regularÔÇØ, defaults to ÔÇ£regularÔÇØ. + /// Poll type, “quiz” or “regular”, defaults to “regular”. /// True, if the poll allows multiple answers, ignored for polls in quiz mode, defaults to False. /// 0-based identifier of the correct answer option, required for polls in quiz mode. /// Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing. @@ -222,15 +218,15 @@ public static async Task SendPollAsync(this BotClient? api, long chatId /// Pass True if the poll needs to be immediately closed. This can be useful for poll preview. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendPollAsync(this BotClient? api, string chatId, string question, IEnumerable options, [Optional] int? messageThreadId, [Optional] bool? isAnonymous, [Optional] string? type, [Optional] bool? allowsMultipleAnswers, [Optional] uint? correctOptionId, [Optional] string? explanation, [Optional] string? explanationParseMode, [Optional] IEnumerable? explanationEntities, [Optional] ushort? openPeriod, [Optional] uint? closeDate, [Optional] bool? isClosed, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendPollAsync(this ITelegramBotClient client, string chatId, string question, IEnumerable options, int? messageThreadId = null, bool? isAnonymous = null, string? type = null, bool? allowsMultipleAnswers = null, uint? correctOptionId = null, string? explanation = null, string? explanationParseMode = null, IEnumerable? explanationEntities = null, ushort? openPeriod = null, uint? closeDate = null, bool? isClosed = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendPollArgs(chatId, question, options) { MessageThreadId = messageThreadId, @@ -246,10 +242,9 @@ public static async Task SendPollAsync(this BotClient? api, string chat IsClosed = isClosed, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCA(MethodNames.SendPoll, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendPoll, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/sendVenue.cs b/src/library/Telegram.BotAPI/Available Methods/sendVenue.cs similarity index 64% rename from src/Telegram.BotAPI/Available Methods/sendVenue.cs rename to src/library/Telegram.BotAPI/Available Methods/sendVenue.cs index 6cb9b382..bc9903b6 100644 --- a/src/Telegram.BotAPI/Available Methods/sendVenue.cs +++ b/src/library/Telegram.BotAPI/Available Methods/sendVenue.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -16,14 +16,14 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message Object. - public static Message SendVenue(this BotClient? bot, SendVenueArgs args) + public static Message SendVenue(this ITelegramBotClient bot, SendVenueArgs args) { - if (bot == default) + if (bot is null) { throw new ArgumentNullException(nameof(bot)); } - return bot.RPC(MethodNames.SendVenue, args); + return bot.CallMethod(MethodNames.SendVenue, args); } /// Use this method to send information about a venue. On success, the sent Message is returned. /// BotClient @@ -32,25 +32,25 @@ public static Message SendVenue(this BotClient? bot, SendVenueArgs args) /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message Object. - public static async Task SendVenueAsync(this BotClient? bot, SendVenueArgs args, [Optional] CancellationToken cancellationToken) + public static async Task SendVenueAsync(this ITelegramBotClient bot, SendVenueArgs args, CancellationToken cancellationToken = default) { - if (bot == default) + if (bot is null) { throw new ArgumentNullException(nameof(bot)); } - if (args == default) + if (args is null) { throw new ArgumentNullException(nameof(args)); } - return await bot.RPCA(MethodNames.SendVenue, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SendVenue, args, cancellationToken: cancellationToken).ConfigureAwait(false); } /// /// Use this method to send information about a venue. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Latitude of the venue. /// Longitude of the venue. @@ -58,19 +58,19 @@ public static async Task SendVenueAsync(this BotClient? bot, SendVenueA /// Address of the venue. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Foursquare identifier of the venue. - /// Foursquare type of the venue, if known. (For example, ÔÇ£arts_entertainment/defaultÔÇØ, ÔÇ£arts_entertainment/aquariumÔÇØ or ÔÇ£food/icecreamÔÇØ.). + /// Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.). /// Google Places identifier of the venue. /// Google Places type of the venue. (See supported types.). /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendVenue(this BotClient? api, long chatId, float latitude, float longitude, string title, string address, [Optional] int? messageThreadId, [Optional] string? foursquareId, [Optional] string? foursquareType, [Optional] string? googlePlaceId, [Optional] string? googlePlaceType, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendVenue(this ITelegramBotClient client, long chatId, float latitude, float longitude, string title, string address, int? messageThreadId = null, string? foursquareId = null, string? foursquareType = null, string? googlePlaceId = null, string? googlePlaceType = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVenueArgs(chatId, latitude, longitude, title, address) { MessageThreadId = messageThreadId, @@ -80,17 +80,16 @@ public static Message SendVenue(this BotClient? api, long chatId, float latitude GooglePlaceType = googlePlaceType, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPC(MethodNames.SendVenue, args); + return client.CallMethod(MethodNames.SendVenue, args); } /// /// Use this method to send information about a venue. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Latitude of the venue. /// Longitude of the venue. @@ -98,19 +97,19 @@ public static Message SendVenue(this BotClient? api, long chatId, float latitude /// Address of the venue. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Foursquare identifier of the venue. - /// Foursquare type of the venue, if known. (For example, ÔÇ£arts_entertainment/defaultÔÇØ, ÔÇ£arts_entertainment/aquariumÔÇØ or ÔÇ£food/icecreamÔÇØ.). + /// Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.). /// Google Places identifier of the venue. /// Google Places type of the venue. (See supported types.). /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendVenue(this BotClient? api, string chatId, float latitude, float longitude, string title, string address, [Optional] int? messageThreadId, [Optional] string? foursquareId, [Optional] string? foursquareType, [Optional] string? googlePlaceId, [Optional] string? googlePlaceType, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendVenue(this ITelegramBotClient client, string chatId, float latitude, float longitude, string title, string address, int? messageThreadId = null, string? foursquareId = null, string? foursquareType = null, string? googlePlaceId = null, string? googlePlaceType = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVenueArgs(chatId, latitude, longitude, title, address) { MessageThreadId = messageThreadId, @@ -120,17 +119,16 @@ public static Message SendVenue(this BotClient? api, string chatId, float latitu GooglePlaceType = googlePlaceType, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPC(MethodNames.SendVenue, args); + return client.CallMethod(MethodNames.SendVenue, args); } /// /// Use this method to send information about a venue. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Latitude of the venue. /// Longitude of the venue. @@ -138,20 +136,20 @@ public static Message SendVenue(this BotClient? api, string chatId, float latitu /// Address of the venue. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Foursquare identifier of the venue. - /// Foursquare type of the venue, if known. (For example, ÔÇ£arts_entertainment/defaultÔÇØ, ÔÇ£arts_entertainment/aquariumÔÇØ or ÔÇ£food/icecreamÔÇØ.). + /// Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.). /// Google Places identifier of the venue. /// Google Places type of the venue. (See supported types.). /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendVenueAsync(this BotClient? api, long chatId, float latitude, float longitude, string title, string address, [Optional] int? messageThreadId, [Optional] string? foursquareId, [Optional] string? foursquareType, [Optional] string? googlePlaceId, [Optional] string? googlePlaceType, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendVenueAsync(this ITelegramBotClient client, long chatId, float latitude, float longitude, string title, string address, int? messageThreadId = null, string? foursquareId = null, string? foursquareType = null, string? googlePlaceId = null, string? googlePlaceType = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVenueArgs(chatId, latitude, longitude, title, address) { MessageThreadId = messageThreadId, @@ -161,17 +159,16 @@ public static async Task SendVenueAsync(this BotClient? api, long chatI GooglePlaceType = googlePlaceType, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCA(MethodNames.SendVenue, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendVenue, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send information about a venue. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Latitude of the venue. /// Longitude of the venue. @@ -179,20 +176,20 @@ public static async Task SendVenueAsync(this BotClient? api, long chatI /// Address of the venue. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Foursquare identifier of the venue. - /// Foursquare type of the venue, if known. (For example, ÔÇ£arts_entertainment/defaultÔÇØ, ÔÇ£arts_entertainment/aquariumÔÇØ or ÔÇ£food/icecreamÔÇØ.). + /// Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, “arts_entertainment/aquarium” or “food/icecream”.). /// Google Places identifier of the venue. /// Google Places type of the venue. (See supported types.). /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendVenueAsync(this BotClient? api, string chatId, float latitude, float longitude, string title, string address, [Optional] int? messageThreadId, [Optional] string? foursquareId, [Optional] string? foursquareType, [Optional] string? googlePlaceId, [Optional] string? googlePlaceType, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendVenueAsync(this ITelegramBotClient client, string chatId, float latitude, float longitude, string title, string address, int? messageThreadId = null, string? foursquareId = null, string? foursquareType = null, string? googlePlaceId = null, string? googlePlaceType = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVenueArgs(chatId, latitude, longitude, title, address) { MessageThreadId = messageThreadId, @@ -202,10 +199,9 @@ public static async Task SendVenueAsync(this BotClient? api, string cha GooglePlaceType = googlePlaceType, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCA(MethodNames.SendVenue, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendVenue, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/sendVideo.cs b/src/library/Telegram.BotAPI/Available Methods/sendVideo.cs similarity index 70% rename from src/Telegram.BotAPI/Available Methods/sendVideo.cs rename to src/library/Telegram.BotAPI/Available Methods/sendVideo.cs index 5a2476e9..e0222edc 100644 --- a/src/Telegram.BotAPI/Available Methods/sendVideo.cs +++ b/src/library/Telegram.BotAPI/Available Methods/sendVideo.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -10,60 +10,48 @@ namespace Telegram.BotAPI.AvailableMethods; public static partial class AvailableMethodsExtensions { - /// Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). - /// BotClient + /// + /// Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. + /// + /// The bot client /// Parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// On success, the sent Message is returned. - public static Message SendVideo(this BotClient? bot, SendVideoArgs args) + public static Message SendVideo(this ITelegramBotClient client, SendVideoArgs args) { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - - return bot.RPCF(MethodNames.SendVideo, args); + return client is null + ? throw new ArgumentNullException(nameof(client)) + : client.CallMethod(MethodNames.SendVideo, args); } - /// Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). - /// BotClient + /// + /// Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. + /// + /// The bot client /// Parameters. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// On success, the sent Message is returned. - public static async Task SendVideoAsync(this BotClient? bot, SendVideoArgs args, [Optional] CancellationToken cancellationToken) + public static Task SendVideoAsync(this ITelegramBotClient client, SendVideoArgs args, CancellationToken cancellationToken = default) { - if (bot == default) - { - throw new ArgumentNullException(nameof(bot)); - } - - if (args == default) - { - throw new ArgumentNullException(nameof(args)); - } - - return await bot.RPCAF(MethodNames.SendVideo, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return client is null + ? throw new ArgumentNullException(nameof(client)) + : client.CallMethodAsync(MethodNames.SendVideo, args, cancellationToken: cancellationToken); } /// /// Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. More information on Sending Files ». + /// Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Duration of sent video in seconds. /// Video width. /// Video height. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Video caption (may also be used when resending videos by file_id), 0-1024 characters after entities parsing. /// Mode for parsing entities in the video caption. See formatting options for more details. /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. @@ -71,14 +59,14 @@ public static async Task SendVideoAsync(this BotClient? bot, SendVideoA /// Pass True if the uploaded video is suitable for streaming. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendVideo(this BotClient? api, long chatId, InputFile video, [Optional] int? messageThreadId, [Optional] uint? duration, [Optional] uint? width, [Optional] uint? height, [Optional] InputFile? thumbnail, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? hasSpoiler, [Optional] bool? supportsStreaming, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendVideo(this ITelegramBotClient client, long chatId, InputFile video, int? messageThreadId = null, uint? duration = null, uint? width = null, uint? height = null, InputFile? thumbnail = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? hasSpoiler = null, bool? supportsStreaming = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVideoArgs(chatId, video) { MessageThreadId = messageThreadId, @@ -93,24 +81,23 @@ public static Message SendVideo(this BotClient? api, long chatId, InputFile vide SupportsStreaming = supportsStreaming, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPCF(MethodNames.SendVideo, args); + return client.CallMethod(MethodNames.SendVideo, args); } /// /// Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. More information on Sending Files ». + /// Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Duration of sent video in seconds. /// Video width. /// Video height. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Video caption (may also be used when resending videos by file_id), 0-1024 characters after entities parsing. /// Mode for parsing entities in the video caption. See formatting options for more details. /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. @@ -118,15 +105,15 @@ public static Message SendVideo(this BotClient? api, long chatId, InputFile vide /// Pass True if the uploaded video is suitable for streaming. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Attached files. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendVideo(this BotClient? api, long chatId, string video, [Optional] int? messageThreadId, [Optional] uint? duration, [Optional] uint? width, [Optional] uint? height, [Optional] string? thumbnail, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? hasSpoiler, [Optional] bool? supportsStreaming, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] IEnumerable? attachedFiles) + public static Message SendVideo(this ITelegramBotClient client, long chatId, string video, int? messageThreadId = null, uint? duration = null, uint? width = null, uint? height = null, string? thumbnail = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? hasSpoiler = null, bool? supportsStreaming = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, IEnumerable? attachedFiles = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVideoArgs(chatId, video) { MessageThreadId = messageThreadId, @@ -141,25 +128,24 @@ public static Message SendVideo(this BotClient? api, long chatId, string video, SupportsStreaming = supportsStreaming, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup, - AttachedFiles = attachedFiles ?? Array.Empty() + AttachedFiles = attachedFiles ?? [] }; - return api.RPCF(MethodNames.SendVideo, args); + return client.CallMethod(MethodNames.SendVideo, args); } /// /// Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. More information on Sending Files ». + /// Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Duration of sent video in seconds. /// Video width. /// Video height. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Video caption (may also be used when resending videos by file_id), 0-1024 characters after entities parsing. /// Mode for parsing entities in the video caption. See formatting options for more details. /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. @@ -167,14 +153,14 @@ public static Message SendVideo(this BotClient? api, long chatId, string video, /// Pass True if the uploaded video is suitable for streaming. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendVideo(this BotClient? api, string chatId, InputFile video, [Optional] int? messageThreadId, [Optional] uint? duration, [Optional] uint? width, [Optional] uint? height, [Optional] InputFile? thumbnail, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? hasSpoiler, [Optional] bool? supportsStreaming, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendVideo(this ITelegramBotClient client, string chatId, InputFile video, int? messageThreadId = null, uint? duration = null, uint? width = null, uint? height = null, InputFile? thumbnail = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? hasSpoiler = null, bool? supportsStreaming = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVideoArgs(chatId, video) { MessageThreadId = messageThreadId, @@ -189,24 +175,23 @@ public static Message SendVideo(this BotClient? api, string chatId, InputFile vi SupportsStreaming = supportsStreaming, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPCF(MethodNames.SendVideo, args); + return client.CallMethod(MethodNames.SendVideo, args); } /// /// Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. More information on Sending Files ». + /// Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Duration of sent video in seconds. /// Video width. /// Video height. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Video caption (may also be used when resending videos by file_id), 0-1024 characters after entities parsing. /// Mode for parsing entities in the video caption. See formatting options for more details. /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. @@ -214,15 +199,15 @@ public static Message SendVideo(this BotClient? api, string chatId, InputFile vi /// Pass True if the uploaded video is suitable for streaming. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Attached files. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendVideo(this BotClient? api, string chatId, string video, [Optional] int? messageThreadId, [Optional] uint? duration, [Optional] uint? width, [Optional] uint? height, [Optional] string? thumbnail, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? hasSpoiler, [Optional] bool? supportsStreaming, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] IEnumerable? attachedFiles) + public static Message SendVideo(this ITelegramBotClient client, string chatId, string video, int? messageThreadId = null, uint? duration = null, uint? width = null, uint? height = null, string? thumbnail = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? hasSpoiler = null, bool? supportsStreaming = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, IEnumerable? attachedFiles = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVideoArgs(chatId, video) { MessageThreadId = messageThreadId, @@ -237,25 +222,24 @@ public static Message SendVideo(this BotClient? api, string chatId, string video SupportsStreaming = supportsStreaming, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup, - AttachedFiles = attachedFiles ?? Array.Empty() + AttachedFiles = attachedFiles ?? [] }; - return api.RPCF(MethodNames.SendVideo, args); + return client.CallMethod(MethodNames.SendVideo, args); } /// /// Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. More information on Sending Files ». + /// Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Duration of sent video in seconds. /// Video width. /// Video height. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Video caption (may also be used when resending videos by file_id), 0-1024 characters after entities parsing. /// Mode for parsing entities in the video caption. See formatting options for more details. /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. @@ -263,15 +247,15 @@ public static Message SendVideo(this BotClient? api, string chatId, string video /// Pass True if the uploaded video is suitable for streaming. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendVideoAsync(this BotClient? api, long chatId, InputFile video, [Optional] int? messageThreadId, [Optional] uint? duration, [Optional] uint? width, [Optional] uint? height, [Optional] InputFile? thumbnail, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? hasSpoiler, [Optional] bool? supportsStreaming, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendVideoAsync(this ITelegramBotClient client, long chatId, InputFile video, int? messageThreadId = null, uint? duration = null, uint? width = null, uint? height = null, InputFile? thumbnail = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? hasSpoiler = null, bool? supportsStreaming = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVideoArgs(chatId, video) { MessageThreadId = messageThreadId, @@ -286,24 +270,23 @@ public static async Task SendVideoAsync(this BotClient? api, long chatI SupportsStreaming = supportsStreaming, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCAF(MethodNames.SendVideo, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendVideo, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. More information on Sending Files ». + /// Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Duration of sent video in seconds. /// Video width. /// Video height. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Video caption (may also be used when resending videos by file_id), 0-1024 characters after entities parsing. /// Mode for parsing entities in the video caption. See formatting options for more details. /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. @@ -311,16 +294,16 @@ public static async Task SendVideoAsync(this BotClient? api, long chatI /// Pass True if the uploaded video is suitable for streaming. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Attached files. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendVideoAsync(this BotClient? api, long chatId, string video, [Optional] int? messageThreadId, [Optional] uint? duration, [Optional] uint? width, [Optional] uint? height, [Optional] string? thumbnail, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? hasSpoiler, [Optional] bool? supportsStreaming, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] IEnumerable? attachedFiles, [Optional] CancellationToken cancellationToken) + public static async Task SendVideoAsync(this ITelegramBotClient client, long chatId, string video, int? messageThreadId = null, uint? duration = null, uint? width = null, uint? height = null, string? thumbnail = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? hasSpoiler = null, bool? supportsStreaming = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, IEnumerable? attachedFiles = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVideoArgs(chatId, video) { MessageThreadId = messageThreadId, @@ -335,25 +318,24 @@ public static async Task SendVideoAsync(this BotClient? api, long chatI SupportsStreaming = supportsStreaming, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup, - AttachedFiles = attachedFiles ?? Array.Empty() + AttachedFiles = attachedFiles ?? [] }; - return await api.RPCAF(MethodNames.SendVideo, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendVideo, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. More information on Sending Files ». + /// Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Duration of sent video in seconds. /// Video width. /// Video height. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Video caption (may also be used when resending videos by file_id), 0-1024 characters after entities parsing. /// Mode for parsing entities in the video caption. See formatting options for more details. /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. @@ -361,15 +343,15 @@ public static async Task SendVideoAsync(this BotClient? api, long chatI /// Pass True if the uploaded video is suitable for streaming. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendVideoAsync(this BotClient? api, string chatId, InputFile video, [Optional] int? messageThreadId, [Optional] uint? duration, [Optional] uint? width, [Optional] uint? height, [Optional] InputFile? thumbnail, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? hasSpoiler, [Optional] bool? supportsStreaming, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendVideoAsync(this ITelegramBotClient client, string chatId, InputFile video, int? messageThreadId = null, uint? duration = null, uint? width = null, uint? height = null, InputFile? thumbnail = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? hasSpoiler = null, bool? supportsStreaming = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVideoArgs(chatId, video) { MessageThreadId = messageThreadId, @@ -384,24 +366,23 @@ public static async Task SendVideoAsync(this BotClient? api, string cha SupportsStreaming = supportsStreaming, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCAF(MethodNames.SendVideo, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendVideo, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. More information on Sending Files ». + /// Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Duration of sent video in seconds. /// Video width. /// Video height. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Video caption (may also be used when resending videos by file_id), 0-1024 characters after entities parsing. /// Mode for parsing entities in the video caption. See formatting options for more details. /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. @@ -409,16 +390,16 @@ public static async Task SendVideoAsync(this BotClient? api, string cha /// Pass True if the uploaded video is suitable for streaming. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Attached files. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendVideoAsync(this BotClient? api, string chatId, string video, [Optional] int? messageThreadId, [Optional] uint? duration, [Optional] uint? width, [Optional] uint? height, [Optional] string? thumbnail, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] bool? hasSpoiler, [Optional] bool? supportsStreaming, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] IEnumerable? attachedFiles, [Optional] CancellationToken cancellationToken) + public static async Task SendVideoAsync(this ITelegramBotClient client, string chatId, string video, int? messageThreadId = null, uint? duration = null, uint? width = null, uint? height = null, string? thumbnail = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, bool? hasSpoiler = null, bool? supportsStreaming = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, IEnumerable? attachedFiles = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVideoArgs(chatId, video) { MessageThreadId = messageThreadId, @@ -433,11 +414,10 @@ public static async Task SendVideoAsync(this BotClient? api, string cha SupportsStreaming = supportsStreaming, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup, - AttachedFiles = attachedFiles ?? Array.Empty() + AttachedFiles = attachedFiles ?? [] }; - return await api.RPCAF(MethodNames.SendVideo, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendVideo, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/sendVideoNote.cs b/src/library/Telegram.BotAPI/Available Methods/sendVideoNote.cs similarity index 63% rename from src/Telegram.BotAPI/Available Methods/sendVideoNote.cs rename to src/library/Telegram.BotAPI/Available Methods/sendVideoNote.cs index f69d6ad6..9ef1a012 100644 --- a/src/Telegram.BotAPI/Available Methods/sendVideoNote.cs +++ b/src/library/Telegram.BotAPI/Available Methods/sendVideoNote.cs @@ -1,11 +1,10 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; using System.Threading.Tasks; using Telegram.BotAPI.AvailableTypes; - namespace Telegram.BotAPI.AvailableMethods; public static partial class AvailableMethodsExtensions @@ -16,20 +15,21 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message Object. - public static Message SendVideoNote(this BotClient? bot, SendVideoNoteArgs args) + public static Message SendVideoNote(this ITelegramBotClient bot, SendVideoNoteArgs args) { - if (bot == default) + if (bot is null) { throw new ArgumentNullException(nameof(bot)); } - if (args == default) + if (args is null) { throw new ArgumentNullException(nameof(args)); } - return bot.RPCF(MethodNames.SendVideoNote, args); + return bot.CallMethod(MethodNames.SendVideoNote, args); } + /// As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned. /// BotClient /// Parameters. @@ -37,41 +37,41 @@ public static Message SendVideoNote(this BotClient? bot, SendVideoNoteArgs args) /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message Object. - public static async Task SendVideoNoteAsync(this BotClient? bot, SendVideoNoteArgs args, [Optional] CancellationToken cancellationToken) + public static Task SendVideoNoteAsync(this ITelegramBotClient bot, SendVideoNoteArgs args, CancellationToken cancellationToken = default) { - if (bot == default) + if (bot is null) { throw new ArgumentNullException(nameof(bot)); } - if (args == default) + if (args is null) { throw new ArgumentNullException(nameof(args)); } - return await bot.RPCAF(MethodNames.SendVideoNote, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return bot.CallMethodAsync(MethodNames.SendVideoNote, args, cancellationToken: cancellationToken); } /// /// As of v.4.0, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ┬╗. Sending video notes by a URL is currently unsupported. + /// Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ». Sending video notes by a URL is currently unsupported. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Duration of sent video in seconds. /// Video width and height, i.e. diameter of the video message. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass ÔÇ£attach://<file_attach_name>ÔÇØ if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ┬╗. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendVideoNote(this BotClient? api, long chatId, InputFile videoNote, [Optional] int? messageThreadId, [Optional] uint? duration, [Optional] uint? length, [Optional] InputFile? thumbnail, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendVideoNote(this ITelegramBotClient client, long chatId, InputFile videoNote, int? messageThreadId = null, uint? duration = null, uint? length = null, InputFile? thumbnail = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVideoNoteArgs(chatId, videoNote) { MessageThreadId = messageThreadId, @@ -80,34 +80,33 @@ public static Message SendVideoNote(this BotClient? api, long chatId, InputFile Thumbnail = thumbnail, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPCF(MethodNames.SendVideoNote, args); + return client.CallMethod(MethodNames.SendVideoNote, args); } /// /// As of v.4.0, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ┬╗. Sending video notes by a URL is currently unsupported. + /// Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ». Sending video notes by a URL is currently unsupported. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Duration of sent video in seconds. /// Video width and height, i.e. diameter of the video message. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass ÔÇ£attach://<file_attach_name>ÔÇØ if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ┬╗. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Attached files. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendVideoNote(this BotClient? api, long chatId, string videoNote, [Optional] int? messageThreadId, [Optional] uint? duration, [Optional] uint? length, [Optional] string? thumbnail, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] IEnumerable? attachedFiles) + public static Message SendVideoNote(this ITelegramBotClient client, long chatId, string videoNote, int? messageThreadId = null, uint? duration = null, uint? length = null, string? thumbnail = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, IEnumerable? attachedFiles = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVideoNoteArgs(chatId, videoNote) { MessageThreadId = messageThreadId, @@ -116,34 +115,33 @@ public static Message SendVideoNote(this BotClient? api, long chatId, string vid Thumbnail = thumbnail, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup, - AttachedFiles = attachedFiles ?? Array.Empty() + AttachedFiles = attachedFiles ?? [] }; - return api.RPCF(MethodNames.SendVideoNote, args); + return client.CallMethod(MethodNames.SendVideoNote, args); } /// /// As of v.4.0, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ┬╗. Sending video notes by a URL is currently unsupported. + /// Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ». Sending video notes by a URL is currently unsupported. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Duration of sent video in seconds. /// Video width and height, i.e. diameter of the video message. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass ÔÇ£attach://<file_attach_name>ÔÇØ if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ┬╗. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendVideoNote(this BotClient? api, string chatId, InputFile videoNote, [Optional] int? messageThreadId, [Optional] uint? duration, [Optional] uint? length, [Optional] InputFile? thumbnail, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendVideoNote(this ITelegramBotClient client, string chatId, InputFile videoNote, int? messageThreadId = null, uint? duration = null, uint? length = null, InputFile? thumbnail = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVideoNoteArgs(chatId, videoNote) { MessageThreadId = messageThreadId, @@ -152,34 +150,33 @@ public static Message SendVideoNote(this BotClient? api, string chatId, InputFil Thumbnail = thumbnail, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPCF(MethodNames.SendVideoNote, args); + return client.CallMethod(MethodNames.SendVideoNote, args); } /// /// As of v.4.0, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ┬╗. Sending video notes by a URL is currently unsupported. + /// Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ». Sending video notes by a URL is currently unsupported. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Duration of sent video in seconds. /// Video width and height, i.e. diameter of the video message. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass ÔÇ£attach://<file_attach_name>ÔÇØ if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ┬╗. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Attached files. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendVideoNote(this BotClient? api, string chatId, string videoNote, [Optional] int? messageThreadId, [Optional] uint? duration, [Optional] uint? length, [Optional] string? thumbnail, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] IEnumerable? attachedFiles) + public static Message SendVideoNote(this ITelegramBotClient client, string chatId, string videoNote, int? messageThreadId = null, uint? duration = null, uint? length = null, string? thumbnail = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, IEnumerable? attachedFiles = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVideoNoteArgs(chatId, videoNote) { MessageThreadId = messageThreadId, @@ -188,35 +185,34 @@ public static Message SendVideoNote(this BotClient? api, string chatId, string v Thumbnail = thumbnail, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup, - AttachedFiles = attachedFiles ?? Array.Empty() + AttachedFiles = attachedFiles ?? [] }; - return api.RPCF(MethodNames.SendVideoNote, args); + return client.CallMethod(MethodNames.SendVideoNote, args); } /// /// As of v.4.0, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ┬╗. Sending video notes by a URL is currently unsupported. + /// Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ». Sending video notes by a URL is currently unsupported. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Duration of sent video in seconds. /// Video width and height, i.e. diameter of the video message. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass ÔÇ£attach://<file_attach_name>ÔÇØ if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ┬╗. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendVideoNoteAsync(this BotClient? api, long chatId, InputFile videoNote, [Optional] int? messageThreadId, [Optional] uint? duration, [Optional] uint? length, [Optional] InputFile? thumbnail, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static Task SendVideoNoteAsync(this ITelegramBotClient client, long chatId, InputFile videoNote, int? messageThreadId = null, uint? duration = null, uint? length = null, InputFile? thumbnail = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVideoNoteArgs(chatId, videoNote) { MessageThreadId = messageThreadId, @@ -225,35 +221,34 @@ public static async Task SendVideoNoteAsync(this BotClient? api, long c Thumbnail = thumbnail, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCAF(MethodNames.SendVideoNote, args, cancellationToken).ConfigureAwait(false); + return client.CallMethodAsync(MethodNames.SendVideoNote, args, cancellationToken); } /// /// As of v.4.0, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ┬╗. Sending video notes by a URL is currently unsupported. + /// Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ». Sending video notes by a URL is currently unsupported. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Duration of sent video in seconds. /// Video width and height, i.e. diameter of the video message. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass ÔÇ£attach://<file_attach_name>ÔÇØ if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ┬╗. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Attached files. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendVideoNoteAsync(this BotClient? api, long chatId, string videoNote, [Optional] int? messageThreadId, [Optional] uint? duration, [Optional] uint? length, [Optional] string? thumbnail, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] IEnumerable? attachedFiles, [Optional] CancellationToken cancellationToken) + public static Task SendVideoNoteAsync(this ITelegramBotClient client, long chatId, string videoNote, int? messageThreadId = null, uint? duration = null, uint? length = null, string? thumbnail = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, IEnumerable? attachedFiles = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVideoNoteArgs(chatId, videoNote) { MessageThreadId = messageThreadId, @@ -262,35 +257,34 @@ public static async Task SendVideoNoteAsync(this BotClient? api, long c Thumbnail = thumbnail, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup, - AttachedFiles = attachedFiles ?? Array.Empty() + AttachedFiles = attachedFiles ?? [] }; - return await api.RPCAF(MethodNames.SendVideoNote, args, cancellationToken).ConfigureAwait(false); + return client.CallMethodAsync(MethodNames.SendVideoNote, args, cancellationToken); } /// /// As of v.4.0, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ┬╗. Sending video notes by a URL is currently unsupported. + /// Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ». Sending video notes by a URL is currently unsupported. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Duration of sent video in seconds. /// Video width and height, i.e. diameter of the video message. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass ÔÇ£attach://<file_attach_name>ÔÇØ if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ┬╗. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendVideoNoteAsync(this BotClient? api, string chatId, InputFile videoNote, [Optional] int? messageThreadId, [Optional] uint? duration, [Optional] uint? length, [Optional] InputFile? thumbnail, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static Task SendVideoNoteAsync(this ITelegramBotClient client, string chatId, InputFile videoNote, int? messageThreadId = null, uint? duration = null, uint? length = null, InputFile? thumbnail = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVideoNoteArgs(chatId, videoNote) { MessageThreadId = messageThreadId, @@ -299,35 +293,34 @@ public static async Task SendVideoNoteAsync(this BotClient? api, string Thumbnail = thumbnail, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCAF(MethodNames.SendVideoNote, args, cancellationToken).ConfigureAwait(false); + return client.CallMethodAsync(MethodNames.SendVideoNote, args, cancellationToken); } /// /// As of v.4.0, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ┬╗. Sending video notes by a URL is currently unsupported. + /// Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. More information on Sending Files ». Sending video notes by a URL is currently unsupported. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Duration of sent video in seconds. /// Video width and height, i.e. diameter of the video message. - /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass ÔÇ£attach://<file_attach_name>ÔÇØ if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ┬╗. + /// Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data under <file_attach_name>. More information on Sending Files ». /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Attached files. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendVideoNoteAsync(this BotClient? api, string chatId, string videoNote, [Optional] int? messageThreadId, [Optional] uint? duration, [Optional] uint? length, [Optional] string? thumbnail, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] IEnumerable? attachedFiles, [Optional] CancellationToken cancellationToken) + public static Task SendVideoNoteAsync(this ITelegramBotClient client, string chatId, string videoNote, int? messageThreadId = null, uint? duration = null, uint? length = null, string? thumbnail = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, IEnumerable? attachedFiles = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVideoNoteArgs(chatId, videoNote) { MessageThreadId = messageThreadId, @@ -336,11 +329,10 @@ public static async Task SendVideoNoteAsync(this BotClient? api, string Thumbnail = thumbnail, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup, - AttachedFiles = attachedFiles ?? Array.Empty() + AttachedFiles = attachedFiles ?? [] }; - return await api.RPCAF(MethodNames.SendVideoNote, args, cancellationToken).ConfigureAwait(false); + return client.CallMethodAsync(MethodNames.SendVideoNote, args, cancellationToken); } } diff --git a/src/Telegram.BotAPI/Available Methods/sendVoice.cs b/src/library/Telegram.BotAPI/Available Methods/sendVoice.cs similarity index 70% rename from src/Telegram.BotAPI/Available Methods/sendVoice.cs rename to src/library/Telegram.BotAPI/Available Methods/sendVoice.cs index 6222c061..eb685e85 100644 --- a/src/Telegram.BotAPI/Available Methods/sendVoice.cs +++ b/src/library/Telegram.BotAPI/Available Methods/sendVoice.cs @@ -1,11 +1,10 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; using System.Threading.Tasks; using Telegram.BotAPI.AvailableTypes; - namespace Telegram.BotAPI.AvailableMethods; public static partial class AvailableMethodsExtensions @@ -16,19 +15,19 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message Object. - public static Message SendVoice(this BotClient? bot, SendVoiceArgs args) + public static Message SendVoice(this ITelegramBotClient bot, SendVoiceArgs args) { - if (bot == default) + if (bot is null) { throw new ArgumentNullException(nameof(bot)); } - if (args == default) + if (args is null) { throw new ArgumentNullException(nameof(args)); } - return bot.RPCF(MethodNames.SendVoice, args); + return bot.CallMethod(MethodNames.SendVoice, args); } /// Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. @@ -38,27 +37,27 @@ public static Message SendVoice(this BotClient? bot, SendVoiceArgs args) /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// Message Object. - public static async Task SendVoiceAsync(this BotClient? bot, SendVoiceArgs args, [Optional] CancellationToken cancellationToken) + public static async Task SendVoiceAsync(this ITelegramBotClient bot, SendVoiceArgs args, CancellationToken cancellationToken = default) { - if (bot == default) + if (bot is null) { throw new ArgumentNullException(nameof(bot)); } - if (args == default) + if (args is null) { throw new ArgumentNullException(nameof(args)); } - return await bot.RPCAF(MethodNames.SendVoice, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SendVoice, args, cancellationToken: cancellationToken).ConfigureAwait(false); } /// /// Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Voice message caption, 0-1024 characters after entities parsing. /// Mode for parsing entities in the voice message caption. See formatting options for more details. @@ -66,14 +65,14 @@ public static async Task SendVoiceAsync(this BotClient? bot, SendVoiceA /// Duration of the voice message in seconds. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendVoice(this BotClient? api, long chatId, InputFile voice, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] uint? duration, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendVoice(this ITelegramBotClient client, long chatId, InputFile voice, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, uint? duration = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVoiceArgs(chatId, voice) { MessageThreadId = messageThreadId, @@ -83,19 +82,18 @@ public static Message SendVoice(this BotClient? api, long chatId, InputFile voic Duration = duration, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPCF(MethodNames.SendVoice, args); + return client.CallMethod(MethodNames.SendVoice, args); } /// /// Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Voice message caption, 0-1024 characters after entities parsing. /// Mode for parsing entities in the voice message caption. See formatting options for more details. @@ -103,14 +101,14 @@ public static Message SendVoice(this BotClient? api, long chatId, InputFile voic /// Duration of the voice message in seconds. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendVoice(this BotClient? api, long chatId, string voice, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] uint? duration, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendVoice(this ITelegramBotClient client, long chatId, string voice, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, uint? duration = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVoiceArgs(chatId, voice) { MessageThreadId = messageThreadId, @@ -120,19 +118,18 @@ public static Message SendVoice(this BotClient? api, long chatId, string voice, Duration = duration, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPCF(MethodNames.SendVoice, args); + return client.CallMethod(MethodNames.SendVoice, args); } /// /// Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Voice message caption, 0-1024 characters after entities parsing. /// Mode for parsing entities in the voice message caption. See formatting options for more details. @@ -140,14 +137,14 @@ public static Message SendVoice(this BotClient? api, long chatId, string voice, /// Duration of the voice message in seconds. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendVoice(this BotClient? api, string chatId, InputFile voice, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] uint? duration, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendVoice(this ITelegramBotClient client, string chatId, InputFile voice, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, uint? duration = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVoiceArgs(chatId, voice) { MessageThreadId = messageThreadId, @@ -157,19 +154,18 @@ public static Message SendVoice(this BotClient? api, string chatId, InputFile vo Duration = duration, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPCF(MethodNames.SendVoice, args); + return client.CallMethod(MethodNames.SendVoice, args); } /// /// Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Voice message caption, 0-1024 characters after entities parsing. /// Mode for parsing entities in the voice message caption. See formatting options for more details. @@ -177,14 +173,14 @@ public static Message SendVoice(this BotClient? api, string chatId, InputFile vo /// Duration of the voice message in seconds. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendVoice(this BotClient? api, string chatId, string voice, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] uint? duration, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendVoice(this ITelegramBotClient client, string chatId, string voice, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, uint? duration = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVoiceArgs(chatId, voice) { MessageThreadId = messageThreadId, @@ -194,19 +190,18 @@ public static Message SendVoice(this BotClient? api, string chatId, string voice Duration = duration, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPCF(MethodNames.SendVoice, args); + return client.CallMethod(MethodNames.SendVoice, args); } /// /// Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Voice message caption, 0-1024 characters after entities parsing. /// Mode for parsing entities in the voice message caption. See formatting options for more details. @@ -214,15 +209,15 @@ public static Message SendVoice(this BotClient? api, string chatId, string voice /// Duration of the voice message in seconds. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendVoiceAsync(this BotClient? api, long chatId, InputFile voice, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] uint? duration, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendVoiceAsync(this ITelegramBotClient client, long chatId, InputFile voice, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, uint? duration = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVoiceArgs(chatId, voice) { MessageThreadId = messageThreadId, @@ -232,19 +227,18 @@ public static async Task SendVoiceAsync(this BotClient? api, long chatI Duration = duration, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCAF(MethodNames.SendVoice, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendVoice, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Voice message caption, 0-1024 characters after entities parsing. /// Mode for parsing entities in the voice message caption. See formatting options for more details. @@ -252,15 +246,15 @@ public static async Task SendVoiceAsync(this BotClient? api, long chatI /// Duration of the voice message in seconds. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendVoiceAsync(this BotClient? api, long chatId, string voice, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] uint? duration, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendVoiceAsync(this ITelegramBotClient client, long chatId, string voice, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, uint? duration = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVoiceArgs(chatId, voice) { MessageThreadId = messageThreadId, @@ -270,19 +264,18 @@ public static async Task SendVoiceAsync(this BotClient? api, long chatI Duration = duration, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCAF(MethodNames.SendVoice, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendVoice, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Voice message caption, 0-1024 characters after entities parsing. /// Mode for parsing entities in the voice message caption. See formatting options for more details. @@ -290,15 +283,15 @@ public static async Task SendVoiceAsync(this BotClient? api, long chatI /// Duration of the voice message in seconds. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendVoiceAsync(this BotClient? api, string chatId, InputFile voice, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] uint? duration, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendVoiceAsync(this ITelegramBotClient client, string chatId, InputFile voice, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, uint? duration = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVoiceArgs(chatId, voice) { MessageThreadId = messageThreadId, @@ -308,19 +301,18 @@ public static async Task SendVoiceAsync(this BotClient? api, string cha Duration = duration, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCAF(MethodNames.SendVoice, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendVoice, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Voice message caption, 0-1024 characters after entities parsing. /// Mode for parsing entities in the voice message caption. See formatting options for more details. @@ -328,15 +320,15 @@ public static async Task SendVoiceAsync(this BotClient? api, string cha /// Duration of the voice message in seconds. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendVoiceAsync(this BotClient? api, string chatId, string voice, [Optional] int? messageThreadId, [Optional] string? caption, [Optional] string? parseMode, [Optional] IEnumerable? captionEntities, [Optional] uint? duration, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendVoiceAsync(this ITelegramBotClient client, string chatId, string voice, int? messageThreadId = null, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, uint? duration = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendVoiceArgs(chatId, voice) { MessageThreadId = messageThreadId, @@ -346,10 +338,9 @@ public static async Task SendVoiceAsync(this BotClient? api, string cha Duration = duration, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCAF(MethodNames.SendVoice, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendVoice, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/setChatAdministratorCustomTitle.cs b/src/library/Telegram.BotAPI/Available Methods/setChatAdministratorCustomTitle.cs similarity index 88% rename from src/Telegram.BotAPI/Available Methods/setChatAdministratorCustomTitle.cs rename to src/library/Telegram.BotAPI/Available Methods/setChatAdministratorCustomTitle.cs index 5b0e4ccf..6cf21e36 100644 --- a/src/Telegram.BotAPI/Available Methods/setChatAdministratorCustomTitle.cs +++ b/src/library/Telegram.BotAPI/Available Methods/setChatAdministratorCustomTitle.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -19,7 +19,7 @@ public static partial class AvailableMethodsExtensions /// Thrown when a required parameter is null. /// True public static bool SetChatAdministratorCustomTitle( - this BotClient? bot, + this ITelegramBotClient bot, long chatId, long userId, string customTitle) @@ -38,7 +38,7 @@ public static bool SetChatAdministratorCustomTitle( json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.SetChatAdministratorCustomTitle, stream); + return bot.CallMethod(MethodNames.SetChatAdministratorCustomTitle, stream); } /// Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns True on success. @@ -50,7 +50,7 @@ public static bool SetChatAdministratorCustomTitle( /// Thrown when a required parameter is null. /// True public static bool SetChatAdministratorCustomTitle( - this BotClient? bot, + this ITelegramBotClient bot, string chatId, long userId, string customTitle) @@ -69,7 +69,7 @@ public static bool SetChatAdministratorCustomTitle( json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.SetChatAdministratorCustomTitle, stream); + return bot.CallMethod(MethodNames.SetChatAdministratorCustomTitle, stream); } /// Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns True on success. /// Bot Client @@ -80,7 +80,7 @@ public static bool SetChatAdministratorCustomTitle( /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static async Task SetChatAdministratorCustomTitleAsync(this BotClient? bot, long chatId, long userId, string customTitle, [Optional] CancellationToken cancellationToken) + public static async Task SetChatAdministratorCustomTitleAsync(this ITelegramBotClient bot, long chatId, long userId, string customTitle, CancellationToken cancellationToken = default) { if (bot == default) { @@ -97,7 +97,7 @@ public static async Task SetChatAdministratorCustomTitleAsync(this BotClie await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.SetChatAdministratorCustomTitle, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetChatAdministratorCustomTitle, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns True on success. @@ -109,7 +109,7 @@ public static async Task SetChatAdministratorCustomTitleAsync(this BotClie /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static async Task SetChatAdministratorCustomTitleAsync(this BotClient? bot, string chatId, long userId, string customTitle, [Optional] CancellationToken cancellationToken) + public static async Task SetChatAdministratorCustomTitleAsync(this ITelegramBotClient bot, string chatId, long userId, string customTitle, CancellationToken cancellationToken = default) { if (bot == default) { @@ -126,6 +126,6 @@ public static async Task SetChatAdministratorCustomTitleAsync(this BotClie await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.SetChatAdministratorCustomTitle, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetChatAdministratorCustomTitle, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/setChatDescription.cs b/src/library/Telegram.BotAPI/Available Methods/setChatDescription.cs similarity index 84% rename from src/Telegram.BotAPI/Available Methods/setChatDescription.cs rename to src/library/Telegram.BotAPI/Available Methods/setChatDescription.cs index 3c98e3b0..5b2d3b89 100644 --- a/src/Telegram.BotAPI/Available Methods/setChatDescription.cs +++ b/src/library/Telegram.BotAPI/Available Methods/setChatDescription.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -16,7 +16,7 @@ public static partial class AvailableMethodsExtensions /// New chat description, 0-255 characters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool SetChatDescription(this BotClient? bot, long chatId, string description) + public static bool SetChatDescription(this ITelegramBotClient bot, long chatId, string description) { if (bot == default) { @@ -31,7 +31,7 @@ public static bool SetChatDescription(this BotClient? bot, long chatId, string d json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.SetChatDescription, stream); + return bot.CallMethod(MethodNames.SetChatDescription, stream); } /// Use this method to change the description of a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. /// BotClient @@ -39,7 +39,7 @@ public static bool SetChatDescription(this BotClient? bot, long chatId, string d /// New chat description, 0-255 characters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool SetChatDescription(this BotClient? bot, string chatId, string description) + public static bool SetChatDescription(this ITelegramBotClient bot, string chatId, string description) { if (bot == default) { @@ -54,7 +54,7 @@ public static bool SetChatDescription(this BotClient? bot, string chatId, string json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.SetChatDescription, stream); + return bot.CallMethod(MethodNames.SetChatDescription, stream); } /// Use this method to change the description of a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. /// BotClient @@ -63,7 +63,7 @@ public static bool SetChatDescription(this BotClient? bot, string chatId, string /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SetChatDescriptionAsync(this BotClient? bot, long chatId, string description, [Optional] CancellationToken cancellationToken) + public static async Task SetChatDescriptionAsync(this ITelegramBotClient bot, long chatId, string description, CancellationToken cancellationToken = default) { if (bot == default) { @@ -79,7 +79,7 @@ public static async Task SetChatDescriptionAsync(this BotClient? bot, long await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.SetChatDescription, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetChatDescription, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to change the description of a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. /// BotClient @@ -88,7 +88,7 @@ public static async Task SetChatDescriptionAsync(this BotClient? bot, long /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SetChatDescriptionAsync(this BotClient? bot, string chatId, string description, [Optional] CancellationToken cancellationToken) + public static async Task SetChatDescriptionAsync(this ITelegramBotClient bot, string chatId, string description, CancellationToken cancellationToken = default) { if (bot == default) { @@ -104,6 +104,6 @@ public static async Task SetChatDescriptionAsync(this BotClient? bot, stri await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.SetChatDescription, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetChatDescription, stream, cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Telegram.BotAPI/Available Methods/setChatMenuButton.cs b/src/library/Telegram.BotAPI/Available Methods/setChatMenuButton.cs similarity index 79% rename from src/Telegram.BotAPI/Available Methods/setChatMenuButton.cs rename to src/library/Telegram.BotAPI/Available Methods/setChatMenuButton.cs index 831bff98..242f127b 100644 --- a/src/Telegram.BotAPI/Available Methods/setChatMenuButton.cs +++ b/src/library/Telegram.BotAPI/Available Methods/setChatMenuButton.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -16,7 +16,7 @@ public static partial class AvailableMethodsExtensions /// A JSON-serialized object for the new bot's menu button. Defaults to MenuButtonDefault. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool SetChatMenuButton(this BotClient? api, [Optional] long? chatId, [Optional] MenuButton? menuButton) + public static bool SetChatMenuButton(this ITelegramBotClient api, [Optional] long? chatId, [Optional] MenuButton? menuButton) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new SetChatMenuButtonArgs() @@ -24,7 +24,7 @@ public static bool SetChatMenuButton(this BotClient? api, [Optional] long? chatI ChatId = chatId, MenuButton = menuButton }; - return api.RPC(MethodNames.SetChatMenuButton, args); + return api.CallMethod(MethodNames.SetChatMenuButton, args); } /// Use this method to change the bot's menu button in a private chat, or the default menu button. Returns True on success. @@ -34,7 +34,7 @@ public static bool SetChatMenuButton(this BotClient? api, [Optional] long? chatI /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SetChatMenuButtonAsync(this BotClient? api, [Optional] long? chatId, [Optional] MenuButton? menuButton, [Optional] CancellationToken cancellationToken) + public static async Task SetChatMenuButtonAsync(this ITelegramBotClient api, [Optional] long? chatId, [Optional] MenuButton? menuButton, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new SetChatMenuButtonArgs() @@ -42,6 +42,6 @@ public static async Task SetChatMenuButtonAsync(this BotClient? api, [Opti ChatId = chatId, MenuButton = menuButton }; - return await api.RPCA(MethodNames.SetChatMenuButton, args, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.SetChatMenuButton, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/setChatPermissions.cs b/src/library/Telegram.BotAPI/Available Methods/setChatPermissions.cs similarity index 83% rename from src/Telegram.BotAPI/Available Methods/setChatPermissions.cs rename to src/library/Telegram.BotAPI/Available Methods/setChatPermissions.cs index fce969c5..5be6429d 100644 --- a/src/Telegram.BotAPI/Available Methods/setChatPermissions.cs +++ b/src/library/Telegram.BotAPI/Available Methods/setChatPermissions.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -18,14 +18,14 @@ public static partial class AvailableMethodsExtensions /// Pass True if chat permissions are set independently. Otherwise, the can_send_other_messages and can_add_web_page_previews permissions will imply the can_send_messages, can_send_audios, can_send_documents, can_send_photos, can_send_videos, can_send_video_notes, and can_send_voice_notes permissions; the can_send_polls permission will imply the can_send_messages permission. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool SetChatPermissions(this BotClient api, long chatId, ChatPermissions permissions, [Optional] bool? useIndependentChatPermissions) + public static bool SetChatPermissions(this ITelegramBotClient api, long chatId, ChatPermissions permissions, [Optional] bool? useIndependentChatPermissions) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new SetChatPermissionsArgs(chatId, permissions) { UseIndependentChatPermissions = useIndependentChatPermissions }; - return api.RPC(MethodNames.SetChatPermissions, args); + return api.CallMethod(MethodNames.SetChatPermissions, args); } /// @@ -37,14 +37,14 @@ public static bool SetChatPermissions(this BotClient api, long chatId, ChatPermi /// Pass True if chat permissions are set independently. Otherwise, the can_send_other_messages and can_add_web_page_previews permissions will imply the can_send_messages, can_send_audios, can_send_documents, can_send_photos, can_send_videos, can_send_video_notes, and can_send_voice_notes permissions; the can_send_polls permission will imply the can_send_messages permission. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool SetChatPermissions(this BotClient api, string chatId, ChatPermissions permissions, [Optional] bool? useIndependentChatPermissions) + public static bool SetChatPermissions(this ITelegramBotClient api, string chatId, ChatPermissions permissions, [Optional] bool? useIndependentChatPermissions) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new SetChatPermissionsArgs(chatId, permissions) { UseIndependentChatPermissions = useIndependentChatPermissions }; - return api.RPC(MethodNames.SetChatPermissions, args); + return api.CallMethod(MethodNames.SetChatPermissions, args); } /// @@ -57,14 +57,14 @@ public static bool SetChatPermissions(this BotClient api, string chatId, ChatPer /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SetChatPermissionsAsync(this BotClient api, long chatId, ChatPermissions permissions, [Optional] bool? useIndependentChatPermissions, [Optional] CancellationToken cancellationToken) + public static async Task SetChatPermissionsAsync(this ITelegramBotClient api, long chatId, ChatPermissions permissions, [Optional] bool? useIndependentChatPermissions, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new SetChatPermissionsArgs(chatId, permissions) { UseIndependentChatPermissions = useIndependentChatPermissions }; - return await api.RPCA(MethodNames.SetChatPermissions, args, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.SetChatPermissions, args, cancellationToken).ConfigureAwait(false); } /// @@ -77,13 +77,13 @@ public static async Task SetChatPermissionsAsync(this BotClient api, long /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SetChatPermissionsAsync(this BotClient api, string chatId, ChatPermissions permissions, [Optional] bool? useIndependentChatPermissions, [Optional] CancellationToken cancellationToken) + public static async Task SetChatPermissionsAsync(this ITelegramBotClient api, string chatId, ChatPermissions permissions, [Optional] bool? useIndependentChatPermissions, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new SetChatPermissionsArgs(chatId, permissions) { UseIndependentChatPermissions = useIndependentChatPermissions }; - return await api.RPCA(MethodNames.SetChatPermissions, args, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.SetChatPermissions, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/setChatPhoto.cs b/src/library/Telegram.BotAPI/Available Methods/setChatPhoto.cs similarity index 78% rename from src/Telegram.BotAPI/Available Methods/setChatPhoto.cs rename to src/library/Telegram.BotAPI/Available Methods/setChatPhoto.cs index 89792df0..b5865be7 100644 --- a/src/Telegram.BotAPI/Available Methods/setChatPhoto.cs +++ b/src/library/Telegram.BotAPI/Available Methods/setChatPhoto.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -16,14 +16,14 @@ public static partial class AvailableMethodsExtensions /// New chat photo, uploaded using multipart/form-data. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool SetChatPhoto(this BotClient? bot, long chatId, InputFile photo) + public static bool SetChatPhoto(this ITelegramBotClient bot, long chatId, InputFile photo) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } - return bot.RPCF(MethodNames.SetChatPhoto, new SetChatPhotoArgs(chatId, photo)); + return bot.CallMethod(MethodNames.SetChatPhoto, new SetChatPhotoArgs(chatId, photo)); } /// Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. @@ -32,14 +32,14 @@ public static bool SetChatPhoto(this BotClient? bot, long chatId, InputFile phot /// New chat photo, uploaded using multipart/form-data. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool SetChatPhoto(this BotClient? bot, string chatId, InputFile photo) + public static bool SetChatPhoto(this ITelegramBotClient bot, string chatId, InputFile photo) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } - return bot.RPCF(MethodNames.SetChatPhoto, new SetChatPhotoArgs(chatId, photo)); + return bot.CallMethod(MethodNames.SetChatPhoto, new SetChatPhotoArgs(chatId, photo)); } /// Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. @@ -47,7 +47,7 @@ public static bool SetChatPhoto(this BotClient? bot, string chatId, InputFile ph /// Parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool SetChatPhoto(this BotClient? bot, SetChatPhotoArgs args) + public static bool SetChatPhoto(this ITelegramBotClient bot, SetChatPhotoArgs args) { if (bot == default) { @@ -59,7 +59,7 @@ public static bool SetChatPhoto(this BotClient? bot, SetChatPhotoArgs args) throw new ArgumentNullException(nameof(args)); } - return bot.RPCF(MethodNames.SetChatPhoto, args); + return bot.CallMethod(MethodNames.SetChatPhoto, args); } /// Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. /// BotClient @@ -68,14 +68,14 @@ public static bool SetChatPhoto(this BotClient? bot, SetChatPhotoArgs args) /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SetChatPhotoAsync(this BotClient? bot, long chatId, InputFile photo, [Optional] CancellationToken cancellationToken) + public static async Task SetChatPhotoAsync(this ITelegramBotClient bot, long chatId, InputFile photo, CancellationToken cancellationToken = default) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } - return await bot.RPCAF(MethodNames.SetChatPhoto, new SetChatPhotoArgs(chatId, photo), cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetChatPhoto, new SetChatPhotoArgs(chatId, photo), cancellationToken: cancellationToken).ConfigureAwait(false); } /// Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. @@ -85,14 +85,14 @@ public static async Task SetChatPhotoAsync(this BotClient? bot, long chatI /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SetChatPhotoAsync(this BotClient? bot, string chatId, InputFile photo, [Optional] CancellationToken cancellationToken) + public static async Task SetChatPhotoAsync(this ITelegramBotClient bot, string chatId, InputFile photo, CancellationToken cancellationToken = default) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } - return await bot.RPCAF(MethodNames.SetChatPhoto, new SetChatPhotoArgs(chatId, photo), cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetChatPhoto, new SetChatPhotoArgs(chatId, photo), cancellationToken: cancellationToken).ConfigureAwait(false); } /// Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. @@ -101,7 +101,7 @@ public static async Task SetChatPhotoAsync(this BotClient? bot, string cha /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SetChatPhotoAsync(this BotClient? bot, SetChatPhotoArgs args, [Optional] CancellationToken cancellationToken) + public static async Task SetChatPhotoAsync(this ITelegramBotClient bot, SetChatPhotoArgs args, CancellationToken cancellationToken = default) { if (bot == default) { @@ -113,6 +113,6 @@ public static async Task SetChatPhotoAsync(this BotClient? bot, SetChatPho throw new ArgumentNullException(nameof(args)); } - return await bot.RPCAF(MethodNames.SetChatPhoto, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetChatPhoto, args, cancellationToken: cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/setChatStickerSet.cs b/src/library/Telegram.BotAPI/Available Methods/setChatStickerSet.cs similarity index 85% rename from src/Telegram.BotAPI/Available Methods/setChatStickerSet.cs rename to src/library/Telegram.BotAPI/Available Methods/setChatStickerSet.cs index 250d71f1..e6a8aa99 100644 --- a/src/Telegram.BotAPI/Available Methods/setChatStickerSet.cs +++ b/src/library/Telegram.BotAPI/Available Methods/setChatStickerSet.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -16,7 +16,7 @@ public static partial class AvailableMethodsExtensions /// Name of the sticker set to be set as the group sticker set. /// /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool SetChatStickerSet(this BotClient? bot, long chatId, string stickerSetName) + public static bool SetChatStickerSet(this ITelegramBotClient bot, long chatId, string stickerSetName) { if (bot == default) { @@ -31,7 +31,7 @@ public static bool SetChatStickerSet(this BotClient? bot, long chatId, string st json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.SetChatStickerSet, stream); + return bot.CallMethod(MethodNames.SetChatStickerSet, stream); } /// Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success. /// BotClient @@ -39,7 +39,7 @@ public static bool SetChatStickerSet(this BotClient? bot, long chatId, string st /// Name of the sticker set to be set as the group sticker set. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool SetChatStickerSet(this BotClient? bot, string chatId, string stickerSetName) + public static bool SetChatStickerSet(this ITelegramBotClient bot, string chatId, string stickerSetName) { if (bot == default) { @@ -54,7 +54,7 @@ public static bool SetChatStickerSet(this BotClient? bot, string chatId, string json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.SetChatStickerSet, stream); + return bot.CallMethod(MethodNames.SetChatStickerSet, stream); } /// Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success. /// BotClient @@ -63,7 +63,7 @@ public static bool SetChatStickerSet(this BotClient? bot, string chatId, string /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SetChatStickerSetAsync(this BotClient? bot, long chatId, string stickerSetName, [Optional] CancellationToken cancellationToken) + public static async Task SetChatStickerSetAsync(this ITelegramBotClient bot, long chatId, string stickerSetName, CancellationToken cancellationToken = default) { if (bot == default) { @@ -79,7 +79,7 @@ public static async Task SetChatStickerSetAsync(this BotClient? bot, long await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.SetChatStickerSet, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetChatStickerSet, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success. /// BotClient @@ -88,7 +88,7 @@ public static async Task SetChatStickerSetAsync(this BotClient? bot, long /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SetChatStickerSetAsync(this BotClient? bot, string chatId, string stickerSetName, [Optional] CancellationToken cancellationToken) + public static async Task SetChatStickerSetAsync(this ITelegramBotClient bot, string chatId, string stickerSetName, CancellationToken cancellationToken = default) { if (bot == default) { @@ -104,6 +104,6 @@ public static async Task SetChatStickerSetAsync(this BotClient? bot, strin await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.SetChatStickerSet, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetChatStickerSet, stream, cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Telegram.BotAPI/Available Methods/setChatTitle.cs b/src/library/Telegram.BotAPI/Available Methods/setChatTitle.cs similarity index 85% rename from src/Telegram.BotAPI/Available Methods/setChatTitle.cs rename to src/library/Telegram.BotAPI/Available Methods/setChatTitle.cs index 783db062..98fa4726 100644 --- a/src/Telegram.BotAPI/Available Methods/setChatTitle.cs +++ b/src/library/Telegram.BotAPI/Available Methods/setChatTitle.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -16,7 +16,7 @@ public static partial class AvailableMethodsExtensions /// New chat title, 1-255 characters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool SetChatTitle(this BotClient? bot, long chatId, string title) + public static bool SetChatTitle(this ITelegramBotClient bot, long chatId, string title) { if (bot == default) { @@ -31,7 +31,7 @@ public static bool SetChatTitle(this BotClient? bot, long chatId, string title) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.SetChatTitle, stream); + return bot.CallMethod(MethodNames.SetChatTitle, stream); } /// Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. /// BotClient @@ -39,7 +39,7 @@ public static bool SetChatTitle(this BotClient? bot, long chatId, string title) /// New chat title, 1-255 characters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool SetChatTitle(this BotClient? bot, string chatId, string title) + public static bool SetChatTitle(this ITelegramBotClient bot, string chatId, string title) { if (bot == default) { @@ -54,7 +54,7 @@ public static bool SetChatTitle(this BotClient? bot, string chatId, string title json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.SetChatTitle, stream); + return bot.CallMethod(MethodNames.SetChatTitle, stream); } /// Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. /// BotClient @@ -63,7 +63,7 @@ public static bool SetChatTitle(this BotClient? bot, string chatId, string title /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SetChatTitleAsync(this BotClient? bot, long chatId, string title, [Optional] CancellationToken cancellationToken) + public static async Task SetChatTitleAsync(this ITelegramBotClient bot, long chatId, string title, CancellationToken cancellationToken = default) { if (bot == default) { @@ -79,7 +79,7 @@ public static async Task SetChatTitleAsync(this BotClient? bot, long chatI await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.SetChatTitle, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetChatTitle, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. /// BotClient @@ -88,7 +88,7 @@ public static async Task SetChatTitleAsync(this BotClient? bot, long chatI /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SetChatTitleAsync(this BotClient? bot, string chatId, string title, [Optional] CancellationToken cancellationToken) + public static async Task SetChatTitleAsync(this ITelegramBotClient bot, string chatId, string title, CancellationToken cancellationToken = default) { if (bot == default) { @@ -104,6 +104,6 @@ public static async Task SetChatTitleAsync(this BotClient? bot, string cha await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.SetChatTitle, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetChatTitle, stream, cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/library/Telegram.BotAPI/Available Methods/setMessageReaction.cs b/src/library/Telegram.BotAPI/Available Methods/setMessageReaction.cs new file mode 100644 index 00000000..e3fe4456 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Methods/setMessageReaction.cs @@ -0,0 +1,102 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System.Threading; +using System.Threading.Tasks; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.AvailableMethods; + +/// Available Methods +public static partial class AvailableMethodsExtensions +{ + /// + /// Use this method to change the chosen reactions on a message. Service messages can't be reacted to. Automatically forwarded messages from a channel to its discussion group have the same available reactions as messages in the channel. In albums, bots must react to the first message. Returns True on success. + /// + /// The bot client. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Identifier of the target message. + /// New list of reaction types to set on the message. Currently, as non-premium users, bots can set up to one reaction per message. A custom emoji reaction can be used if it is either already present on the message or explicitly allowed by chat administrators. + /// Pass True to set the reaction with a big animation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static bool SetMessageReaction(this ITelegramBotClient client, long chatId, int messageId, IEnumerable? reaction = null, bool? isBig = null) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new SetMessageReactionArgs(chatId, messageId) + { + Reaction = reaction, + IsBig = isBig + }; + return client.CallMethod(MethodNames.SetMessageReaction, args); + } + + /// + /// Use this method to change the chosen reactions on a message. Service messages can't be reacted to. Automatically forwarded messages from a channel to its discussion group have the same available reactions as messages in the channel. In albums, bots must react to the first message. Returns True on success. + /// + /// The bot client. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Identifier of the target message. + /// New list of reaction types to set on the message. Currently, as non-premium users, bots can set up to one reaction per message. A custom emoji reaction can be used if it is either already present on the message or explicitly allowed by chat administrators. + /// Pass True to set the reaction with a big animation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static bool SetMessageReaction(this ITelegramBotClient client, string chatId, int messageId, IEnumerable? reaction = null, bool? isBig = null) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new SetMessageReactionArgs(chatId, messageId) + { + Reaction = reaction, + IsBig = isBig + }; + return client.CallMethod(MethodNames.SetMessageReaction, args); + } + + /// + /// Use this method to change the chosen reactions on a message. Service messages can't be reacted to. Automatically forwarded messages from a channel to its discussion group have the same available reactions as messages in the channel. In albums, bots must react to the first message. Returns True on success. + /// + /// The bot client. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Identifier of the target message. + /// New list of reaction types to set on the message. Currently, as non-premium users, bots can set up to one reaction per message. A custom emoji reaction can be used if it is either already present on the message or explicitly allowed by chat administrators. + /// Pass True to set the reaction with a big animation. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static async Task SetMessageReactionAsync(this ITelegramBotClient client, long chatId, int messageId, IEnumerable? reaction = null, bool? isBig = null, CancellationToken cancellationToken = default) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new SetMessageReactionArgs(chatId, messageId) + { + Reaction = reaction, + IsBig = isBig + }; + return await client.CallMethodAsync(MethodNames.SetMessageReaction, args, cancellationToken).ConfigureAwait(false); + } + + /// + /// Use this method to change the chosen reactions on a message. Service messages can't be reacted to. Automatically forwarded messages from a channel to its discussion group have the same available reactions as messages in the channel. In albums, bots must react to the first message. Returns True on success. + /// + /// The bot client. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Identifier of the target message. + /// New list of reaction types to set on the message. Currently, as non-premium users, bots can set up to one reaction per message. A custom emoji reaction can be used if it is either already present on the message or explicitly allowed by chat administrators. + /// Pass True to set the reaction with a big animation. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static async Task SetMessageReactionAsync(this ITelegramBotClient client, string chatId, int messageId, IEnumerable? reaction = null, bool? isBig = null, CancellationToken cancellationToken = default) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new SetMessageReactionArgs(chatId, messageId) + { + Reaction = reaction, + IsBig = isBig + }; + return await client.CallMethodAsync(MethodNames.SetMessageReaction, args, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Telegram.BotAPI/Available Methods/setMyCommands.cs b/src/library/Telegram.BotAPI/Available Methods/setMyCommands.cs similarity index 82% rename from src/Telegram.BotAPI/Available Methods/setMyCommands.cs rename to src/library/Telegram.BotAPI/Available Methods/setMyCommands.cs index 5c08f614..0a9eb962 100644 --- a/src/Telegram.BotAPI/Available Methods/setMyCommands.cs +++ b/src/library/Telegram.BotAPI/Available Methods/setMyCommands.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -17,7 +17,7 @@ public static partial class AvailableMethodsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static bool SetMyCommands(this BotClient? bot, params BotCommand[] commands) + public static bool SetMyCommands(this ITelegramBotClient bot, params BotCommand[] commands) { if (bot == null) { @@ -48,7 +48,7 @@ public static bool SetMyCommands(this BotClient? bot, params BotCommand[] comman json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.SetMyCommands, stream); + return bot.CallMethod(MethodNames.SetMyCommands, stream); } /// Use this method to change the list of the bot's commands. See https://core.telegram.org/bots#commands for more details about bot commands. Returns True on success. /// BotClient @@ -58,7 +58,7 @@ public static bool SetMyCommands(this BotClient? bot, params BotCommand[] comman /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static bool SetMyCommands(this BotClient? bot, IEnumerable commands, [Optional] BotCommandScope scope, [Optional] string languageCode) + public static bool SetMyCommands(this ITelegramBotClient bot, IEnumerable commands, [Optional] BotCommandScope scope, [Optional] string languageCode) { if (bot == null) { @@ -70,7 +70,7 @@ public static bool SetMyCommands(this BotClient? bot, IEnumerable co } var args = new SetMyCommandsArgs(commands, scope, languageCode); - return bot.RPC(MethodNames.SetMyCommands, args); + return bot.CallMethod(MethodNames.SetMyCommands, args); } /// Use this method to change the list of the bot's commands. See https://core.telegram.org/bots#commands for more details about bot commands. Returns True on success. @@ -79,13 +79,13 @@ public static bool SetMyCommands(this BotClient? bot, IEnumerable co /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static bool SetMyCommands(this BotClient? bot, SetMyCommandsArgs args) + public static bool SetMyCommands(this ITelegramBotClient bot, SetMyCommandsArgs args) { if (bot == null) { throw new ArgumentNullException(nameof(bot)); } - return bot.RPC(MethodNames.SetMyCommands, args); + return bot.CallMethod(MethodNames.SetMyCommands, args); } /// Use this method to change the list of the bot's commands. See https://core.telegram.org/bots#commands for more details about bot commands. Returns True on success. @@ -97,7 +97,7 @@ public static bool SetMyCommands(this BotClient? bot, SetMyCommandsArgs args) /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static async Task SetMyCommandsAsync(this BotClient? bot, IEnumerable commands, [Optional] BotCommandScope scope, [Optional] string languageCode, [Optional] CancellationToken cancellationToken) + public static async Task SetMyCommandsAsync(this ITelegramBotClient bot, IEnumerable commands, [Optional] BotCommandScope scope, [Optional] string languageCode, CancellationToken cancellationToken = default) { if (bot == null) { @@ -109,7 +109,7 @@ public static async Task SetMyCommandsAsync(this BotClient? bot, IEnumerab } var args = new SetMyCommandsArgs(commands, scope, languageCode); - return await bot.RPCA(MethodNames.SetMyCommands, args, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetMyCommands, args, cancellationToken).ConfigureAwait(false); } /// Use this method to change the list of the bot's commands. See https://core.telegram.org/bots#commands for more details about bot commands. Returns True on success. @@ -119,7 +119,7 @@ public static async Task SetMyCommandsAsync(this BotClient? bot, IEnumerab /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static async Task SetMyCommandsAsync(this BotClient? bot, SetMyCommandsArgs args, [Optional] CancellationToken cancellationToken) + public static async Task SetMyCommandsAsync(this ITelegramBotClient bot, SetMyCommandsArgs args, CancellationToken cancellationToken = default) { if (bot == null) { @@ -130,6 +130,6 @@ public static async Task SetMyCommandsAsync(this BotClient? bot, SetMyComm throw new ArgumentNullException(nameof(args)); } - return await bot.RPCA(MethodNames.SetMyCommands, args, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetMyCommands, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/setMyDefaultAdministratorRights.cs b/src/library/Telegram.BotAPI/Available Methods/setMyDefaultAdministratorRights.cs similarity index 82% rename from src/Telegram.BotAPI/Available Methods/setMyDefaultAdministratorRights.cs rename to src/library/Telegram.BotAPI/Available Methods/setMyDefaultAdministratorRights.cs index 9fa91306..d9bb54d9 100644 --- a/src/Telegram.BotAPI/Available Methods/setMyDefaultAdministratorRights.cs +++ b/src/library/Telegram.BotAPI/Available Methods/setMyDefaultAdministratorRights.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -16,7 +16,7 @@ public static partial class AvailableMethodsExtensions /// Pass True to change the default administrator rights of the bot in channels. Otherwise, the default administrator rights of the bot for groups and supergroups will be changed. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool SetMyDefaultAdministratorRights(this BotClient? api, [Optional] ChatAdministratorRights? rights, [Optional] bool? forChannels) + public static bool SetMyDefaultAdministratorRights(this ITelegramBotClient api, [Optional] ChatAdministratorRights? rights, [Optional] bool? forChannels) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new SetMyDefaultAdministratorRightsArgs() @@ -24,7 +24,7 @@ public static bool SetMyDefaultAdministratorRights(this BotClient? api, [Optiona Rights = rights, ForChannels = forChannels }; - return api.RPC(MethodNames.SetMyDefaultAdministratorRights, args); + return api.CallMethod(MethodNames.SetMyDefaultAdministratorRights, args); } /// Use this method to change the default administrator rights requested by the bot when it's added as an administrator to groups or channels. These rights will be suggested to users, but they are are free to modify the list before adding the bot. Returns True on success. @@ -34,7 +34,7 @@ public static bool SetMyDefaultAdministratorRights(this BotClient? api, [Optiona /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SetMyDefaultAdministratorRightsAsync(this BotClient? api, [Optional] ChatAdministratorRights? rights, [Optional] bool? forChannels, [Optional] CancellationToken cancellationToken) + public static async Task SetMyDefaultAdministratorRightsAsync(this ITelegramBotClient api, [Optional] ChatAdministratorRights? rights, [Optional] bool? forChannels, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new SetMyDefaultAdministratorRightsArgs() @@ -42,6 +42,6 @@ public static async Task SetMyDefaultAdministratorRightsAsync(this BotClie Rights = rights, ForChannels = forChannels }; - return await api.RPCA(MethodNames.SetMyDefaultAdministratorRights, args, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.SetMyDefaultAdministratorRights, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/setMyDescription.cs b/src/library/Telegram.BotAPI/Available Methods/setMyDescription.cs similarity index 84% rename from src/Telegram.BotAPI/Available Methods/setMyDescription.cs rename to src/library/Telegram.BotAPI/Available Methods/setMyDescription.cs index d5ce900c..3c62cd78 100644 --- a/src/Telegram.BotAPI/Available Methods/setMyDescription.cs +++ b/src/library/Telegram.BotAPI/Available Methods/setMyDescription.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -18,7 +18,7 @@ public static partial class AvailableMethodsExtensions /// A two-letter ISO 639-1 language code. If empty, the description will be applied to all users for whose language there is no dedicated description. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool SetMyDescription(this BotClient? bot, [Optional] string? description, [Optional] string? languageCode) + public static bool SetMyDescription(this ITelegramBotClient bot, [Optional] string? description, [Optional] string? languageCode) { if (bot == default) { @@ -39,7 +39,7 @@ public static bool SetMyDescription(this BotClient? bot, [Optional] string? desc json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.SetMyDescription, stream); + return bot.CallMethod(MethodNames.SetMyDescription, stream); } /// @@ -51,7 +51,7 @@ public static bool SetMyDescription(this BotClient? bot, [Optional] string? desc /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SetMyDescriptionAsync(this BotClient? bot, [Optional] string? description, [Optional] string? languageCode, [Optional] CancellationToken cancellationToken) + public static async Task SetMyDescriptionAsync(this ITelegramBotClient bot, [Optional] string? description, [Optional] string? languageCode, CancellationToken cancellationToken = default) { if (bot == default) { @@ -73,6 +73,6 @@ public static async Task SetMyDescriptionAsync(this BotClient? bot, [Optio await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.SetMyDescription, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetMyDescription, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/setMyName.cs b/src/library/Telegram.BotAPI/Available Methods/setMyName.cs similarity index 78% rename from src/Telegram.BotAPI/Available Methods/setMyName.cs rename to src/library/Telegram.BotAPI/Available Methods/setMyName.cs index c75ca8b0..469a1708 100644 --- a/src/Telegram.BotAPI/Available Methods/setMyName.cs +++ b/src/library/Telegram.BotAPI/Available Methods/setMyName.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -18,7 +18,7 @@ public static partial class AvailableMethodsExtensions /// A two-letter ISO 639-1 language code. If empty, the name will be shown to all users for whose language there is no dedicated name. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool SetMyName(this BotClient api, [Optional] string? name, [Optional] string? languageCode) + public static bool SetMyName(this ITelegramBotClient api, [Optional] string? name, [Optional] string? languageCode) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -26,16 +26,16 @@ public static bool SetMyName(this BotClient api, [Optional] string? name, [Optio json.WriteStartObject(); if (name is not null) { - json.WriteString(PropertyNames.Name, (string)name); + json.WriteString(PropertyNames.Name, name); } if (languageCode is not null) { - json.WriteString(PropertyNames.LanguageCode, (string)languageCode); + json.WriteString(PropertyNames.LanguageCode, languageCode); } json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.SetMyName, stream); + return api.CallMethod(MethodNames.SetMyName, stream); } /// @@ -47,7 +47,7 @@ public static bool SetMyName(this BotClient api, [Optional] string? name, [Optio /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SetMyNameAsync(this BotClient api, [Optional] string? name, [Optional] string? languageCode, [Optional] CancellationToken cancellationToken) + public static async Task SetMyNameAsync(this ITelegramBotClient api, [Optional] string? name, [Optional] string? languageCode, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -55,16 +55,16 @@ public static async Task SetMyNameAsync(this BotClient api, [Optional] str json.WriteStartObject(); if (name is not null) { - json.WriteString(PropertyNames.Name, (string)name); + json.WriteString(PropertyNames.Name, name); } if (languageCode is not null) { - json.WriteString(PropertyNames.LanguageCode, (string)languageCode); + json.WriteString(PropertyNames.LanguageCode, languageCode); } json.WriteEndObject(); await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.SetMyName, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.SetMyName, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/setMyShortDescription.cs b/src/library/Telegram.BotAPI/Available Methods/setMyShortDescription.cs similarity index 86% rename from src/Telegram.BotAPI/Available Methods/setMyShortDescription.cs rename to src/library/Telegram.BotAPI/Available Methods/setMyShortDescription.cs index 0dc835cf..adbd3cd4 100644 --- a/src/Telegram.BotAPI/Available Methods/setMyShortDescription.cs +++ b/src/library/Telegram.BotAPI/Available Methods/setMyShortDescription.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -18,7 +18,7 @@ public static partial class AvailableMethodsExtensions /// A two-letter ISO 639-1 language code. If empty, the short description will be applied to all users for whose language there is no dedicated short description. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool SetMyShortDescription(this BotClient? bot, [Optional] string? shortDescription, [Optional] string? languageCode) + public static bool SetMyShortDescription(this ITelegramBotClient bot, [Optional] string? shortDescription, [Optional] string? languageCode) { if (bot == default) { @@ -39,7 +39,7 @@ public static bool SetMyShortDescription(this BotClient? bot, [Optional] string? json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.SetMyShortDescription, stream); + return bot.CallMethod(MethodNames.SetMyShortDescription, stream); } /// @@ -51,7 +51,7 @@ public static bool SetMyShortDescription(this BotClient? bot, [Optional] string? /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SetMyShortDescriptionAsync(this BotClient? bot, [Optional] string? shortDescription, [Optional] string? languageCode, [Optional] CancellationToken cancellationToken) + public static async Task SetMyShortDescriptionAsync(this ITelegramBotClient bot, [Optional] string? shortDescription, [Optional] string? languageCode, CancellationToken cancellationToken = default) { if (bot == default) { @@ -73,6 +73,6 @@ public static async Task SetMyShortDescriptionAsync(this BotClient? bot, [ await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.SetMyShortDescription, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetMyShortDescription, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/unbanChatMember.cs b/src/library/Telegram.BotAPI/Available Methods/unbanChatMember.cs similarity index 87% rename from src/Telegram.BotAPI/Available Methods/unbanChatMember.cs rename to src/library/Telegram.BotAPI/Available Methods/unbanChatMember.cs index 610ed7c7..338b0cc9 100644 --- a/src/Telegram.BotAPI/Available Methods/unbanChatMember.cs +++ b/src/library/Telegram.BotAPI/Available Methods/unbanChatMember.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -17,7 +17,7 @@ public static partial class AvailableMethodsExtensions /// Do nothing if the user is not banned /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool UnbanChatMember(this BotClient? bot, long chatId, long userId, [Optional] bool? onlyIfBanned) + public static bool UnbanChatMember(this ITelegramBotClient bot, long chatId, long userId, [Optional] bool? onlyIfBanned) { if (bot == default) { @@ -37,7 +37,7 @@ public static bool UnbanChatMember(this BotClient? bot, long chatId, long userId json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.UnbanChatMember, stream); + return bot.CallMethod(MethodNames.UnbanChatMember, stream); } /// Use this method to unban a previously kicked user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be removed from the chat. If you don't want this, use the parameter only_if_banned. Returns True on success. /// BotClient @@ -46,7 +46,7 @@ public static bool UnbanChatMember(this BotClient? bot, long chatId, long userId /// Do nothing if the user is not banned /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool UnbanChatMember(this BotClient? bot, string chatId, long userId, [Optional] bool? onlyIfBanned) + public static bool UnbanChatMember(this ITelegramBotClient bot, string chatId, long userId, [Optional] bool? onlyIfBanned) { if (bot == default) { @@ -66,7 +66,7 @@ public static bool UnbanChatMember(this BotClient? bot, string chatId, long user json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.UnbanChatMember, stream); + return bot.CallMethod(MethodNames.UnbanChatMember, stream); } /// Use this method to unban a previously kicked user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be removed from the chat. If you don't want this, use the parameter only_if_banned. Returns True on success. /// BotClient @@ -76,7 +76,7 @@ public static bool UnbanChatMember(this BotClient? bot, string chatId, long user /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task UnbanChatMemberAsync(this BotClient? bot, long chatId, long userId, [Optional] bool? onlyIfBanned, [Optional] CancellationToken cancellationToken) + public static async Task UnbanChatMemberAsync(this ITelegramBotClient bot, long chatId, long userId, [Optional] bool? onlyIfBanned, CancellationToken cancellationToken = default) { if (bot == default) { @@ -97,7 +97,7 @@ public static async Task UnbanChatMemberAsync(this BotClient? bot, long ch await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.UnbanChatMember, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.UnbanChatMember, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to unban a previously kicked user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be removed from the chat. If you don't want this, use the parameter only_if_banned. Returns True on success. /// BotClient @@ -107,7 +107,7 @@ public static async Task UnbanChatMemberAsync(this BotClient? bot, long ch /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task UnbanChatMemberAsync(this BotClient? bot, string chatId, long userId, [Optional] bool? onlyIfBanned, [Optional] CancellationToken cancellationToken) + public static async Task UnbanChatMemberAsync(this ITelegramBotClient bot, string chatId, long userId, [Optional] bool? onlyIfBanned, CancellationToken cancellationToken = default) { if (bot == default) { @@ -128,6 +128,6 @@ public static async Task UnbanChatMemberAsync(this BotClient? bot, string await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.UnbanChatMember, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.UnbanChatMember, stream, cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Telegram.BotAPI/Available Methods/unbanChatSenderChat.cs b/src/library/Telegram.BotAPI/Available Methods/unbanChatSenderChat.cs similarity index 84% rename from src/Telegram.BotAPI/Available Methods/unbanChatSenderChat.cs rename to src/library/Telegram.BotAPI/Available Methods/unbanChatSenderChat.cs index 42c29a26..ce75282a 100644 --- a/src/Telegram.BotAPI/Available Methods/unbanChatSenderChat.cs +++ b/src/library/Telegram.BotAPI/Available Methods/unbanChatSenderChat.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -17,7 +17,7 @@ public static partial class AvailableMethodsExtensions /// Unique identifier of the target sender chat /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool UnbanChatSenderChat(this BotClient? bot, long chatId, long senderChatId) + public static bool UnbanChatSenderChat(this ITelegramBotClient bot, long chatId, long senderChatId) { if (bot == default) { @@ -32,7 +32,7 @@ public static bool UnbanChatSenderChat(this BotClient? bot, long chatId, long se json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.UnbanChatSenderChat, stream); + return bot.CallMethod(MethodNames.UnbanChatSenderChat, stream); } /// Use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns True on success. /// BotClient @@ -40,7 +40,7 @@ public static bool UnbanChatSenderChat(this BotClient? bot, long chatId, long se /// Unique identifier of the target sender chat /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool UnbanChatSenderChat(this BotClient? bot, string chatId, long senderChatId) + public static bool UnbanChatSenderChat(this ITelegramBotClient bot, string chatId, long senderChatId) { if (bot == default) { @@ -55,7 +55,7 @@ public static bool UnbanChatSenderChat(this BotClient? bot, string chatId, long json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.UnbanChatSenderChat, stream); + return bot.CallMethod(MethodNames.UnbanChatSenderChat, stream); } /// Use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns True on success. /// BotClient @@ -64,7 +64,7 @@ public static bool UnbanChatSenderChat(this BotClient? bot, string chatId, long /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task UnbanChatSenderChatAsync(this BotClient? bot, long chatId, long senderChatId, [Optional] CancellationToken cancellationToken) + public static async Task UnbanChatSenderChatAsync(this ITelegramBotClient bot, long chatId, long senderChatId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -80,7 +80,7 @@ public static async Task UnbanChatSenderChatAsync(this BotClient? bot, lon await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.UnbanChatSenderChat, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.UnbanChatSenderChat, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns True on success. /// BotClient @@ -89,7 +89,7 @@ public static async Task UnbanChatSenderChatAsync(this BotClient? bot, lon /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task UnbanChatSenderChatAsync(this BotClient? bot, string chatId, long senderChatId, [Optional] CancellationToken cancellationToken) + public static async Task UnbanChatSenderChatAsync(this ITelegramBotClient bot, string chatId, long senderChatId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -105,6 +105,6 @@ public static async Task UnbanChatSenderChatAsync(this BotClient? bot, str await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.UnbanChatSenderChat, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.UnbanChatSenderChat, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/unhideGeneralForumTopic.cs b/src/library/Telegram.BotAPI/Available Methods/unhideGeneralForumTopic.cs similarity index 86% rename from src/Telegram.BotAPI/Available Methods/unhideGeneralForumTopic.cs rename to src/library/Telegram.BotAPI/Available Methods/unhideGeneralForumTopic.cs index 381705e1..ca6afaad 100644 --- a/src/Telegram.BotAPI/Available Methods/unhideGeneralForumTopic.cs +++ b/src/library/Telegram.BotAPI/Available Methods/unhideGeneralForumTopic.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -19,7 +19,7 @@ public static partial class AvailableMethodsExtensions /// Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername). /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool UnhideGeneralForumTopic(this BotClient? api, long chatId) + public static bool UnhideGeneralForumTopic(this ITelegramBotClient api, long chatId) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -29,7 +29,7 @@ public static bool UnhideGeneralForumTopic(this BotClient? api, long chatId) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.UnhideGeneralForumTopic, stream); + return api.CallMethod(MethodNames.UnhideGeneralForumTopic, stream); } /// @@ -39,7 +39,7 @@ public static bool UnhideGeneralForumTopic(this BotClient? api, long chatId) /// Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername). /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool UnhideGeneralForumTopic(this BotClient? api, string chatId) + public static bool UnhideGeneralForumTopic(this ITelegramBotClient api, string chatId) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -49,7 +49,7 @@ public static bool UnhideGeneralForumTopic(this BotClient? api, string chatId) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.UnhideGeneralForumTopic, stream); + return api.CallMethod(MethodNames.UnhideGeneralForumTopic, stream); } /// @@ -60,7 +60,7 @@ public static bool UnhideGeneralForumTopic(this BotClient? api, string chatId) /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task UnhideGeneralForumTopicAsync(this BotClient? api, long chatId, [Optional] CancellationToken cancellationToken) + public static async Task UnhideGeneralForumTopicAsync(this ITelegramBotClient api, long chatId, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -71,7 +71,7 @@ public static async Task UnhideGeneralForumTopicAsync(this BotClient? api, await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.UnhideGeneralForumTopic, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.UnhideGeneralForumTopic, stream, cancellationToken).ConfigureAwait(false); } /// @@ -82,7 +82,7 @@ public static async Task UnhideGeneralForumTopicAsync(this BotClient? api, /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task UnhideGeneralForumTopicAsync(this BotClient? api, string chatId, [Optional] CancellationToken cancellationToken) + public static async Task UnhideGeneralForumTopicAsync(this ITelegramBotClient api, string chatId, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -93,6 +93,6 @@ public static async Task UnhideGeneralForumTopicAsync(this BotClient? api, await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.UnhideGeneralForumTopic, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.UnhideGeneralForumTopic, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/unpinAllChatMessages.cs b/src/library/Telegram.BotAPI/Available Methods/unpinAllChatMessages.cs similarity index 84% rename from src/Telegram.BotAPI/Available Methods/unpinAllChatMessages.cs rename to src/library/Telegram.BotAPI/Available Methods/unpinAllChatMessages.cs index 97b4c851..bf918fe6 100644 --- a/src/Telegram.BotAPI/Available Methods/unpinAllChatMessages.cs +++ b/src/library/Telegram.BotAPI/Available Methods/unpinAllChatMessages.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -15,7 +15,7 @@ public static partial class AvailableMethodsExtensions /// Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername). /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool UnpinAllChatMessages(this BotClient? bot, long chatId) + public static bool UnpinAllChatMessages(this ITelegramBotClient bot, long chatId) { if (bot == default) { @@ -29,14 +29,14 @@ public static bool UnpinAllChatMessages(this BotClient? bot, long chatId) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.UnpinAllChatMessages, stream); + return bot.CallMethod(MethodNames.UnpinAllChatMessages, stream); } /// Use this method to unpin a message in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin right in the channel. Returns True on success. /// BotClient /// Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername). /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool UnpinAllChatMessages(this BotClient? bot, string chatId) + public static bool UnpinAllChatMessages(this ITelegramBotClient bot, string chatId) { if (bot == default) { @@ -50,7 +50,7 @@ public static bool UnpinAllChatMessages(this BotClient? bot, string chatId) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.UnpinAllChatMessages, stream); + return bot.CallMethod(MethodNames.UnpinAllChatMessages, stream); } /// Use this method to unpin a message in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin right in the channel. Returns True on success. /// BotClient @@ -58,7 +58,7 @@ public static bool UnpinAllChatMessages(this BotClient? bot, string chatId) /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task UnpinAllChatMessages(this BotClient? bot, long chatId, [Optional] CancellationToken cancellationToken) + public static async Task UnpinAllChatMessages(this ITelegramBotClient bot, long chatId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -72,7 +72,7 @@ public static async Task UnpinAllChatMessages(this BotClient? bot, long ch json.WriteEndObject(); await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.UnpinAllChatMessages, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.UnpinAllChatMessages, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to unpin a message in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin right in the channel. Returns True on success. /// BotClient @@ -80,7 +80,7 @@ public static async Task UnpinAllChatMessages(this BotClient? bot, long ch /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task UnpinAllChatMessages(this BotClient? bot, string chatId, [Optional] CancellationToken cancellationToken) + public static async Task UnpinAllChatMessages(this ITelegramBotClient bot, string chatId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -94,6 +94,6 @@ public static async Task UnpinAllChatMessages(this BotClient? bot, string json.WriteEndObject(); await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.UnpinAllChatMessages, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.UnpinAllChatMessages, stream, cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Telegram.BotAPI/Available Methods/unpinAllForumTopicMessages.cs b/src/library/Telegram.BotAPI/Available Methods/unpinAllForumTopicMessages.cs similarity index 86% rename from src/Telegram.BotAPI/Available Methods/unpinAllForumTopicMessages.cs rename to src/library/Telegram.BotAPI/Available Methods/unpinAllForumTopicMessages.cs index 25711847..76dbee6f 100644 --- a/src/Telegram.BotAPI/Available Methods/unpinAllForumTopicMessages.cs +++ b/src/library/Telegram.BotAPI/Available Methods/unpinAllForumTopicMessages.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -18,7 +18,7 @@ public static partial class AvailableMethodsExtensions /// Unique identifier for the target message thread of the forum topic. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool UnpinAllForumTopicMessages(this BotClient? api, long chatId, int messageThreadId) + public static bool UnpinAllForumTopicMessages(this ITelegramBotClient api, long chatId, int messageThreadId) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -29,7 +29,7 @@ public static bool UnpinAllForumTopicMessages(this BotClient? api, long chatId, json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.UnpinAllForumTopicMessages, stream); + return api.CallMethod(MethodNames.UnpinAllForumTopicMessages, stream); } /// @@ -40,7 +40,7 @@ public static bool UnpinAllForumTopicMessages(this BotClient? api, long chatId, /// Unique identifier for the target message thread of the forum topic. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool UnpinAllForumTopicMessages(this BotClient? api, string chatId, int messageThreadId) + public static bool UnpinAllForumTopicMessages(this ITelegramBotClient api, string chatId, int messageThreadId) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -51,7 +51,7 @@ public static bool UnpinAllForumTopicMessages(this BotClient? api, string chatId json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.UnpinAllForumTopicMessages, stream); + return api.CallMethod(MethodNames.UnpinAllForumTopicMessages, stream); } /// @@ -63,7 +63,7 @@ public static bool UnpinAllForumTopicMessages(this BotClient? api, string chatId /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task UnpinAllForumTopicMessagesAsync(this BotClient? api, long chatId, int messageThreadId, [Optional] CancellationToken cancellationToken) + public static async Task UnpinAllForumTopicMessagesAsync(this ITelegramBotClient api, long chatId, int messageThreadId, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -75,7 +75,7 @@ public static async Task UnpinAllForumTopicMessagesAsync(this BotClient? a await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.UnpinAllForumTopicMessages, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.UnpinAllForumTopicMessages, stream, cancellationToken).ConfigureAwait(false); } /// @@ -87,7 +87,7 @@ public static async Task UnpinAllForumTopicMessagesAsync(this BotClient? a /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task UnpinAllForumTopicMessagesAsync(this BotClient? api, string chatId, int messageThreadId, [Optional] CancellationToken cancellationToken) + public static async Task UnpinAllForumTopicMessagesAsync(this ITelegramBotClient api, string chatId, int messageThreadId, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -99,6 +99,6 @@ public static async Task UnpinAllForumTopicMessagesAsync(this BotClient? a await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.UnpinAllForumTopicMessages, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.UnpinAllForumTopicMessages, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/unpinAllGeneralForumTopicMessages.cs b/src/library/Telegram.BotAPI/Available Methods/unpinAllGeneralForumTopicMessages.cs similarity index 85% rename from src/Telegram.BotAPI/Available Methods/unpinAllGeneralForumTopicMessages.cs rename to src/library/Telegram.BotAPI/Available Methods/unpinAllGeneralForumTopicMessages.cs index 9539e892..65aed35b 100644 --- a/src/Telegram.BotAPI/Available Methods/unpinAllGeneralForumTopicMessages.cs +++ b/src/library/Telegram.BotAPI/Available Methods/unpinAllGeneralForumTopicMessages.cs @@ -1,10 +1,10 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; using System.Text.Json; -using System.Threading.Tasks; using System.Threading; +using System.Threading.Tasks; namespace Telegram.BotAPI.AvailableMethods; @@ -17,7 +17,7 @@ public static partial class AvailableMethodsExtensions /// Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername). /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool UnpinAllGeneralForumTopicMessages(this BotClient api, long chatId) + public static bool UnpinAllGeneralForumTopicMessages(this ITelegramBotClient api, long chatId) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -27,7 +27,7 @@ public static bool UnpinAllGeneralForumTopicMessages(this BotClient api, long ch json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.UnpinAllGeneralForumTopicMessages, stream); + return api.CallMethod(MethodNames.UnpinAllGeneralForumTopicMessages, stream); } /// @@ -37,7 +37,7 @@ public static bool UnpinAllGeneralForumTopicMessages(this BotClient api, long ch /// Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername). /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool UnpinAllGeneralForumTopicMessages(this BotClient api, string chatId) + public static bool UnpinAllGeneralForumTopicMessages(this ITelegramBotClient api, string chatId) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -47,7 +47,7 @@ public static bool UnpinAllGeneralForumTopicMessages(this BotClient api, string json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.UnpinAllGeneralForumTopicMessages, stream); + return api.CallMethod(MethodNames.UnpinAllGeneralForumTopicMessages, stream); } /// @@ -58,7 +58,7 @@ public static bool UnpinAllGeneralForumTopicMessages(this BotClient api, string /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task UnpinAllGeneralForumTopicMessagesAsync(this BotClient api, long chatId, [Optional] CancellationToken cancellationToken) + public static async Task UnpinAllGeneralForumTopicMessagesAsync(this ITelegramBotClient api, long chatId, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -69,7 +69,7 @@ public static async Task UnpinAllGeneralForumTopicMessagesAsync(this BotCl await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.UnpinAllGeneralForumTopicMessages, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.UnpinAllGeneralForumTopicMessages, stream, cancellationToken).ConfigureAwait(false); } /// @@ -80,7 +80,7 @@ public static async Task UnpinAllGeneralForumTopicMessagesAsync(this BotCl /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task UnpinAllGeneralForumTopicMessagesAsync(this BotClient api, string chatId, [Optional] CancellationToken cancellationToken) + public static async Task UnpinAllGeneralForumTopicMessagesAsync(this ITelegramBotClient api, string chatId, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); @@ -91,6 +91,6 @@ public static async Task UnpinAllGeneralForumTopicMessagesAsync(this BotCl await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.UnpinAllGeneralForumTopicMessages, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.UnpinAllGeneralForumTopicMessages, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Available Methods/unpinChatMessage.cs b/src/library/Telegram.BotAPI/Available Methods/unpinChatMessage.cs similarity index 85% rename from src/Telegram.BotAPI/Available Methods/unpinChatMessage.cs rename to src/library/Telegram.BotAPI/Available Methods/unpinChatMessage.cs index da4e95b3..0a5f6e35 100644 --- a/src/Telegram.BotAPI/Available Methods/unpinChatMessage.cs +++ b/src/library/Telegram.BotAPI/Available Methods/unpinChatMessage.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -16,7 +16,7 @@ public static partial class AvailableMethodsExtensions /// Identifier of a message to unpin. If not specified, the most recent pinned message (by sending date) will be unpinned. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool UnPinChatMessage(this BotClient? bot, long chatId, [Optional] int? messageId) + public static bool UnPinChatMessage(this ITelegramBotClient bot, long chatId, [Optional] int? messageId) { if (bot == default) { @@ -35,7 +35,7 @@ public static bool UnPinChatMessage(this BotClient? bot, long chatId, [Optional] json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.UnpinChatMessage, stream); + return bot.CallMethod(MethodNames.UnpinChatMessage, stream); } /// Use this method to unpin a message in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin right in the channel. Returns True on success. /// BotClient @@ -43,7 +43,7 @@ public static bool UnPinChatMessage(this BotClient? bot, long chatId, [Optional] /// Identifier of a message to unpin. If not specified, the most recent pinned message (by sending date) will be unpinned. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool UnPinChatMessage(this BotClient? bot, string chatId, [Optional] int? messageId) + public static bool UnPinChatMessage(this ITelegramBotClient bot, string chatId, [Optional] int? messageId) { if (bot == default) { @@ -62,7 +62,7 @@ public static bool UnPinChatMessage(this BotClient? bot, string chatId, [Optiona json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.UnpinChatMessage, stream); + return bot.CallMethod(MethodNames.UnpinChatMessage, stream); } /// Use this method to unpin a message in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin right in the channel. Returns True on success. /// BotClient @@ -71,7 +71,7 @@ public static bool UnPinChatMessage(this BotClient? bot, string chatId, [Optiona /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task UnPinChatMessageAsync(this BotClient? bot, long chatId, [Optional] int? messageId, [Optional] CancellationToken cancellationToken) + public static async Task UnPinChatMessageAsync(this ITelegramBotClient bot, long chatId, [Optional] int? messageId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -90,7 +90,7 @@ public static async Task UnPinChatMessageAsync(this BotClient? bot, long c json.WriteEndObject(); await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.UnpinChatMessage, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.UnpinChatMessage, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to unpin a message in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin right in the channel. Returns True on success. /// BotClient @@ -99,7 +99,7 @@ public static async Task UnPinChatMessageAsync(this BotClient? bot, long c /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task UnPinChatMessageAsync(this BotClient? bot, string chatId, [Optional] int? messageId, [Optional] CancellationToken cancellationToken) + public static async Task UnPinChatMessageAsync(this ITelegramBotClient bot, string chatId, [Optional] int? messageId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -118,6 +118,6 @@ public static async Task UnPinChatMessageAsync(this BotClient? bot, string json.WriteEndObject(); await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.UnpinChatMessage, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.UnpinChatMessage, stream, cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Telegram.BotAPI/Available Types/Animation.cs b/src/library/Telegram.BotAPI/Available Types/Animation.cs similarity index 99% rename from src/Telegram.BotAPI/Available Types/Animation.cs rename to src/library/Telegram.BotAPI/Available Types/Animation.cs index eee341a9..2e72951a 100644 --- a/src/Telegram.BotAPI/Available Types/Animation.cs +++ b/src/library/Telegram.BotAPI/Available Types/Animation.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/Audio.cs b/src/library/Telegram.BotAPI/Available Types/Audio.cs similarity index 99% rename from src/Telegram.BotAPI/Available Types/Audio.cs rename to src/library/Telegram.BotAPI/Available Types/Audio.cs index aebf1f62..517c21ed 100644 --- a/src/Telegram.BotAPI/Available Types/Audio.cs +++ b/src/library/Telegram.BotAPI/Available Types/Audio.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/BotCommand.cs b/src/library/Telegram.BotAPI/Available Types/BotCommand.cs similarity index 98% rename from src/Telegram.BotAPI/Available Types/BotCommand.cs rename to src/library/Telegram.BotAPI/Available Types/BotCommand.cs index 71146cec..9c1894a6 100644 --- a/src/Telegram.BotAPI/Available Types/BotCommand.cs +++ b/src/library/Telegram.BotAPI/Available Types/BotCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScope.cs b/src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScope.cs similarity index 96% rename from src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScope.cs rename to src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScope.cs index 420a15cb..c72c63d5 100644 --- a/src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScope.cs +++ b/src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScope.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeAllChatAdministrators.cs b/src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeAllChatAdministrators.cs similarity index 94% rename from src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeAllChatAdministrators.cs rename to src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeAllChatAdministrators.cs index 50f73b80..b409bb39 100644 --- a/src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeAllChatAdministrators.cs +++ b/src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeAllChatAdministrators.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeAllGroupChats.cs b/src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeAllGroupChats.cs similarity index 94% rename from src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeAllGroupChats.cs rename to src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeAllGroupChats.cs index d8cdc3b5..e153feaa 100644 --- a/src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeAllGroupChats.cs +++ b/src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeAllGroupChats.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeAllPrivateChats.cs b/src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeAllPrivateChats.cs similarity index 94% rename from src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeAllPrivateChats.cs rename to src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeAllPrivateChats.cs index 685756a0..90b12d2d 100644 --- a/src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeAllPrivateChats.cs +++ b/src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeAllPrivateChats.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeChat.cs b/src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeChat.cs similarity index 98% rename from src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeChat.cs rename to src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeChat.cs index 040a7dd1..08c8304b 100644 --- a/src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeChat.cs +++ b/src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeChat.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeChatAdministrators.cs b/src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeChatAdministrators.cs similarity index 98% rename from src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeChatAdministrators.cs rename to src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeChatAdministrators.cs index c0aa9814..6f3defee 100644 --- a/src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeChatAdministrators.cs +++ b/src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeChatAdministrators.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeChatMember.cs b/src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeChatMember.cs similarity index 98% rename from src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeChatMember.cs rename to src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeChatMember.cs index 2db162dd..2d7be5c2 100644 --- a/src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeChatMember.cs +++ b/src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeChatMember.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeDefault.cs b/src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeDefault.cs similarity index 95% rename from src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeDefault.cs rename to src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeDefault.cs index 3f738d41..1f205dd6 100644 --- a/src/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeDefault.cs +++ b/src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeDefault.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeType.cs b/src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeType.cs new file mode 100644 index 00000000..4e75178d --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/BotCommandScope/BotCommandScopeType.cs @@ -0,0 +1,39 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// Available types of . +/// +public static class BotCommandScopeType +{ + /// + /// All chat administrators. Represents the scope of bot commands, covering all group and supergroup chat administrators. + /// + public const string AllChatAdministrators = "all_chat_administrators"; + /// + /// All group chats. Represents the scope of bot commands, covering all group and supergroup chats. + /// + public const string AllGroupChats = "all_group_chats"; + /// + /// All private chats. Represents the scope of bot commands, covering all private chats. + /// + public const string AllPrivateChats = "all_private_chats"; + /// + /// Chat. Represents the scope of bot commands, covering a specific chat. + /// + public const string Chat = CommonNames.Chat; + /// + /// Chat administrators. Represents the scope of bot commands, covering all administrators of a specific group or supergroup chat. + /// + public const string ChatAdministrators = "chat_administrators"; + /// + /// Chat member. Represents the scope of bot commands, covering a specific member of a group or supergroup chat. + /// + public const string ChatMember = CommonNames.ChatMember; + /// + /// Default. Represents the default scope of bot commands. Default commands are used if no commands with a narrower scope are specified for the user. + /// + public const string Default = "default"; +} diff --git a/src/Telegram.BotAPI/Available Types/BotDescription.cs b/src/library/Telegram.BotAPI/Available Types/BotDescription.cs similarity index 95% rename from src/Telegram.BotAPI/Available Types/BotDescription.cs rename to src/library/Telegram.BotAPI/Available Types/BotDescription.cs index 781e0d44..d7b33643 100644 --- a/src/Telegram.BotAPI/Available Types/BotDescription.cs +++ b/src/library/Telegram.BotAPI/Available Types/BotDescription.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/BotName.cs b/src/library/Telegram.BotAPI/Available Types/BotName.cs similarity index 97% rename from src/Telegram.BotAPI/Available Types/BotName.cs rename to src/library/Telegram.BotAPI/Available Types/BotName.cs index c7470c79..42f77439 100644 --- a/src/Telegram.BotAPI/Available Types/BotName.cs +++ b/src/library/Telegram.BotAPI/Available Types/BotName.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/BotShortDescription.cs b/src/library/Telegram.BotAPI/Available Types/BotShortDescription.cs similarity index 95% rename from src/Telegram.BotAPI/Available Types/BotShortDescription.cs rename to src/library/Telegram.BotAPI/Available Types/BotShortDescription.cs index 38039ace..99121d8d 100644 --- a/src/Telegram.BotAPI/Available Types/BotShortDescription.cs +++ b/src/library/Telegram.BotAPI/Available Types/BotShortDescription.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/library/Telegram.BotAPI/Available Types/CallbackQuery.cs b/src/library/Telegram.BotAPI/Available Types/CallbackQuery.cs new file mode 100644 index 00000000..3dad15c6 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/CallbackQuery.cs @@ -0,0 +1,55 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// This object represents an incoming callback query from a callback button in an inline keyboard. If the button that originated the query was attached to a message sent by the bot, the field message will be present. If the button was attached to a message sent via the bot (in inline mode), the field inline_message_id will be present. Exactly one of the fields data or game_short_name will be present. +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public sealed class CallbackQuery +{ + /// + /// Unique identifier for this query + /// + [JsonPropertyName(PropertyNames.Id)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string Id { get; set; } + /// + /// Sender + /// + [JsonPropertyName(PropertyNames.From)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public User From { get; set; } + /// + /// Global identifier, uniquely corresponding to the chat to which the message with the callback button was sent. Useful for high scores in games. + /// + [JsonPropertyName(PropertyNames.ChatInstance)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string ChatInstance { get; set; } + /// + /// Optional. Message sent by the bot with the callback button that originated the query + /// + [JsonPropertyName(PropertyNames.Message)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public MaybeInaccessibleMessage? Message { get; set; } + /// + /// Optional. Identifier of the message sent via the bot in inline mode, that originated the query. + /// + [JsonPropertyName(PropertyNames.InlineMessageId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? InlineMessageId { get; set; } + /// + /// Optional. Data associated with the callback button. Be aware that the message originated the query can contain no callback buttons with this data. + /// + [JsonPropertyName(PropertyNames.Data)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? Data { get; set; } + /// + /// Optional. Short name of a Game to be returned, serves as the unique identifier for the game + /// + [JsonPropertyName(PropertyNames.GameShortName)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? GameShortName { get; set; } +} diff --git a/src/Telegram.BotAPI/Available Types/Chat.cs b/src/library/Telegram.BotAPI/Available Types/Chat.cs similarity index 63% rename from src/Telegram.BotAPI/Available Types/Chat.cs rename to src/library/Telegram.BotAPI/Available Types/Chat.cs index 523b5157..3a32ca7a 100644 --- a/src/Telegram.BotAPI/Available Types/Chat.cs +++ b/src/library/Telegram.BotAPI/Available Types/Chat.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; @@ -6,9 +6,11 @@ namespace Telegram.BotAPI.AvailableTypes; -/// This object represents a chat. +/// +/// This object represents a chat. +/// [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public sealed class Chat : ITelegramChat, IEquatable +public class Chat : ITelegramChat { /// /// Unique identifier for this chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier. @@ -21,7 +23,7 @@ public sealed class Chat : ITelegramChat, IEquatable /// [JsonPropertyName(PropertyNames.Type)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string Type { get; set; } = null!; + public string Type { get; set; } /// /// Optional. Title, for supergroups, channels and group chats /// @@ -65,13 +67,43 @@ public sealed class Chat : ITelegramChat, IEquatable [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public IEnumerable? ActiveUsernames { get; set; } /// - /// Optional. Custom emoji identifier of emoji status of the other party in a private chat. Returned only in getChat. + /// Optional. List of available reactions allowed in the chat. If omitted, then all emoji reactions are allowed. Returned only in getChat. + /// + [JsonPropertyName(PropertyNames.AvailableReactions)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public IEnumerable? AvailableReactions { get; set; } + /// + /// Optional. Identifier of the accent color for the chat name and backgrounds of the chat photo, reply header, and link preview. See accent colors for more details. Returned only in getChat. Always returned in getChat. + /// + [JsonPropertyName(PropertyNames.AccentColorId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? AccentColorId { get; set; } + /// + /// Optional. Custom emoji identifier of emoji chosen by the chat for the reply header and link preview background. Returned only in getChat. + /// + [JsonPropertyName(PropertyNames.BackgroundCustomEmojiId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? BackgroundCustomEmojiId { get; set; } + /// + /// Optional. Identifier of the accent color for the chat's profile background. See profile accent colors for more details. Returned only in getChat. + /// + [JsonPropertyName(PropertyNames.ProfileAccentColorId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? ProfileAccentColorId { get; set; } + /// + /// Optional. Custom emoji identifier of the emoji chosen by the chat for its profile background. Returned only in getChat. + /// + [JsonPropertyName(PropertyNames.ProfileBackgroundCustomEmojiId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? ProfileBackgroundCustomEmojiId { get; set; } + /// + /// Optional. Custom emoji identifier of the emoji status of the chat or the other party in a private chat. Returned only in getChat. /// [JsonPropertyName(PropertyNames.EmojiStatusCustomEmojiId)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? EmojiStatusCustomEmojiId { get; set; } /// - /// Optional. Expiration date of the emoji status of the other party in a private chat, if any. Returned only in getChat. + /// Optional. Expiration date of the emoji status of the chat or the other party in a private chat, in Unix time, if any. Returned only in getChat. /// [JsonPropertyName(PropertyNames.EmojiStatusExpirationDate)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] @@ -161,6 +193,12 @@ public sealed class Chat : ITelegramChat, IEquatable [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? HasProtectedContent { get; set; } /// + /// Optional. True, if new chat members will have access to old messages; available only to chat administrators. Returned only in getChat. + /// + [JsonPropertyName(PropertyNames.HasVisibleHistory)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? HasVisibleHistory { get; set; } + /// /// Optional. For supergroups, name of group sticker set. Returned only in getChat. /// [JsonPropertyName(PropertyNames.StickerSetName)] @@ -184,93 +222,4 @@ public sealed class Chat : ITelegramChat, IEquatable [JsonPropertyName(PropertyNames.Location)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public ChatLocation? Location { get; set; } - - /// - public override bool Equals(object? obj) - { - return this.Equals(obj as Chat); - } - - /// - public bool Equals(Chat? other) - { - return other is not null && - this.Id == other.Id && - this.Type == other.Type && - this.Title == other.Title && - this.Username == other.Username && - this.FirstName == other.FirstName && - this.LastName == other.LastName && - this.IsForum == other.IsForum && - EqualityComparer.Default.Equals(this.Photo, other.Photo) && - EqualityComparer?>.Default.Equals(this.ActiveUsernames, other.ActiveUsernames) && - this.EmojiStatusCustomEmojiId == other.EmojiStatusCustomEmojiId && - this.EmojiStatusExpirationDate == other.EmojiStatusExpirationDate && - this.Bio == other.Bio && - this.HasPrivateForwards == other.HasPrivateForwards && - this.HasRestrictedVoiceAndVideoMessages == other.HasRestrictedVoiceAndVideoMessages && - this.JoinToSendMessages == other.JoinToSendMessages && - this.JoinByRequest == other.JoinByRequest && - this.Description == other.Description && - this.InviteLink == other.InviteLink && - EqualityComparer.Default.Equals(this.PinnedMessage, other.PinnedMessage) && - EqualityComparer.Default.Equals(this.Permissions, other.Permissions) && - this.SlowModeDelay == other.SlowModeDelay && - this.MessageAutoDeleteTime == other.MessageAutoDeleteTime && - this.HasAggressiveAntiSpamEnabled == other.HasAggressiveAntiSpamEnabled && - this.HasHiddenMembers == other.HasHiddenMembers && - this.HasProtectedContent == other.HasProtectedContent && - this.StickerSetName == other.StickerSetName && - this.CanSetStickerSet == other.CanSetStickerSet && - this.LinkedChatId == other.LinkedChatId && - EqualityComparer.Default.Equals(this.Location, other.Location); - } - - /// - public override int GetHashCode() - { - int hashCode = -2076976327; - hashCode = hashCode * -1521134295 + this.Id.GetHashCode(); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Type); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Title); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Username); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.FirstName); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.LastName); - hashCode = hashCode * -1521134295 + this.IsForum.GetHashCode(); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Photo); - hashCode = hashCode * -1521134295 + EqualityComparer?>.Default.GetHashCode(this.ActiveUsernames); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.EmojiStatusCustomEmojiId); - hashCode = hashCode * -1521134295 + this.EmojiStatusExpirationDate.GetHashCode(); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Bio); - hashCode = hashCode * -1521134295 + this.HasPrivateForwards.GetHashCode(); - hashCode = hashCode * -1521134295 + this.HasRestrictedVoiceAndVideoMessages.GetHashCode(); - hashCode = hashCode * -1521134295 + this.JoinToSendMessages.GetHashCode(); - hashCode = hashCode * -1521134295 + this.JoinByRequest.GetHashCode(); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Description); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.InviteLink); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.PinnedMessage); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Permissions); - hashCode = hashCode * -1521134295 + this.SlowModeDelay.GetHashCode(); - hashCode = hashCode * -1521134295 + this.MessageAutoDeleteTime.GetHashCode(); - hashCode = hashCode * -1521134295 + this.HasAggressiveAntiSpamEnabled.GetHashCode(); - hashCode = hashCode * -1521134295 + this.HasHiddenMembers.GetHashCode(); - hashCode = hashCode * -1521134295 + this.HasProtectedContent.GetHashCode(); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.StickerSetName); - hashCode = hashCode * -1521134295 + this.CanSetStickerSet.GetHashCode(); - hashCode = hashCode * -1521134295 + this.LinkedChatId.GetHashCode(); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Location); - return hashCode; - } - - /// - public static bool operator ==(Chat? left, Chat? right) - { - return EqualityComparer.Default.Equals(left, right); - } - - /// - public static bool operator !=(Chat? left, Chat? right) - { - return !(left == right); - } } diff --git a/src/Telegram.BotAPI/Available Types/ChatAdministratorRights.cs b/src/library/Telegram.BotAPI/Available Types/ChatAdministratorRights.cs similarity index 99% rename from src/Telegram.BotAPI/Available Types/ChatAdministratorRights.cs rename to src/library/Telegram.BotAPI/Available Types/ChatAdministratorRights.cs index e0f9902c..375f0fbc 100644 --- a/src/Telegram.BotAPI/Available Types/ChatAdministratorRights.cs +++ b/src/library/Telegram.BotAPI/Available Types/ChatAdministratorRights.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/library/Telegram.BotAPI/Available Types/ChatBoost/ChatBoost.cs b/src/library/Telegram.BotAPI/Available Types/ChatBoost/ChatBoost.cs new file mode 100644 index 00000000..035756cc --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/ChatBoost/ChatBoost.cs @@ -0,0 +1,39 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// This object contains information about a chat boost. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class ChatBoost +{ + /// + /// Unique identifier of the boost + /// + [JsonPropertyName(PropertyNames.BoostId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string BoostId { get; set; } + /// + /// Point in time (Unix timestamp) when the chat was boosted + /// + [JsonPropertyName(PropertyNames.AddDate)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public uint AddDate { get; set; } + /// + /// Point in time (Unix timestamp) when the boost will automatically expire, unless the booster's Telegram Premium subscription is prolonged + /// + [JsonPropertyName(PropertyNames.ExpirationDate)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public uint ExpirationDate { get; set; } + /// + /// Source of the added boost + /// + [JsonPropertyName(PropertyNames.Source)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ChatBoostSource Source { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Available Types/ChatBoost/ChatBoostRemoved.cs b/src/library/Telegram.BotAPI/Available Types/ChatBoost/ChatBoostRemoved.cs new file mode 100644 index 00000000..970cc7bf --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/ChatBoost/ChatBoostRemoved.cs @@ -0,0 +1,39 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// This object represents a boost removed from a chat. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class ChatBoostRemoved +{ + /// + /// Chat which was boosted + /// + [JsonPropertyName(PropertyNames.Chat)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Chat Chat { get; set; } + /// + /// Unique identifier of the boost + /// + [JsonPropertyName(PropertyNames.BoostId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string BoostId { get; set; } + /// + /// Point in time (Unix timestamp) when the boost was removed + /// + [JsonPropertyName(PropertyNames.RemoveDate)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int RemoveDate { get; set; } + /// + /// Source of the removed boost + /// + [JsonPropertyName(PropertyNames.Source)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ChatBoostSource Source { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Available Types/ChatBoost/ChatBoostSource.cs b/src/library/Telegram.BotAPI/Available Types/ChatBoost/ChatBoostSource.cs new file mode 100644 index 00000000..5b9bf843 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/ChatBoost/ChatBoostSource.cs @@ -0,0 +1,28 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using Telegram.BotAPI.Converters; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// This object describes the source of a chat boost. It can be one of +/// +/// +/// +/// +/// +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +[System.Text.Json.Serialization.JsonConverter(typeof(ChatBoostSourceConverter))] +public abstract class ChatBoostSource +{ + /// + /// Source of the boost + /// + [JsonPropertyName(PropertyNames.Source)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public abstract string Source { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Available Types/ChatBoost/ChatBoostSourceGiftCode.cs b/src/library/Telegram.BotAPI/Available Types/ChatBoost/ChatBoostSourceGiftCode.cs new file mode 100644 index 00000000..e4b366e9 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/ChatBoost/ChatBoostSourceGiftCode.cs @@ -0,0 +1,27 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// The boost was obtained by the creation of Telegram Premium gift codes to boost a chat. Each such code boosts the chat 4 times for the duration of the corresponding Telegram Premium subscription. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class ChatBoostSourceGiftCode : ChatBoostSource +{ + /// + /// Source of the boost, always “gift_code” + /// + [JsonPropertyName(PropertyNames.Source)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public override string Source { get; set; } + /// + /// User for which the gift code was created + /// + [JsonPropertyName(PropertyNames.User)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public User User { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Available Types/ChatBoost/ChatBoostSourceGiveaway.cs b/src/library/Telegram.BotAPI/Available Types/ChatBoost/ChatBoostSourceGiveaway.cs new file mode 100644 index 00000000..f7d0bdb5 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/ChatBoost/ChatBoostSourceGiveaway.cs @@ -0,0 +1,39 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// The boost was obtained by the creation of a Telegram Premium giveaway. This boosts the chat 4 times for the duration of the corresponding Telegram Premium subscription. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class ChatBoostSourceGiveaway : ChatBoostSource +{ + /// + /// Source of the boost, always “giveaway” + /// + [JsonPropertyName(PropertyNames.Source)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public override string Source { get; set; } + /// + /// Identifier of a message in the chat with the giveaway; the message could have been deleted already. May be 0 if the message isn't sent yet. + /// + [JsonPropertyName(PropertyNames.GiveawayMessageId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public long GiveawayMessageId { get; set; } + /// + /// Optional. User that won the prize in the giveaway if any + /// + [JsonPropertyName(PropertyNames.User)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public User? User { get; set; } + /// + /// Optional. True, if the giveaway was completed, but there was no user to win the prize + /// + [JsonPropertyName(PropertyNames.IsUnclaimed)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? IsUnclaimed { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Available Types/ChatBoost/ChatBoostSourcePremium.cs b/src/library/Telegram.BotAPI/Available Types/ChatBoost/ChatBoostSourcePremium.cs new file mode 100644 index 00000000..8a2984ef --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/ChatBoost/ChatBoostSourcePremium.cs @@ -0,0 +1,27 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// The boost was obtained by subscribing to Telegram Premium or by gifting a Telegram Premium subscription to another user. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class ChatBoostSourcePremium : ChatBoostSource +{ + /// + /// Source of the boost, always “premium” + /// + [JsonPropertyName(PropertyNames.Source)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public override string Source { get; set; } + /// + /// User that boosted the chat + /// + [JsonPropertyName(PropertyNames.User)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public User User { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Available Types/ChatBoost/ChatBoostUpdated.cs b/src/library/Telegram.BotAPI/Available Types/ChatBoost/ChatBoostUpdated.cs new file mode 100644 index 00000000..69d6a650 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/ChatBoost/ChatBoostUpdated.cs @@ -0,0 +1,27 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// This object represents a boost added to a chat or changed. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class ChatBoostUpdated +{ + /// + /// Chat which was boosted + /// + [JsonPropertyName(PropertyNames.Chat)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Chat Chat { get; set; } + /// + /// Infomation about the chat boost + /// + [JsonPropertyName(PropertyNames.Boost)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ChatBoost Boost { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Available Types/ChatBoost/UserChatBoosts.cs b/src/library/Telegram.BotAPI/Available Types/ChatBoost/UserChatBoosts.cs new file mode 100644 index 00000000..07033dd9 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/ChatBoost/UserChatBoosts.cs @@ -0,0 +1,21 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// This object represents a list of boosts added to a chat by a user. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class UserChatBoosts +{ + /// + /// The list of boosts added to the chat by the user + /// + [JsonPropertyName(PropertyNames.Boosts)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public IEnumerable Boosts { get; set; } +} diff --git a/src/Telegram.BotAPI/Available Types/ChatInviteLink.cs b/src/library/Telegram.BotAPI/Available Types/ChatInviteLink.cs similarity index 99% rename from src/Telegram.BotAPI/Available Types/ChatInviteLink.cs rename to src/library/Telegram.BotAPI/Available Types/ChatInviteLink.cs index 2678d6ca..a0f36d28 100644 --- a/src/Telegram.BotAPI/Available Types/ChatInviteLink.cs +++ b/src/library/Telegram.BotAPI/Available Types/ChatInviteLink.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/ChatJoinRequest.cs b/src/library/Telegram.BotAPI/Available Types/ChatJoinRequest.cs similarity index 98% rename from src/Telegram.BotAPI/Available Types/ChatJoinRequest.cs rename to src/library/Telegram.BotAPI/Available Types/ChatJoinRequest.cs index d1560ef7..73101b97 100644 --- a/src/Telegram.BotAPI/Available Types/ChatJoinRequest.cs +++ b/src/library/Telegram.BotAPI/Available Types/ChatJoinRequest.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/ChatLocation.cs b/src/library/Telegram.BotAPI/Available Types/ChatLocation.cs similarity index 98% rename from src/Telegram.BotAPI/Available Types/ChatLocation.cs rename to src/library/Telegram.BotAPI/Available Types/ChatLocation.cs index c29df82e..b21178bb 100644 --- a/src/Telegram.BotAPI/Available Types/ChatLocation.cs +++ b/src/library/Telegram.BotAPI/Available Types/ChatLocation.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/ChatMember/ChatMember.cs b/src/library/Telegram.BotAPI/Available Types/ChatMember/ChatMember.cs similarity index 97% rename from src/Telegram.BotAPI/Available Types/ChatMember/ChatMember.cs rename to src/library/Telegram.BotAPI/Available Types/ChatMember/ChatMember.cs index d3713550..64386a70 100644 --- a/src/Telegram.BotAPI/Available Types/ChatMember/ChatMember.cs +++ b/src/library/Telegram.BotAPI/Available Types/ChatMember/ChatMember.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/ChatMember/ChatMemberAdministrator.cs b/src/library/Telegram.BotAPI/Available Types/ChatMember/ChatMemberAdministrator.cs similarity index 99% rename from src/Telegram.BotAPI/Available Types/ChatMember/ChatMemberAdministrator.cs rename to src/library/Telegram.BotAPI/Available Types/ChatMember/ChatMemberAdministrator.cs index fda847f9..e85cf9cd 100644 --- a/src/Telegram.BotAPI/Available Types/ChatMember/ChatMemberAdministrator.cs +++ b/src/library/Telegram.BotAPI/Available Types/ChatMember/ChatMemberAdministrator.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/ChatMember/ChatMemberBanned.cs b/src/library/Telegram.BotAPI/Available Types/ChatMember/ChatMemberBanned.cs similarity index 98% rename from src/Telegram.BotAPI/Available Types/ChatMember/ChatMemberBanned.cs rename to src/library/Telegram.BotAPI/Available Types/ChatMember/ChatMemberBanned.cs index 2a71ba06..59d60731 100644 --- a/src/Telegram.BotAPI/Available Types/ChatMember/ChatMemberBanned.cs +++ b/src/library/Telegram.BotAPI/Available Types/ChatMember/ChatMemberBanned.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/ChatMember/ChatMemberLeft.cs b/src/library/Telegram.BotAPI/Available Types/ChatMember/ChatMemberLeft.cs similarity index 97% rename from src/Telegram.BotAPI/Available Types/ChatMember/ChatMemberLeft.cs rename to src/library/Telegram.BotAPI/Available Types/ChatMember/ChatMemberLeft.cs index 3676eceb..c09f063f 100644 --- a/src/Telegram.BotAPI/Available Types/ChatMember/ChatMemberLeft.cs +++ b/src/library/Telegram.BotAPI/Available Types/ChatMember/ChatMemberLeft.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/ChatMember/ChatMemberMember.cs b/src/library/Telegram.BotAPI/Available Types/ChatMember/ChatMemberMember.cs similarity index 97% rename from src/Telegram.BotAPI/Available Types/ChatMember/ChatMemberMember.cs rename to src/library/Telegram.BotAPI/Available Types/ChatMember/ChatMemberMember.cs index becfb48c..1df1d0d1 100644 --- a/src/Telegram.BotAPI/Available Types/ChatMember/ChatMemberMember.cs +++ b/src/library/Telegram.BotAPI/Available Types/ChatMember/ChatMemberMember.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/ChatMember/ChatMemberOwner.cs b/src/library/Telegram.BotAPI/Available Types/ChatMember/ChatMemberOwner.cs similarity index 98% rename from src/Telegram.BotAPI/Available Types/ChatMember/ChatMemberOwner.cs rename to src/library/Telegram.BotAPI/Available Types/ChatMember/ChatMemberOwner.cs index 9aae2182..e3f54d12 100644 --- a/src/Telegram.BotAPI/Available Types/ChatMember/ChatMemberOwner.cs +++ b/src/library/Telegram.BotAPI/Available Types/ChatMember/ChatMemberOwner.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/ChatMember/ChatMemberRestricted.cs b/src/library/Telegram.BotAPI/Available Types/ChatMember/ChatMemberRestricted.cs similarity index 99% rename from src/Telegram.BotAPI/Available Types/ChatMember/ChatMemberRestricted.cs rename to src/library/Telegram.BotAPI/Available Types/ChatMember/ChatMemberRestricted.cs index 32e1a1c6..4b89e73d 100644 --- a/src/Telegram.BotAPI/Available Types/ChatMember/ChatMemberRestricted.cs +++ b/src/library/Telegram.BotAPI/Available Types/ChatMember/ChatMemberRestricted.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/ChatMember/ChatMemberStatus.cs b/src/library/Telegram.BotAPI/Available Types/ChatMember/ChatMemberStatus.cs similarity index 95% rename from src/Telegram.BotAPI/Available Types/ChatMember/ChatMemberStatus.cs rename to src/library/Telegram.BotAPI/Available Types/ChatMember/ChatMemberStatus.cs index 9f13f198..b896fb74 100644 --- a/src/Telegram.BotAPI/Available Types/ChatMember/ChatMemberStatus.cs +++ b/src/library/Telegram.BotAPI/Available Types/ChatMember/ChatMemberStatus.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI.AvailableTypes; diff --git a/src/Telegram.BotAPI/Available Types/ChatMemberUpdated.cs b/src/library/Telegram.BotAPI/Available Types/ChatMemberUpdated.cs similarity index 99% rename from src/Telegram.BotAPI/Available Types/ChatMemberUpdated.cs rename to src/library/Telegram.BotAPI/Available Types/ChatMemberUpdated.cs index d369e856..fe951758 100644 --- a/src/Telegram.BotAPI/Available Types/ChatMemberUpdated.cs +++ b/src/library/Telegram.BotAPI/Available Types/ChatMemberUpdated.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/ChatPermissions.cs b/src/library/Telegram.BotAPI/Available Types/ChatPermissions.cs similarity index 99% rename from src/Telegram.BotAPI/Available Types/ChatPermissions.cs rename to src/library/Telegram.BotAPI/Available Types/ChatPermissions.cs index b6bf9cd6..5925cfa9 100644 --- a/src/Telegram.BotAPI/Available Types/ChatPermissions.cs +++ b/src/library/Telegram.BotAPI/Available Types/ChatPermissions.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/ChatPhoto.cs b/src/library/Telegram.BotAPI/Available Types/ChatPhoto.cs similarity index 98% rename from src/Telegram.BotAPI/Available Types/ChatPhoto.cs rename to src/library/Telegram.BotAPI/Available Types/ChatPhoto.cs index 1ee34f83..e967bd1f 100644 --- a/src/Telegram.BotAPI/Available Types/ChatPhoto.cs +++ b/src/library/Telegram.BotAPI/Available Types/ChatPhoto.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/ChatShared.cs b/src/library/Telegram.BotAPI/Available Types/ChatShared.cs similarity index 97% rename from src/Telegram.BotAPI/Available Types/ChatShared.cs rename to src/library/Telegram.BotAPI/Available Types/ChatShared.cs index 933d5b27..d389269b 100644 --- a/src/Telegram.BotAPI/Available Types/ChatShared.cs +++ b/src/library/Telegram.BotAPI/Available Types/ChatShared.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/Contact.cs b/src/library/Telegram.BotAPI/Available Types/Contact.cs similarity index 94% rename from src/Telegram.BotAPI/Available Types/Contact.cs rename to src/library/Telegram.BotAPI/Available Types/Contact.cs index eb83b8a8..fa8fa5a1 100644 --- a/src/Telegram.BotAPI/Available Types/Contact.cs +++ b/src/library/Telegram.BotAPI/Available Types/Contact.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; @@ -71,9 +71,7 @@ public override int GetHashCode() /// public static bool operator ==(Contact? left, Contact? right) { -#pragma warning disable CS8604 // Possible null reference argument. return EqualityComparer.Default.Equals(left!, right!); -#pragma warning restore CS8604 // Possible null reference argument. } /// public static bool operator !=(Contact? left, Contact? right) diff --git a/src/Telegram.BotAPI/Available Types/Dice.cs b/src/library/Telegram.BotAPI/Available Types/Dice.cs similarity index 93% rename from src/Telegram.BotAPI/Available Types/Dice.cs rename to src/library/Telegram.BotAPI/Available Types/Dice.cs index 0abda38d..286f2efc 100644 --- a/src/Telegram.BotAPI/Available Types/Dice.cs +++ b/src/library/Telegram.BotAPI/Available Types/Dice.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; @@ -49,9 +49,7 @@ public override int GetHashCode() /// public static bool operator ==(Dice? left, Dice? right) { -#pragma warning disable CS8604 // Possible null reference argument. return EqualityComparer.Default.Equals(left!, right!); -#pragma warning restore CS8604 // Possible null reference argument. } /// public static bool operator !=(Dice? left, Dice? right) diff --git a/src/Telegram.BotAPI/Available Types/Document.cs b/src/library/Telegram.BotAPI/Available Types/Document.cs similarity index 98% rename from src/Telegram.BotAPI/Available Types/Document.cs rename to src/library/Telegram.BotAPI/Available Types/Document.cs index 51c311a0..163e2d94 100644 --- a/src/Telegram.BotAPI/Available Types/Document.cs +++ b/src/library/Telegram.BotAPI/Available Types/Document.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/library/Telegram.BotAPI/Available Types/ExternalReplyInfo.cs b/src/library/Telegram.BotAPI/Available Types/ExternalReplyInfo.cs new file mode 100644 index 00000000..3afbcb64 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/ExternalReplyInfo.cs @@ -0,0 +1,156 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using Telegram.BotAPI.Games; +using Telegram.BotAPI.Payments; +using Telegram.BotAPI.Stickers; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// This object contains information about a message that is being replied to, which may come from another chat or forum topic. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class ExternalReplyInfo +{ + /// + /// Origin of the message replied to by the given message + /// + [JsonPropertyName(PropertyNames.Origin)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public MessageOrigin Origin { get; set; } + /// + /// Optional. Chat the original message belongs to. Available only if the chat is a supergroup or a channel. + /// + [JsonPropertyName(PropertyNames.Chat)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Chat? Chat { get; set; } + /// + /// Optional. Unique message identifier inside the original chat. Available only if the original chat is a supergroup or a channel. + /// + [JsonPropertyName(PropertyNames.MessageId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public long? MessageId { get; set; } + /// + /// Optional. Options used for link preview generation for the original message, if it is a text message + /// + [JsonPropertyName(PropertyNames.LinkPreviewOptions)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public LinkPreviewOptions? LinkPreviewOptions { get; set; } + /// + /// Optional. Message is an animation, information about the animation + /// + [JsonPropertyName(PropertyNames.Animation)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Animation? Animation { get; set; } + /// + /// Optional. Message is an audio file, information about the file + /// + [JsonPropertyName(PropertyNames.Audio)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Audio? Audio { get; set; } + /// + /// Optional. Message is a general file, information about the file + /// + [JsonPropertyName(PropertyNames.Document)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Document? Document { get; set; } + /// + /// Optional. Message is a photo, available sizes of the photo + /// + [JsonPropertyName(PropertyNames.Photo)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public IEnumerable? Photo { get; set; } + /// + /// Optional. Message is a sticker, information about the sticker + /// + [JsonPropertyName(PropertyNames.Sticker)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Sticker? Sticker { get; set; } + /// + /// Optional. Message is a forwarded story + /// + [JsonPropertyName(PropertyNames.Story)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Story? Story { get; set; } + /// + /// Optional. Message is a video, information about the video + /// + [JsonPropertyName(PropertyNames.Video)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Video? Video { get; set; } + /// + /// Optional. Message is a video note, information about the video message + /// + [JsonPropertyName(PropertyNames.VideoNote)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public VideoNote? VideoNote { get; set; } + /// + /// Optional. Message is a voice message, information about the file + /// + [JsonPropertyName(PropertyNames.Voice)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Voice? Voice { get; set; } + /// + /// Optional. True, if the message media is covered by a spoiler animation + /// + [JsonPropertyName(PropertyNames.HasMediaSpoiler)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? HasMediaSpoiler { get; set; } + /// + /// Optional. Message is a shared contact, information about the contact + /// + [JsonPropertyName(PropertyNames.Contact)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Contact? Contact { get; set; } + /// + /// Optional. Message is a dice with random value + /// + [JsonPropertyName(PropertyNames.Dice)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Dice? Dice { get; set; } + /// + /// Optional. Message is a game, information about the game. More about games » + /// + [JsonPropertyName(PropertyNames.Game)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Game? Game { get; set; } + /// + /// Optional. Message is a scheduled giveaway, information about the giveaway + /// + [JsonPropertyName(PropertyNames.Giveaway)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Giveaway? Giveaway { get; set; } + /// + /// Optional. A giveaway with public winners was completed + /// + [JsonPropertyName(PropertyNames.GiveawayWinners)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public GiveawayWinners? GiveawayWinners { get; set; } + /// + /// Optional. Message is an invoice for a payment, information about the invoice. More about payments » + /// + [JsonPropertyName(PropertyNames.Invoice)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Invoice? Invoice { get; set; } + /// + /// Optional. Message is a shared location, information about the location + /// + [JsonPropertyName(PropertyNames.Location)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Location? Location { get; set; } + /// + /// Optional. Message is a native poll, information about the poll + /// + [JsonPropertyName(PropertyNames.Poll)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Poll? Poll { get; set; } + /// + /// Optional. Message is a venue, information about the venue + /// + [JsonPropertyName(PropertyNames.Venue)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Venue? Venue { get; set; } +} diff --git a/src/Telegram.BotAPI/Available Types/File.cs b/src/library/Telegram.BotAPI/Available Types/File.cs similarity index 98% rename from src/Telegram.BotAPI/Available Types/File.cs rename to src/library/Telegram.BotAPI/Available Types/File.cs index 43da24f3..305e8948 100644 --- a/src/Telegram.BotAPI/Available Types/File.cs +++ b/src/library/Telegram.BotAPI/Available Types/File.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/ForceReply.cs b/src/library/Telegram.BotAPI/Available Types/ForceReply.cs similarity index 98% rename from src/Telegram.BotAPI/Available Types/ForceReply.cs rename to src/library/Telegram.BotAPI/Available Types/ForceReply.cs index dd1eaa8e..a5a1816d 100644 --- a/src/Telegram.BotAPI/Available Types/ForceReply.cs +++ b/src/library/Telegram.BotAPI/Available Types/ForceReply.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/ForumTopic.cs b/src/library/Telegram.BotAPI/Available Types/ForumTopic.cs similarity index 97% rename from src/Telegram.BotAPI/Available Types/ForumTopic.cs rename to src/library/Telegram.BotAPI/Available Types/ForumTopic.cs index f3db452b..dd4d5d9a 100644 --- a/src/Telegram.BotAPI/Available Types/ForumTopic.cs +++ b/src/library/Telegram.BotAPI/Available Types/ForumTopic.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/ForumTopicClosed.cs b/src/library/Telegram.BotAPI/Available Types/ForumTopicClosed.cs similarity index 92% rename from src/Telegram.BotAPI/Available Types/ForumTopicClosed.cs rename to src/library/Telegram.BotAPI/Available Types/ForumTopicClosed.cs index 5f997579..d5e55e43 100644 --- a/src/Telegram.BotAPI/Available Types/ForumTopicClosed.cs +++ b/src/library/Telegram.BotAPI/Available Types/ForumTopicClosed.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/ForumTopicCreated.cs b/src/library/Telegram.BotAPI/Available Types/ForumTopicCreated.cs similarity index 96% rename from src/Telegram.BotAPI/Available Types/ForumTopicCreated.cs rename to src/library/Telegram.BotAPI/Available Types/ForumTopicCreated.cs index dda1ba88..a753538f 100644 --- a/src/Telegram.BotAPI/Available Types/ForumTopicCreated.cs +++ b/src/library/Telegram.BotAPI/Available Types/ForumTopicCreated.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/ForumTopicEdited.cs b/src/library/Telegram.BotAPI/Available Types/ForumTopicEdited.cs similarity index 91% rename from src/Telegram.BotAPI/Available Types/ForumTopicEdited.cs rename to src/library/Telegram.BotAPI/Available Types/ForumTopicEdited.cs index 9dde7876..5aaec970 100644 --- a/src/Telegram.BotAPI/Available Types/ForumTopicEdited.cs +++ b/src/library/Telegram.BotAPI/Available Types/ForumTopicEdited.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; @@ -47,9 +47,7 @@ public override int GetHashCode() /// public static bool operator ==(ForumTopicEdited? left, ForumTopicEdited? right) { -#pragma warning disable CS8604 // Possible null reference argument. return EqualityComparer.Default.Equals(left!, right!); -#pragma warning restore CS8604 // Possible null reference argument. } /// public static bool operator !=(ForumTopicEdited? left, ForumTopicEdited? right) diff --git a/src/Telegram.BotAPI/Available Types/ForumTopicReopened.cs b/src/library/Telegram.BotAPI/Available Types/ForumTopicReopened.cs similarity index 92% rename from src/Telegram.BotAPI/Available Types/ForumTopicReopened.cs rename to src/library/Telegram.BotAPI/Available Types/ForumTopicReopened.cs index ee9a9f90..9e3629c4 100644 --- a/src/Telegram.BotAPI/Available Types/ForumTopicReopened.cs +++ b/src/library/Telegram.BotAPI/Available Types/ForumTopicReopened.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/GeneralForumTopicHidden.cs b/src/library/Telegram.BotAPI/Available Types/GeneralForumTopicHidden.cs similarity index 92% rename from src/Telegram.BotAPI/Available Types/GeneralForumTopicHidden.cs rename to src/library/Telegram.BotAPI/Available Types/GeneralForumTopicHidden.cs index 4d042c36..2d8e53ff 100644 --- a/src/Telegram.BotAPI/Available Types/GeneralForumTopicHidden.cs +++ b/src/library/Telegram.BotAPI/Available Types/GeneralForumTopicHidden.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/GeneralForumTopicUnhidden.cs b/src/library/Telegram.BotAPI/Available Types/GeneralForumTopicUnhidden.cs similarity index 93% rename from src/Telegram.BotAPI/Available Types/GeneralForumTopicUnhidden.cs rename to src/library/Telegram.BotAPI/Available Types/GeneralForumTopicUnhidden.cs index 23ab4581..5c933042 100644 --- a/src/Telegram.BotAPI/Available Types/GeneralForumTopicUnhidden.cs +++ b/src/library/Telegram.BotAPI/Available Types/GeneralForumTopicUnhidden.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/library/Telegram.BotAPI/Available Types/Giveaway.cs b/src/library/Telegram.BotAPI/Available Types/Giveaway.cs new file mode 100644 index 00000000..bc3ae3e6 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/Giveaway.cs @@ -0,0 +1,63 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// This object represents a message about a scheduled giveaway. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class Giveaway +{ + /// + /// The list of chats which the user must join to participate in the giveaway + /// + [JsonPropertyName(PropertyNames.Chats)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public IEnumerable Chats { get; set; } + /// + /// Point in time (Unix timestamp) when winners of the giveaway will be selected + /// + [JsonPropertyName(PropertyNames.WinnersSelectionDate)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public uint WinnersSelectionDate { get; set; } + /// + /// The number of users which are supposed to be selected as winners of the giveaway + /// + [JsonPropertyName(PropertyNames.WinnerCount)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public uint WinnerCount { get; set; } + /// + /// Optional. True, if only users who join the chats after the giveaway started should be eligible to win + /// + [JsonPropertyName(PropertyNames.OnlyNewMembers)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? OnlyNewMembers { get; set; } + /// + /// Optional. True, if the list of giveaway winners will be visible to everyone + /// + [JsonPropertyName(PropertyNames.HasPublicWinners)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? HasPublicWinners { get; set; } + /// + /// Optional. Description of additional giveaway prize + /// + [JsonPropertyName(PropertyNames.PrizeDescription)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? PrizeDescription { get; set; } + /// + /// Optional. A list of two-letter ISO 3166-1 alpha-2 country codes indicating the countries from which eligible users for the giveaway must come. If empty, then all users can participate in the giveaway. Users with a phone number that was bought on Fragment can always participate in giveaways. + /// + [JsonPropertyName(PropertyNames.CountryCodes)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public IEnumerable? CountryCodes { get; set; } + /// + /// Optional. The number of months the Telegram Premium subscription won from the giveaway will be active for + /// + [JsonPropertyName(PropertyNames.PremiumSubscriptionMonthCount)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public uint? PremiumSubscriptionMonthCount { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Available Types/GiveawayCompleted.cs b/src/library/Telegram.BotAPI/Available Types/GiveawayCompleted.cs new file mode 100644 index 00000000..d834da92 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/GiveawayCompleted.cs @@ -0,0 +1,33 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// This object represents a service message about the completion of a giveaway without public winners. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class GiveawayCompleted +{ + /// + /// Number of winners in the giveaway + /// + [JsonPropertyName(PropertyNames.WinnerCount)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public uint WinnerCount { get; set; } + /// + /// Optional. Number of undistributed prizes + /// + [JsonPropertyName(PropertyNames.UnclaimedPrizeCount)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public uint? UnclaimedPrizeCount { get; set; } + /// + /// Optional. Message with the giveaway that was completed, if it wasn't deleted + /// + [JsonPropertyName(PropertyNames.GiveawayMessage)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Message? GiveawayMessage { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Available Types/GiveawayCreated.cs b/src/library/Telegram.BotAPI/Available Types/GiveawayCreated.cs new file mode 100644 index 00000000..a53f8918 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/GiveawayCreated.cs @@ -0,0 +1,11 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// This object represents a service message about the creation of a scheduled giveaway. Currently holds no information. +/// +public class GiveawayCreated +{ +} diff --git a/src/library/Telegram.BotAPI/Available Types/GiveawayWinners.cs b/src/library/Telegram.BotAPI/Available Types/GiveawayWinners.cs new file mode 100644 index 00000000..1e4a2142 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/GiveawayWinners.cs @@ -0,0 +1,81 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// This object represents a message about the completion of a giveaway with public winners. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class GiveawayWinners +{ + /// + /// The chat that created the giveaway + /// + [JsonPropertyName(PropertyNames.Chat)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Chat Chat { get; set; } + /// + /// Identifier of the messsage with the giveaway in the chat + /// + [JsonPropertyName(PropertyNames.GiveawayMessageId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public long GiveawayMessageId { get; set; } + /// + /// Point in time (Unix timestamp) when winners of the giveaway were selected + /// + [JsonPropertyName(PropertyNames.WinnersSelectionDate)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public uint WinnersSelectionDate { get; set; } + /// + /// Total number of winners in the giveaway + /// + [JsonPropertyName(PropertyNames.WinnerCount)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public uint WinnerCount { get; set; } + /// + /// List of up to 100 winners of the giveaway + /// + [JsonPropertyName(PropertyNames.Winners)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public IEnumerable Winners { get; set; } + /// + /// Optional. The number of other chats the user had to join in order to be eligible for the giveaway + /// + [JsonPropertyName(PropertyNames.AdditionalChatCount)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public uint? AdditionalChatCount { get; set; } + /// + /// Optional. The number of months the Telegram Premium subscription won from the giveaway will be active for + /// + [JsonPropertyName(PropertyNames.PremiumSubscriptionMonthCount)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public uint? PremiumSubscriptionMonthCount { get; set; } + /// + /// Optional. Number of undistributed prizes + /// + [JsonPropertyName(PropertyNames.UnclaimedPrizeCount)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public uint? UnclaimedPrizeCount { get; set; } + /// + /// Optional. True, if only users who had joined the chats after the giveaway started were eligible to win + /// + [JsonPropertyName(PropertyNames.OnlyNewMembers)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? OnlyNewMembers { get; set; } + /// + /// Optional. True, if the giveaway was canceled because the payment for it was refunded + /// + [JsonPropertyName(PropertyNames.WasRefunded)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? WasRefunded { get; set; } + /// + /// Optional. Description of additional giveaway prize + /// + [JsonPropertyName(PropertyNames.PrizeDescription)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? PrizeDescription { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Available Types/InaccessibleMessage.cs b/src/library/Telegram.BotAPI/Available Types/InaccessibleMessage.cs new file mode 100644 index 00000000..29557b07 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/InaccessibleMessage.cs @@ -0,0 +1,33 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// This object describes a message that was deleted or is otherwise inaccessible to the bot. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class InaccessibleMessage : MaybeInaccessibleMessage +{ + /// + /// Chat the message belonged to + /// + [JsonPropertyName(PropertyNames.Chat)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public override Chat Chat { get; set; } + /// + /// Unique message identifier inside the chat + /// + [JsonPropertyName(PropertyNames.MessageId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public override int MessageId { get; set; } + /// + /// Always 0. The field can be used to differentiate regular and inaccessible messages. + /// + [JsonPropertyName(PropertyNames.Date)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public override uint Date { get; set; } +} diff --git a/src/Telegram.BotAPI/Available Types/InputFile.cs b/src/library/Telegram.BotAPI/Available Types/InputFile.cs similarity index 70% rename from src/Telegram.BotAPI/Available Types/InputFile.cs rename to src/library/Telegram.BotAPI/Available Types/InputFile.cs index 41d26db6..869daa41 100644 --- a/src/Telegram.BotAPI/Available Types/InputFile.cs +++ b/src/library/Telegram.BotAPI/Available Types/InputFile.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -6,15 +6,22 @@ namespace Telegram.BotAPI.AvailableTypes; -/// This object represents the contents of a file to be uploaded. Must be posted using multipart/form-data in the usual way that files are uploaded via the browser. +/// +/// This object represents the contents of a file to be uploaded. Must be posted using multipart/form-data in the usual way that files are uploaded via the browser. +/// public sealed class InputFile : IEquatable { - /// HTTP file content. + /// + /// HTTP file content. + /// [JsonIgnore] public StreamContent Content { get; private set; } - /// File name. + /// + /// File name. + /// [JsonIgnore] public string Filename { get; private set; } + /// New InputFile. /// HTTP file content. /// File name. @@ -23,14 +30,16 @@ public InputFile(StreamContent streamcontent, string filename) this.Content = streamcontent; this.Filename = filename; } + /// New InputFile. - /// Stream file. + /// Stream file. /// File name. - public InputFile(MemoryStream streamfile, string filename) + public InputFile(Stream stream, string filename) { - this.Content = new StreamContent(streamfile); + this.Content = new StreamContent(stream); this.Filename = filename; } + /// New InputFile. /// File. /// File name. @@ -39,6 +48,7 @@ public InputFile(byte[] file, string filename) this.Content = new StreamContent(new MemoryStream(file)); this.Filename = filename; } + /// public override bool Equals(object obj) { @@ -71,19 +81,15 @@ public override int GetHashCode() } } + /// This object represents a attached file. -public sealed class AttachedFile +/// New AttachFile +/// File attach name. +/// This object represents the contents of a file to be uploaded. +public sealed class AttachedFile(string name, InputFile inputFile) { /// AttachFile Name - public string Name { get; } + public string Name { get; } = name; /// File - public InputFile File { get; } - /// New AttachFile - /// File attach name. - /// This object represents the contents of a file to be uploaded. - public AttachedFile(string name, InputFile inputFile) - { - this.Name = name; - this.File = inputFile; - } + public InputFile File { get; } = inputFile; } diff --git a/src/Telegram.BotAPI/Available Types/InputMedia/InputMedia.cs b/src/library/Telegram.BotAPI/Available Types/InputMedia/InputMedia.cs similarity index 80% rename from src/Telegram.BotAPI/Available Types/InputMedia/InputMedia.cs rename to src/library/Telegram.BotAPI/Available Types/InputMedia/InputMedia.cs index d7a09635..b2c3d623 100644 --- a/src/Telegram.BotAPI/Available Types/InputMedia/InputMedia.cs +++ b/src/library/Telegram.BotAPI/Available Types/InputMedia/InputMedia.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; @@ -9,12 +9,15 @@ namespace Telegram.BotAPI.AvailableTypes; -/// This object represents the content of a media message to be sent. It should be one of:

-/// •
-/// •
-/// •
-/// •
-/// •
+/// This object represents the content of a media message to be sent. It should be one of: +/// +/// +/// +/// +/// +/// +/// +/// [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] [JsonConverter(typeof(InputMediaConverter))] public abstract class InputMedia : ICaption, IFormattableMessage @@ -25,7 +28,7 @@ public abstract class InputMedia : ICaption, IFormattableMessage /// File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass “attach://<file_attach_name>” to upload a new one using multipart/form-data under <file_attach_name> name. protected InputMedia(string media) { - this.Media = media ?? throw new ArgumentNullException(nameof(media)); + this.Media = media; } /// Type of the result. @@ -35,7 +38,7 @@ protected InputMedia(string media) ///
[JsonPropertyName(PropertyNames.Media)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string Media { get; set; } + public object Media { get; set; } /// public abstract string? Caption { get; set; } diff --git a/src/Telegram.BotAPI/Available Types/InputMedia/InputMediaAnimation.cs b/src/library/Telegram.BotAPI/Available Types/InputMedia/InputMediaAnimation.cs similarity index 98% rename from src/Telegram.BotAPI/Available Types/InputMedia/InputMediaAnimation.cs rename to src/library/Telegram.BotAPI/Available Types/InputMedia/InputMediaAnimation.cs index edba2672..dbdb7ad8 100644 --- a/src/Telegram.BotAPI/Available Types/InputMedia/InputMediaAnimation.cs +++ b/src/library/Telegram.BotAPI/Available Types/InputMedia/InputMediaAnimation.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/InputMedia/InputMediaAudio.cs b/src/library/Telegram.BotAPI/Available Types/InputMedia/InputMediaAudio.cs similarity index 54% rename from src/Telegram.BotAPI/Available Types/InputMedia/InputMediaAudio.cs rename to src/library/Telegram.BotAPI/Available Types/InputMedia/InputMediaAudio.cs index 01e032ee..3c133d8d 100644 --- a/src/Telegram.BotAPI/Available Types/InputMedia/InputMediaAudio.cs +++ b/src/library/Telegram.BotAPI/Available Types/InputMedia/InputMediaAudio.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; @@ -8,7 +8,7 @@ namespace Telegram.BotAPI.AvailableTypes; /// Represents an audio file to be treated as music to be sent. [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public sealed class InputMediaAudio : InputMedia, IThumbnail, IEquatable +public sealed class InputMediaAudio : InputMedia, IThumbnail { /// /// Initializes a new instance of the class. @@ -44,53 +44,4 @@ public InputMediaAudio(string media) : base(media) [JsonPropertyName(PropertyNames.Title)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? Title { get; set; } - - /// - public override bool Equals(object obj) - { - return this.Equals(obj as InputMediaAudio); - } - - /// - public bool Equals(InputMediaAudio? other) - { - return other != null && - this.Media == other.Media && - EqualityComparer?>.Default.Equals(this.CaptionEntities, other.CaptionEntities) && - this.Type == other.Type && - this.Thumbnail == other.Thumbnail && - this.Caption == other.Caption && - this.ParseMode == other.ParseMode && - this.Duration == other.Duration && - this.Performer == other.Performer && - this.Title == other.Title; - } - - /// - public override int GetHashCode() - { - int hashCode = -1375899436; - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Media); - hashCode = hashCode * -1521134295 + EqualityComparer?>.Default.GetHashCode(this.CaptionEntities); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Type); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Thumbnail); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Caption); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ParseMode); - hashCode = hashCode * -1521134295 + this.Duration.GetHashCode(); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Performer); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Title); - return hashCode; - } - - /// - public static bool operator ==(InputMediaAudio? left, InputMediaAudio? right) - { - return EqualityComparer.Default.Equals(left!, right!); - } - - /// - public static bool operator !=(InputMediaAudio? left, InputMediaAudio? right) - { - return !(left == right); - } } diff --git a/src/Telegram.BotAPI/Available Types/InputMedia/InputMediaDocument.cs b/src/library/Telegram.BotAPI/Available Types/InputMedia/InputMediaDocument.cs similarity index 54% rename from src/Telegram.BotAPI/Available Types/InputMedia/InputMediaDocument.cs rename to src/library/Telegram.BotAPI/Available Types/InputMedia/InputMediaDocument.cs index 7df55799..01774f46 100644 --- a/src/Telegram.BotAPI/Available Types/InputMedia/InputMediaDocument.cs +++ b/src/library/Telegram.BotAPI/Available Types/InputMedia/InputMediaDocument.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; @@ -8,7 +8,7 @@ namespace Telegram.BotAPI.AvailableTypes; /// Represents a general file to be sent. [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public sealed class InputMediaDocument : InputMedia, IThumbnail, IEquatable +public sealed class InputMediaDocument : InputMedia, IThumbnail { /// /// Initializes a new instance of the class. @@ -34,49 +34,4 @@ public InputMediaDocument(string media) : base(media) [JsonPropertyName(PropertyNames.DisableContentTypeDetection)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? DisableContentTypeDetection { get; set; } - - /// - public override bool Equals(object obj) - { - return this.Equals(obj as InputMediaDocument); - } - - /// - public bool Equals(InputMediaDocument? other) - { - return other != null && - this.Media == other.Media && - EqualityComparer?>.Default.Equals(this.CaptionEntities, other.CaptionEntities) && - this.Type == other.Type && - this.Thumbnail == other.Thumbnail && - this.Caption == other.Caption && - this.ParseMode == other.ParseMode && - this.DisableContentTypeDetection == other.DisableContentTypeDetection; - } - - /// - public override int GetHashCode() - { - int hashCode = 363848984; - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Media); - hashCode = hashCode * -1521134295 + EqualityComparer?>.Default.GetHashCode(this.CaptionEntities); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Type); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Thumbnail); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Caption); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ParseMode); - hashCode = hashCode * -1521134295 + this.DisableContentTypeDetection.GetHashCode(); - return hashCode; - } - - /// - public static bool operator ==(InputMediaDocument? left, InputMediaDocument? right) - { - return EqualityComparer.Default.Equals(left!, right!); - } - - /// - public static bool operator !=(InputMediaDocument? left, InputMediaDocument? right) - { - return !(left == right); - } } diff --git a/src/library/Telegram.BotAPI/Available Types/InputMedia/InputMediaPhoto.cs b/src/library/Telegram.BotAPI/Available Types/InputMedia/InputMediaPhoto.cs new file mode 100644 index 00000000..4165f745 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/InputMedia/InputMediaPhoto.cs @@ -0,0 +1,33 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// Represents a photo to be sent. +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public sealed class InputMediaPhoto : InputMedia +{ + /// + /// Initializes a new instance of the class. + /// + /// File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass �attach://<file_attach_name>� to upload a new one using multipart/form-data under <file_attach_name> name. + public InputMediaPhoto(string media) : base(media) + { + } + + /// Type of the result, must be photo. + [JsonPropertyName(PropertyNames.Type)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public override string Type => InputMediaType.Photo; + /// Optional. Caption of the photo to be sent, 0-1024 characters. + [JsonPropertyName(PropertyNames.Caption)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public override string? Caption { get; set; } + /// Optional. Pass True if the photo needs to be covered with a spoiler animation. + [JsonPropertyName(PropertyNames.HasSpoiler)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? HasSpoiler { get; set; } +} diff --git a/src/Telegram.BotAPI/Available Types/InputMedia/InputMediaType.cs b/src/library/Telegram.BotAPI/Available Types/InputMedia/InputMediaType.cs similarity index 94% rename from src/Telegram.BotAPI/Available Types/InputMedia/InputMediaType.cs rename to src/library/Telegram.BotAPI/Available Types/InputMedia/InputMediaType.cs index 36105e6d..1ff7b912 100644 --- a/src/Telegram.BotAPI/Available Types/InputMedia/InputMediaType.cs +++ b/src/library/Telegram.BotAPI/Available Types/InputMedia/InputMediaType.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI.AvailableTypes; diff --git a/src/Telegram.BotAPI/Available Types/InputMedia/InputMediaVideo.cs b/src/library/Telegram.BotAPI/Available Types/InputMedia/InputMediaVideo.cs similarity index 55% rename from src/Telegram.BotAPI/Available Types/InputMedia/InputMediaVideo.cs rename to src/library/Telegram.BotAPI/Available Types/InputMedia/InputMediaVideo.cs index 3ade799c..77cd860f 100644 --- a/src/Telegram.BotAPI/Available Types/InputMedia/InputMediaVideo.cs +++ b/src/library/Telegram.BotAPI/Available Types/InputMedia/InputMediaVideo.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; @@ -8,7 +8,7 @@ namespace Telegram.BotAPI.AvailableTypes; /// Represents a video to be sent. [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public sealed class InputMediaVideo : InputMedia, IThumbnail, IEquatable +public sealed class InputMediaVideo : InputMedia, IThumbnail { /// /// Initializes a new instance of the class. @@ -50,61 +50,4 @@ public InputMediaVideo(string media) : base(media) [JsonPropertyName(PropertyNames.HasSpoiler)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? HasSpoiler { get; set; } - - /// - public override bool Equals(object? obj) - { - return this.Equals(obj as InputMediaVideo); - } - - /// - public bool Equals(InputMediaVideo? other) - { - return other is not null && - this.Type == other.Type && - this.Media == other.Media && - this.Caption == other.Caption && - EqualityComparer?>.Default.Equals(this.CaptionEntities, other.CaptionEntities) && - this.ParseMode == other.ParseMode && - this.Type == other.Type && - this.Thumbnail == other.Thumbnail && - this.Caption == other.Caption && - this.Width == other.Width && - this.Height == other.Height && - this.Duration == other.Duration && - this.SupportsStreaming == other.SupportsStreaming && - this.HasSpoiler == other.HasSpoiler; - } - - /// - public override int GetHashCode() - { - int hashCode = -1560366449; - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Type); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Media); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Caption); - hashCode = hashCode * -1521134295 + EqualityComparer?>.Default.GetHashCode(this.CaptionEntities); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ParseMode); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Type); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Thumbnail); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Caption); - hashCode = hashCode * -1521134295 + this.Width.GetHashCode(); - hashCode = hashCode * -1521134295 + this.Height.GetHashCode(); - hashCode = hashCode * -1521134295 + this.Duration.GetHashCode(); - hashCode = hashCode * -1521134295 + this.SupportsStreaming.GetHashCode(); - hashCode = hashCode * -1521134295 + this.HasSpoiler.GetHashCode(); - return hashCode; - } - - /// - public static bool operator ==(InputMediaVideo? left, InputMediaVideo? right) - { - return EqualityComparer.Default.Equals(left!, right!); - } - - /// - public static bool operator !=(InputMediaVideo? left, InputMediaVideo? right) - { - return !(left == right); - } } diff --git a/src/library/Telegram.BotAPI/Available Types/Interfaces/ITelegramChat.cs b/src/library/Telegram.BotAPI/Available Types/Interfaces/ITelegramChat.cs new file mode 100644 index 00000000..16b43f92 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/Interfaces/ITelegramChat.cs @@ -0,0 +1,41 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// Defines the basic properties of a Telegram chat. +/// +[Obsolete] +public interface ITelegramChat +{ + /// + /// Unique identifier for this chat. + /// + public long Id { get; set; } + /// + /// Type of chat, can be either “private”, “group”, “supergroup” or “channel”. + /// + public string Type { get; set; } + /// + /// Title, for supergroups, channels and group chats. + /// + public string Title { get; set; } + /// + /// Username, for private chats, supergroups and channels if available. + /// + public string? Username { get; set; } + /// + /// Description, for supergroups and channel chats. + /// + public string? Description { get; set; } + /// + /// Optional. Chat invite link, for supergroups and channel chats. + /// + public string? InviteLink { get; set; } + /// + /// Optional. Unique identifier for the linked chat, i.e. the discussion group identifier for a channel and vice versa; for supergroups and channel chats. + /// + public long? LinkedChatId { get; set; } +} diff --git a/src/Telegram.BotAPI/Available Types/Interfaces/ITelegramUser.cs b/src/library/Telegram.BotAPI/Available Types/Interfaces/ITelegramUser.cs similarity index 85% rename from src/Telegram.BotAPI/Available Types/Interfaces/ITelegramUser.cs rename to src/library/Telegram.BotAPI/Available Types/Interfaces/ITelegramUser.cs index 649f6004..e2b8fcec 100644 --- a/src/Telegram.BotAPI/Available Types/Interfaces/ITelegramUser.cs +++ b/src/library/Telegram.BotAPI/Available Types/Interfaces/ITelegramUser.cs @@ -1,9 +1,12 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI.AvailableTypes; -/// Defines the basic properties of a Telegram user. +/// +/// Defines the basic properties of a Telegram user. +/// +[Obsolete] public interface ITelegramUser { /// Unique identifier for this user or bot. diff --git a/src/library/Telegram.BotAPI/Available Types/LinkPreviewOptions.cs b/src/library/Telegram.BotAPI/Available Types/LinkPreviewOptions.cs new file mode 100644 index 00000000..98fdb1c0 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/LinkPreviewOptions.cs @@ -0,0 +1,45 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// Describes the options used for link preview generation. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class LinkPreviewOptions +{ + /// + /// Optional. True, if the link preview is disabled + /// + [JsonPropertyName(PropertyNames.IsDisabled)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? IsDisabled { get; set; } + /// + /// Optional. URL to use for the link preview. If empty, then the first URL found in the message text will be used + /// + [JsonPropertyName(PropertyNames.Url)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? Url { get; set; } + /// + /// Optional. True, if the media in the link preview is suppposed to be shrunk; ignored if the URL isn't explicitly specified or media size change isn't supported for the preview + /// + [JsonPropertyName(PropertyNames.PreferSmallMedia)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? PreferSmallMedia { get; set; } + /// + /// Optional. True, if the media in the link preview is suppposed to be enlarged; ignored if the URL isn't explicitly specified or media size change isn't supported for the preview + /// + [JsonPropertyName(PropertyNames.PreferLargeMedia)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? PreferLargeMedia { get; set; } + /// + /// Optional. True, if the link preview must be shown above the message text; otherwise, the link preview will be shown below the message text + /// + [JsonPropertyName(PropertyNames.ShowAboveText)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? ShowAboveText { get; set; } +} diff --git a/src/Telegram.BotAPI/Available Types/Location.cs b/src/library/Telegram.BotAPI/Available Types/Location.cs similarity index 95% rename from src/Telegram.BotAPI/Available Types/Location.cs rename to src/library/Telegram.BotAPI/Available Types/Location.cs index c07d6d4d..e560e939 100644 --- a/src/Telegram.BotAPI/Available Types/Location.cs +++ b/src/library/Telegram.BotAPI/Available Types/Location.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; @@ -65,9 +65,7 @@ public override int GetHashCode() /// public static bool operator ==(Location? left, Location? right) { -#pragma warning disable CS8604 // Possible null reference argument. return EqualityComparer.Default.Equals(left!, right!); -#pragma warning restore CS8604 // Possible null reference argument. } /// public static bool operator !=(Location? left, Location? right) diff --git a/src/Telegram.BotAPI/Available Types/LoginUrl.cs b/src/library/Telegram.BotAPI/Available Types/LoginUrl.cs similarity index 99% rename from src/Telegram.BotAPI/Available Types/LoginUrl.cs rename to src/library/Telegram.BotAPI/Available Types/LoginUrl.cs index b72e3689..7f4266bc 100644 --- a/src/Telegram.BotAPI/Available Types/LoginUrl.cs +++ b/src/library/Telegram.BotAPI/Available Types/LoginUrl.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/library/Telegram.BotAPI/Available Types/MaybeInaccessibleMessage.cs b/src/library/Telegram.BotAPI/Available Types/MaybeInaccessibleMessage.cs new file mode 100644 index 00000000..459ee0be --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/MaybeInaccessibleMessage.cs @@ -0,0 +1,35 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using Telegram.BotAPI.Converters; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// This object describes a message that was deleted or is otherwise inaccessible to the bot. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +[System.Text.Json.Serialization.JsonConverter(typeof(MaybeInaccessibleMessageConverter))] +public abstract class MaybeInaccessibleMessage +{ + /// + /// Chat the message belonged to + /// + [JsonPropertyName(PropertyNames.Chat)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public abstract Chat Chat { get; set; } + /// + /// Unique message identifier inside the chat + /// + [JsonPropertyName(PropertyNames.MessageId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public abstract int MessageId { get; set; } + /// + /// Always 0. The field can be used to differentiate regular and inaccessible messages. + /// + [JsonPropertyName(PropertyNames.Date)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public abstract uint Date { get; set; } +} diff --git a/src/Telegram.BotAPI/Available Types/MenuButton/MenuButton.cs b/src/library/Telegram.BotAPI/Available Types/MenuButton/MenuButton.cs similarity index 96% rename from src/Telegram.BotAPI/Available Types/MenuButton/MenuButton.cs rename to src/library/Telegram.BotAPI/Available Types/MenuButton/MenuButton.cs index c038764c..113aed1a 100644 --- a/src/Telegram.BotAPI/Available Types/MenuButton/MenuButton.cs +++ b/src/library/Telegram.BotAPI/Available Types/MenuButton/MenuButton.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/MenuButton/MenuButtonCommands.cs b/src/library/Telegram.BotAPI/Available Types/MenuButton/MenuButtonCommands.cs similarity index 94% rename from src/Telegram.BotAPI/Available Types/MenuButton/MenuButtonCommands.cs rename to src/library/Telegram.BotAPI/Available Types/MenuButton/MenuButtonCommands.cs index 8a6c101a..5006999f 100644 --- a/src/Telegram.BotAPI/Available Types/MenuButton/MenuButtonCommands.cs +++ b/src/library/Telegram.BotAPI/Available Types/MenuButton/MenuButtonCommands.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/MenuButton/MenuButtonDefault.cs b/src/library/Telegram.BotAPI/Available Types/MenuButton/MenuButtonDefault.cs similarity index 94% rename from src/Telegram.BotAPI/Available Types/MenuButton/MenuButtonDefault.cs rename to src/library/Telegram.BotAPI/Available Types/MenuButton/MenuButtonDefault.cs index afa780f7..bdbb29d4 100644 --- a/src/Telegram.BotAPI/Available Types/MenuButton/MenuButtonDefault.cs +++ b/src/library/Telegram.BotAPI/Available Types/MenuButton/MenuButtonDefault.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/MenuButton/MenuButtonType.cs b/src/library/Telegram.BotAPI/Available Types/MenuButton/MenuButtonType.cs similarity index 93% rename from src/Telegram.BotAPI/Available Types/MenuButton/MenuButtonType.cs rename to src/library/Telegram.BotAPI/Available Types/MenuButton/MenuButtonType.cs index 62964f47..da3dab43 100644 --- a/src/Telegram.BotAPI/Available Types/MenuButton/MenuButtonType.cs +++ b/src/library/Telegram.BotAPI/Available Types/MenuButton/MenuButtonType.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI.AvailableTypes; diff --git a/src/Telegram.BotAPI/Available Types/MenuButton/MenuButtonWebApp.cs b/src/library/Telegram.BotAPI/Available Types/MenuButton/MenuButtonWebApp.cs similarity index 97% rename from src/Telegram.BotAPI/Available Types/MenuButton/MenuButtonWebApp.cs rename to src/library/Telegram.BotAPI/Available Types/MenuButton/MenuButtonWebApp.cs index 521d6140..35e0229a 100644 --- a/src/Telegram.BotAPI/Available Types/MenuButton/MenuButtonWebApp.cs +++ b/src/library/Telegram.BotAPI/Available Types/MenuButton/MenuButtonWebApp.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/Message.cs b/src/library/Telegram.BotAPI/Available Types/Message.cs similarity index 55% rename from src/Telegram.BotAPI/Available Types/Message.cs rename to src/library/Telegram.BotAPI/Available Types/Message.cs index d679fd0b..61369a22 100644 --- a/src/Telegram.BotAPI/Available Types/Message.cs +++ b/src/library/Telegram.BotAPI/Available Types/Message.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; @@ -14,26 +14,26 @@ namespace Telegram.BotAPI.AvailableTypes; /// This object represents a message. /// [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public sealed class Message : IEquatable +public class Message : MaybeInaccessibleMessage { /// /// Unique message identifier inside this chat /// [JsonPropertyName(PropertyNames.MessageId)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public int MessageId { get; set; } + public override int MessageId { get; set; } /// - /// Date the message was sent in Unix time + /// Date the message was sent in Unix time. It is always a positive number, representing a valid date. /// [JsonPropertyName(PropertyNames.Date)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public uint Date { get; set; } + public override uint Date { get; set; } /// - /// Conversation the message belongs to + /// Chat the message belongs to /// [JsonPropertyName(PropertyNames.Chat)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public Chat Chat { get; set; } = null!; + public override Chat Chat { get; set; } /// /// Optional. Unique identifier of a message thread to which the message belongs; for supergroups only /// @@ -53,41 +53,11 @@ public sealed class Message : IEquatable [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public Chat? SenderChat { get; set; } /// - /// Optional. For forwarded messages, sender of the original message + /// Optional. Information about the original message for forwarded messages /// - [JsonPropertyName(PropertyNames.ForwardFrom)] + [JsonPropertyName(PropertyNames.ForwardOrigin)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public User? ForwardFrom { get; set; } - /// - /// Optional. For messages forwarded from channels or from anonymous administrators, information about the original sender chat - /// - [JsonPropertyName(PropertyNames.ForwardFromChat)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public Chat? ForwardFromChat { get; set; } - /// - /// Optional. For messages forwarded from channels, identifier of the original message in the channel - /// - [JsonPropertyName(PropertyNames.ForwardFromMessageId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public int? ForwardFromMessageId { get; set; } - /// - /// Optional. For forwarded messages that were originally sent in channels or by an anonymous chat administrator, signature of the message sender if present - /// - [JsonPropertyName(PropertyNames.ForwardSignature)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string? ForwardSignature { get; set; } - /// - /// Optional. Sender's name for messages forwarded from users who disallow adding a link to their account in forwarded messages - /// - [JsonPropertyName(PropertyNames.ForwardSenderName)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string? ForwardSenderName { get; set; } - /// - /// Optional. For forwarded messages, date the original message was sent in Unix time - /// - [JsonPropertyName(PropertyNames.ForwardDate)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public uint? ForwardDate { get; set; } + public MessageOrigin? ForwardOrigin { get; set; } /// /// Optional. True, if the message is sent to a forum topic /// @@ -101,12 +71,24 @@ public sealed class Message : IEquatable [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? IsAutomaticForward { get; set; } /// - /// Optional. For replies, the original message. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply. + /// Optional. For replies in the same chat and message thread, the original message. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply. /// [JsonPropertyName(PropertyNames.ReplyToMessage)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public Message? ReplyToMessage { get; set; } /// + /// Optional. Information about the message that is being replied to, which may come from another chat or forum topic + /// + [JsonPropertyName(PropertyNames.ExternalReply)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ExternalReplyInfo? ExternalReply { get; set; } + /// + /// Optional. For replies that quote part of the original message, the quoted part of the message + /// + [JsonPropertyName(PropertyNames.Quote)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public TextQuote? Quote { get; set; } + /// /// Optional. Bot through which the message was sent /// [JsonPropertyName(PropertyNames.ViaBot)] @@ -147,7 +129,13 @@ public sealed class Message : IEquatable /// [JsonPropertyName(PropertyNames.Entities)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public MessageEntity[]? Entities { get; set; } + public IEnumerable? Entities { get; set; } + /// + /// Optional. Options used for link preview generation for the message, if it is a text message and link preview options were changed + /// + [JsonPropertyName(PropertyNames.LinkPreviewOptions)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public LinkPreviewOptions? LinkPreviewOptions { get; set; } /// /// Optional. Message is an animation, information about the animation. For backward compatibility, when this field is set, the document field will also be set /// @@ -213,7 +201,7 @@ public sealed class Message : IEquatable /// [JsonPropertyName(PropertyNames.CaptionEntities)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public MessageEntity[]? CaptionEntities { get; set; } + public IEnumerable? CaptionEntities { get; set; } /// /// Optional. True, if the message media is covered by a spoiler animation /// @@ -261,7 +249,7 @@ public sealed class Message : IEquatable ///
[JsonPropertyName(PropertyNames.NewChatMembers)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public User[]? NewChatMembers { get; set; } + public IEnumerable? NewChatMembers { get; set; } /// /// Optional. A member was removed from the group, information about them (this member may be the bot itself) /// @@ -279,7 +267,7 @@ public sealed class Message : IEquatable ///
[JsonPropertyName(PropertyNames.NewChatPhoto)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public PhotoSize[]? NewChatPhoto { get; set; } + public IEnumerable? NewChatPhoto { get; set; } /// /// Optional. Service message: the chat photo was deleted /// @@ -315,19 +303,19 @@ public sealed class Message : IEquatable ///
[JsonPropertyName(PropertyNames.MigrateToChatId)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public long? MigrateToChatId { get; set; } + public int? MigrateToChatId { get; set; } /// /// Optional. The supergroup has been migrated from a group with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier. /// [JsonPropertyName(PropertyNames.MigrateFromChatId)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public long? MigrateFromChatId { get; set; } + public int? MigrateFromChatId { get; set; } /// - /// Optional. Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it is itself a reply. + /// Optional. Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply. /// [JsonPropertyName(PropertyNames.PinnedMessage)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public Message? PinnedMessage { get; set; } + public MaybeInaccessibleMessage? PinnedMessage { get; set; } /// /// Optional. Message is an invoice for a payment, information about the invoice. More about payments » /// @@ -341,11 +329,11 @@ public sealed class Message : IEquatable [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public SuccessfulPayment? SuccessfulPayment { get; set; } /// - /// Optional. Service message: a user was shared with the bot + /// Optional. Service message: users were shared with the bot /// - [JsonPropertyName(PropertyNames.UserShared)] + [JsonPropertyName(PropertyNames.UsersShared)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public UserShared? UserShared { get; set; } + public UsersShared? UsersShared { get; set; } /// /// Optional. Service message: a chat was shared with the bot /// @@ -359,7 +347,7 @@ public sealed class Message : IEquatable [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? ConnectedWebsite { get; set; } /// - /// Optional. Service message: the user allowed the bot added to the attachment menu to write messages + /// Optional. Service message: the user allowed the bot to write messages after adding it to the attachment or side menu, launching a Web App from a link, or accepting an explicit request from a Web App sent by the method requestWriteAccess /// [JsonPropertyName(PropertyNames.WriteAccessAllowed)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] @@ -413,6 +401,30 @@ public sealed class Message : IEquatable [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public GeneralForumTopicUnhidden? GeneralForumTopicUnhidden { get; set; } /// + /// Optional. Service message: a scheduled giveaway was created + /// + [JsonPropertyName(PropertyNames.GiveawayCreated)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public GiveawayCreated? GiveawayCreated { get; set; } + /// + /// Optional. The message is a scheduled giveaway message + /// + [JsonPropertyName(PropertyNames.Giveaway)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Giveaway? Giveaway { get; set; } + /// + /// Optional. A giveaway with public winners was completed + /// + [JsonPropertyName(PropertyNames.GiveawayWinners)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public GiveawayWinners? GiveawayWinners { get; set; } + /// + /// Optional. Service message: a giveaway without public winners was completed + /// + [JsonPropertyName(PropertyNames.GiveawayCompleted)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public GiveawayCompleted? GiveawayCompleted { get; set; } + /// /// Optional. Service message: video chat scheduled /// [JsonPropertyName(PropertyNames.VideoChatScheduled)] @@ -448,179 +460,4 @@ public sealed class Message : IEquatable [JsonPropertyName(PropertyNames.ReplyMarkup)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public InlineKeyboardMarkup? ReplyMarkup { get; set; } - - /// - public override bool Equals(object? obj) - { - return this.Equals(obj as Message); - } - - /// - public bool Equals(Message? other) - { - return other is not null && - this.MessageId == other.MessageId && - this.Date == other.Date && - EqualityComparer.Default.Equals(this.Chat, other.Chat) && - this.MessageThreadId == other.MessageThreadId && - EqualityComparer.Default.Equals(this.From, other.From) && - EqualityComparer.Default.Equals(this.SenderChat, other.SenderChat) && - EqualityComparer.Default.Equals(this.ForwardFrom, other.ForwardFrom) && - EqualityComparer.Default.Equals(this.ForwardFromChat, other.ForwardFromChat) && - this.ForwardFromMessageId == other.ForwardFromMessageId && - this.ForwardSignature == other.ForwardSignature && - this.ForwardSenderName == other.ForwardSenderName && - this.ForwardDate == other.ForwardDate && - this.IsTopicMessage == other.IsTopicMessage && - this.IsAutomaticForward == other.IsAutomaticForward && - EqualityComparer.Default.Equals(this.ReplyToMessage, other.ReplyToMessage) && - EqualityComparer.Default.Equals(this.ViaBot, other.ViaBot) && - this.EditDate == other.EditDate && - this.HasProtectedContent == other.HasProtectedContent && - this.MediaGroupId == other.MediaGroupId && - this.AuthorSignature == other.AuthorSignature && - this.Text == other.Text && - EqualityComparer?>.Default.Equals(this.Entities, other.Entities) && - EqualityComparer.Default.Equals(this.Animation, other.Animation) && - EqualityComparer.Default.Equals(this.Audio, other.Audio) && - EqualityComparer.Default.Equals(this.Document, other.Document) && - EqualityComparer?>.Default.Equals(this.Photo, other.Photo) && - EqualityComparer.Default.Equals(this.Sticker, other.Sticker) && - EqualityComparer.Default.Equals(this.Story, other.Story) && - EqualityComparer.Default.Equals(this.Video, other.Video) && - EqualityComparer.Default.Equals(this.VideoNote, other.VideoNote) && - EqualityComparer.Default.Equals(this.Voice, other.Voice) && - this.Caption == other.Caption && - EqualityComparer?>.Default.Equals(this.CaptionEntities, other.CaptionEntities) && - this.HasMediaSpoiler == other.HasMediaSpoiler && - EqualityComparer.Default.Equals(this.Contact, other.Contact) && - EqualityComparer.Default.Equals(this.Dice, other.Dice) && - EqualityComparer.Default.Equals(this.Game, other.Game) && - EqualityComparer.Default.Equals(this.Poll, other.Poll) && - EqualityComparer.Default.Equals(this.Venue, other.Venue) && - EqualityComparer.Default.Equals(this.Location, other.Location) && - EqualityComparer?>.Default.Equals(this.NewChatMembers, other.NewChatMembers) && - EqualityComparer.Default.Equals(this.LeftChatMember, other.LeftChatMember) && - this.NewChatTitle == other.NewChatTitle && - EqualityComparer?>.Default.Equals(this.NewChatPhoto, other.NewChatPhoto) && - this.DeleteChatPhoto == other.DeleteChatPhoto && - this.GroupChatCreated == other.GroupChatCreated && - this.SupergroupChatCreated == other.SupergroupChatCreated && - this.ChannelChatCreated == other.ChannelChatCreated && - EqualityComparer.Default.Equals(this.MessageAutoDeleteTimerChanged, other.MessageAutoDeleteTimerChanged) && - this.MigrateToChatId == other.MigrateToChatId && - this.MigrateFromChatId == other.MigrateFromChatId && - EqualityComparer.Default.Equals(this.PinnedMessage, other.PinnedMessage) && - EqualityComparer.Default.Equals(this.Invoice, other.Invoice) && - EqualityComparer.Default.Equals(this.SuccessfulPayment, other.SuccessfulPayment) && - EqualityComparer.Default.Equals(this.UserShared, other.UserShared) && - EqualityComparer.Default.Equals(this.ChatShared, other.ChatShared) && - this.ConnectedWebsite == other.ConnectedWebsite && - EqualityComparer.Default.Equals(this.WriteAccessAllowed, other.WriteAccessAllowed) && - EqualityComparer.Default.Equals(this.PassportData, other.PassportData) && - EqualityComparer.Default.Equals(this.ProximityAlertTriggered, other.ProximityAlertTriggered) && - EqualityComparer.Default.Equals(this.ForumTopicCreated, other.ForumTopicCreated) && - EqualityComparer.Default.Equals(this.ForumTopicEdited, other.ForumTopicEdited) && - EqualityComparer.Default.Equals(this.ForumTopicClosed, other.ForumTopicClosed) && - EqualityComparer.Default.Equals(this.ForumTopicReopened, other.ForumTopicReopened) && - EqualityComparer.Default.Equals(this.GeneralForumTopicHidden, other.GeneralForumTopicHidden) && - EqualityComparer.Default.Equals(this.GeneralForumTopicUnhidden, other.GeneralForumTopicUnhidden) && - EqualityComparer.Default.Equals(this.VideoChatScheduled, other.VideoChatScheduled) && - EqualityComparer.Default.Equals(this.VideoChatStarted, other.VideoChatStarted) && - EqualityComparer.Default.Equals(this.VideoChatEnded, other.VideoChatEnded) && - EqualityComparer.Default.Equals(this.VideoChatParticipantsInvited, other.VideoChatParticipantsInvited) && - EqualityComparer.Default.Equals(this.WebAppData, other.WebAppData) && - EqualityComparer.Default.Equals(this.ReplyMarkup, other.ReplyMarkup); - } - - /// - public override int GetHashCode() - { - int hashCode = -25731238; - hashCode = hashCode * -1521134295 + this.MessageId.GetHashCode(); - hashCode = hashCode * -1521134295 + this.Date.GetHashCode(); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Chat); - hashCode = hashCode * -1521134295 + this.MessageThreadId.GetHashCode(); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.From); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.SenderChat); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ForwardFrom); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ForwardFromChat); - hashCode = hashCode * -1521134295 + this.ForwardFromMessageId.GetHashCode(); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ForwardSignature); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ForwardSenderName); - hashCode = hashCode * -1521134295 + this.ForwardDate.GetHashCode(); - hashCode = hashCode * -1521134295 + this.IsTopicMessage.GetHashCode(); - hashCode = hashCode * -1521134295 + this.IsAutomaticForward.GetHashCode(); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ReplyToMessage); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ViaBot); - hashCode = hashCode * -1521134295 + this.EditDate.GetHashCode(); - hashCode = hashCode * -1521134295 + this.HasProtectedContent.GetHashCode(); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.MediaGroupId); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.AuthorSignature); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Text); - hashCode = hashCode * -1521134295 + EqualityComparer?>.Default.GetHashCode(this.Entities); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Animation); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Audio); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Document); - hashCode = hashCode * -1521134295 + EqualityComparer?>.Default.GetHashCode(this.Photo); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Sticker); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Story); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Video); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.VideoNote); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Voice); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Caption); - hashCode = hashCode * -1521134295 + EqualityComparer?>.Default.GetHashCode(this.CaptionEntities); - hashCode = hashCode * -1521134295 + this.HasMediaSpoiler.GetHashCode(); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Contact); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Dice); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Game); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Poll); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Venue); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Location); - hashCode = hashCode * -1521134295 + EqualityComparer?>.Default.GetHashCode(this.NewChatMembers); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.LeftChatMember); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.NewChatTitle); - hashCode = hashCode * -1521134295 + EqualityComparer?>.Default.GetHashCode(this.NewChatPhoto); - hashCode = hashCode * -1521134295 + this.DeleteChatPhoto.GetHashCode(); - hashCode = hashCode * -1521134295 + this.GroupChatCreated.GetHashCode(); - hashCode = hashCode * -1521134295 + this.SupergroupChatCreated.GetHashCode(); - hashCode = hashCode * -1521134295 + this.ChannelChatCreated.GetHashCode(); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.MessageAutoDeleteTimerChanged); - hashCode = hashCode * -1521134295 + this.MigrateToChatId.GetHashCode(); - hashCode = hashCode * -1521134295 + this.MigrateFromChatId.GetHashCode(); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.PinnedMessage); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Invoice); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.SuccessfulPayment); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.UserShared); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ChatShared); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ConnectedWebsite); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.WriteAccessAllowed); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.PassportData); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ProximityAlertTriggered); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ForumTopicCreated); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ForumTopicEdited); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ForumTopicClosed); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ForumTopicReopened); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.GeneralForumTopicHidden); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.GeneralForumTopicUnhidden); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.VideoChatScheduled); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.VideoChatStarted); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.VideoChatEnded); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.VideoChatParticipantsInvited); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.WebAppData); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.ReplyMarkup); - return hashCode; - } - - /// - public static bool operator ==(Message? left, Message? right) - { - return EqualityComparer.Default.Equals(left, right); - } - - /// - public static bool operator !=(Message? left, Message? right) - { - return !(left == right); - } } diff --git a/src/Telegram.BotAPI/Available Types/MessageAutoDeleteTimerChanged.cs b/src/library/Telegram.BotAPI/Available Types/MessageAutoDeleteTimerChanged.cs similarity index 97% rename from src/Telegram.BotAPI/Available Types/MessageAutoDeleteTimerChanged.cs rename to src/library/Telegram.BotAPI/Available Types/MessageAutoDeleteTimerChanged.cs index bf1e26f6..f7dadb96 100644 --- a/src/Telegram.BotAPI/Available Types/MessageAutoDeleteTimerChanged.cs +++ b/src/library/Telegram.BotAPI/Available Types/MessageAutoDeleteTimerChanged.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/MessageEntity.cs b/src/library/Telegram.BotAPI/Available Types/MessageEntity.cs similarity index 99% rename from src/Telegram.BotAPI/Available Types/MessageEntity.cs rename to src/library/Telegram.BotAPI/Available Types/MessageEntity.cs index aa3ece3a..9265604d 100644 --- a/src/Telegram.BotAPI/Available Types/MessageEntity.cs +++ b/src/library/Telegram.BotAPI/Available Types/MessageEntity.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/MessageID.cs b/src/library/Telegram.BotAPI/Available Types/MessageID.cs similarity index 97% rename from src/Telegram.BotAPI/Available Types/MessageID.cs rename to src/library/Telegram.BotAPI/Available Types/MessageID.cs index 767d7d47..84a55cdf 100644 --- a/src/Telegram.BotAPI/Available Types/MessageID.cs +++ b/src/library/Telegram.BotAPI/Available Types/MessageID.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/library/Telegram.BotAPI/Available Types/MessageOrigin/MessageOrigin.cs b/src/library/Telegram.BotAPI/Available Types/MessageOrigin/MessageOrigin.cs new file mode 100644 index 00000000..b402fa22 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/MessageOrigin/MessageOrigin.cs @@ -0,0 +1,34 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using Telegram.BotAPI.Converters; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// This object describes the origin of a message. It can be one of: +/// +/// +/// +/// +/// +/// +/// +[System.Text.Json.Serialization.JsonConverter(typeof(MessageOriginConverter))] +public abstract class MessageOrigin +{ + /// + /// Type of the message origin. + /// + [JsonPropertyName(PropertyNames.Type)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public abstract string Type { get; set; } + /// + /// Date the message was sent originally in Unix time + /// + [JsonPropertyName(PropertyNames.Date)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public uint Date { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Available Types/MessageOrigin/MessageOriginChannel.cs b/src/library/Telegram.BotAPI/Available Types/MessageOrigin/MessageOriginChannel.cs new file mode 100644 index 00000000..80b4974b --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/MessageOrigin/MessageOriginChannel.cs @@ -0,0 +1,39 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// The message was originally sent to a channel chat. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class MessageOriginChannel : MessageOrigin +{ + /// + /// Type of the message origin, always “channel” + /// + [JsonPropertyName(PropertyNames.Type)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public override string Type { get; set; } + /// + /// Channel chat to which the message was originally sent + /// + [JsonPropertyName(PropertyNames.Chat)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Chat Chat { get; set; } + /// + /// Unique message identifier inside the chat + /// + [JsonPropertyName(PropertyNames.MessageId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int MessageId { get; set; } + /// + /// Optional. Signature of the original post author + /// + [JsonPropertyName(PropertyNames.AuthorSignature)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? AuthorSignature { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Available Types/MessageOrigin/MessageOriginChat.cs b/src/library/Telegram.BotAPI/Available Types/MessageOrigin/MessageOriginChat.cs new file mode 100644 index 00000000..cc082c1a --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/MessageOrigin/MessageOriginChat.cs @@ -0,0 +1,33 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// The message was originally sent on behalf of a chat to a group chat. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class MessageOriginChat : MessageOrigin +{ + /// + /// Type of the message origin, always “chat” + /// + [JsonPropertyName(PropertyNames.Type)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public override string Type { get; set; } + /// + /// Chat that sent the message originally + /// + [JsonPropertyName(PropertyNames.SenderChat)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Chat SenderChat { get; set; } + /// + /// Optional. For messages originally sent by an anonymous chat administrator, original message author signature + /// + [JsonPropertyName(PropertyNames.AuthorSignature)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? AuthorSignature { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Available Types/MessageOrigin/MessageOriginHiddenUser.cs b/src/library/Telegram.BotAPI/Available Types/MessageOrigin/MessageOriginHiddenUser.cs new file mode 100644 index 00000000..f3879abd --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/MessageOrigin/MessageOriginHiddenUser.cs @@ -0,0 +1,27 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// The message was originally sent by an unknown user. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class MessageOriginHiddenUser : MessageOrigin +{ + /// + /// Type of the message origin, always “hidden_user” + /// + [JsonPropertyName(PropertyNames.Type)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public override string Type { get; set; } + /// + /// Name of the user that sent the message originally + /// + [JsonPropertyName(PropertyNames.SenderUserName)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string SenderUserName { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Available Types/MessageOrigin/MessageOriginUser.cs b/src/library/Telegram.BotAPI/Available Types/MessageOrigin/MessageOriginUser.cs new file mode 100644 index 00000000..64251b76 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/MessageOrigin/MessageOriginUser.cs @@ -0,0 +1,27 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// The message was originally sent by a known user. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class MessageOriginUser : MessageOrigin +{ + /// + /// Type of the message origin, always “user” + /// + [JsonPropertyName(PropertyNames.Type)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public override string Type { get; set; } + /// + /// User that sent the message originally + /// + [JsonPropertyName(PropertyNames.SenderUser)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public User SenderUser { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Available Types/MessageReactionCountUpdated.cs b/src/library/Telegram.BotAPI/Available Types/MessageReactionCountUpdated.cs new file mode 100644 index 00000000..ecb89c5c --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/MessageReactionCountUpdated.cs @@ -0,0 +1,39 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// This object represents reaction changes on a message with anonymous reactions. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class MessageReactionCountUpdated +{ + /// + /// The chat containing the message + /// + [JsonPropertyName(PropertyNames.Chat)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Chat Chat { get; set; } + /// + /// Unique message identifier inside the chat + /// + [JsonPropertyName(PropertyNames.MessageId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int MessageId { get; set; } + /// + /// Date of the change in Unix time + /// + [JsonPropertyName(PropertyNames.Date)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public uint Date { get; set; } + /// + /// List of reactions that are present on the message + /// + [JsonPropertyName(PropertyNames.Reactions)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public IEnumerable Reactions { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Available Types/MessageReactionUpdated.cs b/src/library/Telegram.BotAPI/Available Types/MessageReactionUpdated.cs new file mode 100644 index 00000000..b8e34b0c --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/MessageReactionUpdated.cs @@ -0,0 +1,57 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// This object represents a change of a reaction on a message performed by a user. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class MessageReactionUpdated +{ + /// + /// The chat containing the message the user reacted to + /// + [JsonPropertyName(PropertyNames.Chat)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Chat Chat { get; set; } + /// + /// Unique identifier of the message inside the chat + /// + [JsonPropertyName(PropertyNames.MessageId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int MessageId { get; set; } + /// + /// Date of the change in Unix time + /// + [JsonPropertyName(PropertyNames.Date)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public uint Date { get; set; } + /// + /// Previous list of reaction types that were set by the user + /// + [JsonPropertyName(PropertyNames.OldReaction)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public IEnumerable OldReaction { get; set; } + /// + /// New list of reaction types that have been set by the user + /// + [JsonPropertyName(PropertyNames.NewReaction)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public IEnumerable NewReaction { get; set; } + /// + /// Optional. The user that changed the reaction, if the user isn't anonymous + /// + [JsonPropertyName(PropertyNames.User)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public User? User { get; set; } + /// + /// Optional. The chat on behalf of which the reaction was changed, if the user is anonymous + /// + [JsonPropertyName(PropertyNames.ActorChat)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Chat? ActorChat { get; set; } +} diff --git a/src/Telegram.BotAPI/Available Types/PhotoSize.cs b/src/library/Telegram.BotAPI/Available Types/PhotoSize.cs similarity index 98% rename from src/Telegram.BotAPI/Available Types/PhotoSize.cs rename to src/library/Telegram.BotAPI/Available Types/PhotoSize.cs index a4956aab..05192afc 100644 --- a/src/Telegram.BotAPI/Available Types/PhotoSize.cs +++ b/src/library/Telegram.BotAPI/Available Types/PhotoSize.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/Poll.cs b/src/library/Telegram.BotAPI/Available Types/Poll.cs similarity index 99% rename from src/Telegram.BotAPI/Available Types/Poll.cs rename to src/library/Telegram.BotAPI/Available Types/Poll.cs index 3f495ff1..8b83a39c 100644 --- a/src/Telegram.BotAPI/Available Types/Poll.cs +++ b/src/library/Telegram.BotAPI/Available Types/Poll.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/PollAnswer.cs b/src/library/Telegram.BotAPI/Available Types/PollAnswer.cs similarity index 98% rename from src/Telegram.BotAPI/Available Types/PollAnswer.cs rename to src/library/Telegram.BotAPI/Available Types/PollAnswer.cs index 0efb5a8c..739164b3 100644 --- a/src/Telegram.BotAPI/Available Types/PollAnswer.cs +++ b/src/library/Telegram.BotAPI/Available Types/PollAnswer.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/PollOption.cs b/src/library/Telegram.BotAPI/Available Types/PollOption.cs similarity index 97% rename from src/Telegram.BotAPI/Available Types/PollOption.cs rename to src/library/Telegram.BotAPI/Available Types/PollOption.cs index 465330b5..75963a0c 100644 --- a/src/Telegram.BotAPI/Available Types/PollOption.cs +++ b/src/library/Telegram.BotAPI/Available Types/PollOption.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/ProximityAlertTriggered.cs b/src/library/Telegram.BotAPI/Available Types/ProximityAlertTriggered.cs similarity index 98% rename from src/Telegram.BotAPI/Available Types/ProximityAlertTriggered.cs rename to src/library/Telegram.BotAPI/Available Types/ProximityAlertTriggered.cs index 31f6feaa..222f500a 100644 --- a/src/Telegram.BotAPI/Available Types/ProximityAlertTriggered.cs +++ b/src/library/Telegram.BotAPI/Available Types/ProximityAlertTriggered.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/library/Telegram.BotAPI/Available Types/ReactionCount.cs b/src/library/Telegram.BotAPI/Available Types/ReactionCount.cs new file mode 100644 index 00000000..d96434e2 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/ReactionCount.cs @@ -0,0 +1,27 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// Represents a reaction added to a message along with the number of times it was added. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class ReactionCount +{ + /// + /// Type of the reaction + /// + [JsonPropertyName(PropertyNames.Type)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReactionType Type { get; set; } + /// + /// Number of times the reaction was added + /// + [JsonPropertyName(PropertyNames.TotalCount)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public uint TotalCount { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Available Types/ReactionType/ReactionType.cs b/src/library/Telegram.BotAPI/Available Types/ReactionType/ReactionType.cs new file mode 100644 index 00000000..dd23b5e8 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/ReactionType/ReactionType.cs @@ -0,0 +1,23 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Telegram.BotAPI.Converters; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// This object describes the type of a reaction. Currently, it can be one of: +/// +/// +/// +/// +/// +[JsonConverter(typeof(ReactionTypeConverter))] +public abstract class ReactionType +{ + /// + /// Type of the reaction. + /// + [JsonPropertyName(PropertyNames.Type)] + public abstract string Type { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Available Types/ReactionType/ReactionTypeCustomEmoji.cs b/src/library/Telegram.BotAPI/Available Types/ReactionType/ReactionTypeCustomEmoji.cs new file mode 100644 index 00000000..ad0f84fc --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/ReactionType/ReactionTypeCustomEmoji.cs @@ -0,0 +1,27 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// The reaction is based on a custom emoji. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class ReactionTypeCustomEmoji : ReactionType +{ + /// + /// Type of the reaction, always “custom_emoji” + /// + [JsonPropertyName(PropertyNames.Type)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public override string Type { get; set; } + /// + /// Custom emoji identifier + /// + [JsonPropertyName(PropertyNames.CustomEmoji)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string CustomEmoji { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Available Types/ReactionType/ReactionTypeEmoji.cs b/src/library/Telegram.BotAPI/Available Types/ReactionType/ReactionTypeEmoji.cs new file mode 100644 index 00000000..c7a938cf --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/ReactionType/ReactionTypeEmoji.cs @@ -0,0 +1,27 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// The reaction is based on an emoji. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class ReactionTypeEmoji : ReactionType +{ + /// + /// Type of the reaction, always “emoji” + /// + [JsonPropertyName(PropertyNames.Type)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public override string Type { get; set; } + /// + /// Reaction emoji. Currently, it can be one of "👍", "👎", "❤", "🔥", "🥰", "👏", "😁", "🤔", "🤯", "😱", "🤬", "😢", "🎉", "🤩", "🤮", "💩", "🙏", "👌", "🕊", "🤡", "🥱", "🥴", "😍", "🐳", "❤‍🔥", "🌚", "🌭", "💯", "🤣", "⚡", "🍌", "🏆", "💔", "🤨", "😐", "🍓", "🍾", "💋", "🖕", "😈", "😴", "😭", "🤓", "👻", "👨‍💻", "👀", "🎃", "🙈", "😇", "😨", "🤝", "✍", "🤗", "🫡", "🎅", "🎄", "☃", "💅", "🤪", "🗿", "🆒", "💘", "🙉", "🦄", "😘", "💊", "🙊", "😎", "👾", "🤷‍♂", "🤷", "🤷‍♀", "😡" + /// + [JsonPropertyName(PropertyNames.Emoji)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string Emoji { get; set; } +} diff --git a/src/Telegram.BotAPI/Available Types/ReplyMarkup/InlineKeyboardButton.cs b/src/library/Telegram.BotAPI/Available Types/ReplyMarkup/InlineKeyboardButton.cs similarity index 64% rename from src/Telegram.BotAPI/Available Types/ReplyMarkup/InlineKeyboardButton.cs rename to src/library/Telegram.BotAPI/Available Types/ReplyMarkup/InlineKeyboardButton.cs index 9656e870..86a9c54e 100644 --- a/src/Telegram.BotAPI/Available Types/ReplyMarkup/InlineKeyboardButton.cs +++ b/src/library/Telegram.BotAPI/Available Types/ReplyMarkup/InlineKeyboardButton.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; @@ -98,91 +98,6 @@ public InlineKeyboardButton(string text) [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? Pay { get; set; } - /// Button Type. - [System.Text.Json.Serialization.JsonIgnore] - [Newtonsoft.Json.JsonIgnore] - [Obsolete("Use InlineKeyboardButtonExtensions.GetButtonType instead.")] - public InlineKeyboardButtonType Type => this.GetButtonType(); - - /// Create a new with a url. - /// Button text. - /// Url. - /// - [Obsolete("Use InlineButtonBuilder.SetUrl instead.")] - public static InlineKeyboardButton SetUrl(string text, string url) - { - return new InlineKeyboardButton(text) { Url = url }; - } - - /// Create a new with a . - /// Button text. - /// A - /// - [Obsolete("Use InlineButtonBuilder.SetLoginUrl instead.")] - public static InlineKeyboardButton SetLoginUrl(string text, LoginUrl loginUrl) - { - return new InlineKeyboardButton(text) { LoginUrl = loginUrl }; - } - - /// Create a new with a Callback data. - /// Button text. - /// Callback data. - /// - [Obsolete("Use InlineButtonBuilder.SetCallbackData instead.")] - public static InlineKeyboardButton SetCallbackData(string text, string callbackData) - { - return new InlineKeyboardButton(text) { CallbackData = callbackData }; - } - - /// Create a new with a inline query. - /// Button text. - /// Inline query. - /// - [Obsolete("Use InlineButtonBuilder.SetSwitchInlineQuery instead.")] - public static InlineKeyboardButton SetSwitchInlineQuery(string text, string switchInlineQuery) - { - return new InlineKeyboardButton(text) { SwitchInlineQuery = switchInlineQuery }; - } - - /// Create a new with a inline query for the current chat. - /// Button text. - /// Inline query. - /// - [Obsolete("Use InlineButtonBuilder.SetSwitchInlineQueryCurrentChat instead.")] - public static InlineKeyboardButton SetSwitchInlineQueryCurrentChat(string text, string switchInlineQueryCurrentChat) - { - return new InlineKeyboardButton(text) { SwitchInlineQueryCurrentChat = switchInlineQueryCurrentChat }; - } - - /// Create a new with a callback game. - /// Button text. - /// Callback game. - /// - [Obsolete("Use InlineButtonBuilder.SetCallbackGame instead.")] - public static InlineKeyboardButton SetCallbackGame(string text, CallbackGame callbackGame) - { - return new InlineKeyboardButton(text) { CallbackGame = callbackGame }; - } - - /// Create a new for pay. - /// Button text. - /// - [Obsolete("Use InlineButtonBuilder.SetPay instead.")] - public static InlineKeyboardButton SetPay(string text) - { - return new InlineKeyboardButton(text) { Pay = true }; - } - - /// Create a new for pay. - /// Button text. - /// Description of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method answerWebAppQuery. Available only in private chats between a user and the bot. - /// - [Obsolete("Use InlineButtonBuilder.SetWebApp instead.")] - public static InlineKeyboardButton SetWebApp(string text, WebAppInfo webApp) - { - return new InlineKeyboardButton(text) { WebApp = webApp }; - } - /// public override bool Equals(object? obj) { diff --git a/src/Telegram.BotAPI/Available Types/ReplyMarkup/InlineKeyboardMarkup.cs b/src/library/Telegram.BotAPI/Available Types/ReplyMarkup/InlineKeyboardMarkup.cs similarity index 98% rename from src/Telegram.BotAPI/Available Types/ReplyMarkup/InlineKeyboardMarkup.cs rename to src/library/Telegram.BotAPI/Available Types/ReplyMarkup/InlineKeyboardMarkup.cs index e75b8b71..ef6775fc 100644 --- a/src/Telegram.BotAPI/Available Types/ReplyMarkup/InlineKeyboardMarkup.cs +++ b/src/library/Telegram.BotAPI/Available Types/ReplyMarkup/InlineKeyboardMarkup.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButton.cs b/src/library/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButton.cs similarity index 53% rename from src/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButton.cs rename to src/library/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButton.cs index 3e4e82b9..2b3d6da9 100644 --- a/src/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButton.cs +++ b/src/library/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButton.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; @@ -6,29 +6,25 @@ namespace Telegram.BotAPI.AvailableTypes; -/// This object represents one button of the reply keyboard. For simple text buttons String can be used instead of this object to specify text of the button. Optional fields are mutually exclusive. +/// +/// This object represents one button of the reply keyboard. For simple text buttons, String can be used instead of this object to specify the button text. The optional fields web_app, request_user, request_chat, request_contact, request_location, and request_poll are mutually exclusive. +/// +/// Text of the button. If none of the optional fields are used, it will be sent as a message when the button is pressed. [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public sealed class KeyboardButton : IEquatable +public class KeyboardButton(string text) { - /// Creates a new keyboard button. - /// Text of the button. If none of the optional fields are used, it will be sent as a message when the button is pressed. - public KeyboardButton(string text) - { - this.Text = text; - } - /// /// Text of the button. If none of the optional fields are used, it will be sent as a message when the button is pressed /// [JsonPropertyName(PropertyNames.Text)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string Text { get; set; } + public string Text { get; set; } = text; /// - /// Optional. If specified, pressing the button will open a list of suitable users. Tapping on any user will send their identifier to the bot in a “user_shared” service message. Available in private chats only. + /// Optional. If specified, pressing the button will open a list of suitable users. Identifiers of selected users will be sent to the bot in a “users_shared” service message. Available in private chats only. /// - [JsonPropertyName(PropertyNames.RequestUser)] + [JsonPropertyName(PropertyNames.RequestUsers)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public KeyboardButtonRequestUser? RequestUser { get; set; } + public KeyboardButtonRequestUsers? RequestUsers { get; set; } /// /// Optional. If specified, pressing the button will open a list of suitable chats. Tapping on a chat will send its identifier to the bot in a “chat_shared” service message. Available in private chats only. /// @@ -60,44 +56,14 @@ public KeyboardButton(string text) [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public WebAppInfo? WebApp { get; set; } - /// - public override bool Equals(object? obj) - { - return this.Equals(obj as KeyboardButton); - } - /// - public bool Equals(KeyboardButton? other) - { - return other is not null && - this.Text == other.Text && - EqualityComparer.Default.Equals(this.RequestUser, other.RequestUser) && - EqualityComparer.Default.Equals(this.RequestChat, other.RequestChat) && - this.RequestContact == other.RequestContact && - this.RequestLocation == other.RequestLocation && - EqualityComparer.Default.Equals(this.RequestPoll, other.RequestPoll) && - EqualityComparer.Default.Equals(this.WebApp, other.WebApp); - } - /// - public override int GetHashCode() - { - int hashCode = 1592818789; - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.Text); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.RequestUser); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.RequestChat); - hashCode = hashCode * -1521134295 + this.RequestContact.GetHashCode(); - hashCode = hashCode * -1521134295 + this.RequestLocation.GetHashCode(); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.RequestPoll); - hashCode = hashCode * -1521134295 + EqualityComparer.Default.GetHashCode(this.WebApp); - return hashCode; - } - /// - public static bool operator ==(KeyboardButton? left, KeyboardButton? right) - { - return EqualityComparer.Default.Equals(left, right); - } - /// - public static bool operator !=(KeyboardButton? left, KeyboardButton? right) - { - return !(left == right); - } + /// + /// Optional. If specified, pressing the button will open a list of suitable users. Tapping on any user will send their identifier to the bot in a “user_shared” service message. Available in private chats only. + /// + /// + /// This property is only here for backward compatibility. Use RequestUsers instead. + /// + [JsonPropertyName(PropertyNames.RequestUser)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + [Obsolete("Use RequestUsers instead")] + public KeyboardButtonRequestUser? RequestUser { get; set; } } diff --git a/src/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButtonPollType.cs b/src/library/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButtonPollType.cs similarity index 97% rename from src/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButtonPollType.cs rename to src/library/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButtonPollType.cs index f84b08dd..8d151835 100644 --- a/src/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButtonPollType.cs +++ b/src/library/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButtonPollType.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButtonRequestChat.cs b/src/library/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButtonRequestChat.cs similarity index 98% rename from src/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButtonRequestChat.cs rename to src/library/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButtonRequestChat.cs index 14449599..2da99ab6 100644 --- a/src/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButtonRequestChat.cs +++ b/src/library/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButtonRequestChat.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/library/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButtonRequestUser.cs b/src/library/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButtonRequestUser.cs new file mode 100644 index 00000000..766cad64 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButtonRequestUser.cs @@ -0,0 +1,16 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// This object defines the criteria used to request a suitable user. The identifier of the selected user will be shared with the bot when the corresponding button is pressed. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +[Obsolete("Replace by KeyboardButtonRequestUsers")] +public sealed class KeyboardButtonRequestUser(int requestId) : KeyboardButtonRequestUsers(requestId) +{ +} diff --git a/src/library/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButtonRequestUsers.cs b/src/library/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButtonRequestUsers.cs new file mode 100644 index 00000000..fe5341e4 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/ReplyMarkup/KeyboardButtonRequestUsers.cs @@ -0,0 +1,40 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// This object defines the criteria used to request suitable users. The identifiers of the selected users will be shared with the bot when the corresponding button is pressed. More about requesting users » +/// +/// Signed 32-bit identifier of the request that will be received back in the UsersShared object. Must be unique within the message +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class KeyboardButtonRequestUsers(int requestId) +{ + /// + /// Signed 32-bit identifier of the request that will be received back in the UsersShared object. Must be unique within the message + /// + [JsonPropertyName(PropertyNames.RequestId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int RequestId { get; set; } = requestId; + /// + /// Optional. Pass True to request bots, pass False to request regular users. If not specified, no additional restrictions are applied. + /// + [JsonPropertyName(PropertyNames.UserIsBot)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? UserIsBot { get; set; } + /// + /// Optional. Pass True to request premium users, pass False to request non-premium users. If not specified, no additional restrictions are applied. + /// + [JsonPropertyName(PropertyNames.UserIsPremium)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? UserIsPremium { get; set; } + /// + /// Optional. The maximum number of users to be selected; 1-10. Defaults to 1. + /// + [JsonPropertyName(PropertyNames.MaxQuantity)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ushort? MaxQuantity { get; set; } +} diff --git a/src/Telegram.BotAPI/Available Types/ReplyMarkup/ReplyKeyboardMarkup.cs b/src/library/Telegram.BotAPI/Available Types/ReplyMarkup/ReplyKeyboardMarkup.cs similarity index 99% rename from src/Telegram.BotAPI/Available Types/ReplyMarkup/ReplyKeyboardMarkup.cs rename to src/library/Telegram.BotAPI/Available Types/ReplyMarkup/ReplyKeyboardMarkup.cs index b10c0688..3e94df14 100644 --- a/src/Telegram.BotAPI/Available Types/ReplyMarkup/ReplyKeyboardMarkup.cs +++ b/src/library/Telegram.BotAPI/Available Types/ReplyMarkup/ReplyKeyboardMarkup.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. diff --git a/src/Telegram.BotAPI/Available Types/ReplyMarkup/ReplyKeyboardRemove.cs b/src/library/Telegram.BotAPI/Available Types/ReplyMarkup/ReplyKeyboardRemove.cs similarity index 98% rename from src/Telegram.BotAPI/Available Types/ReplyMarkup/ReplyKeyboardRemove.cs rename to src/library/Telegram.BotAPI/Available Types/ReplyMarkup/ReplyKeyboardRemove.cs index 2ed2cffd..4e8942a6 100644 --- a/src/Telegram.BotAPI/Available Types/ReplyMarkup/ReplyKeyboardRemove.cs +++ b/src/library/Telegram.BotAPI/Available Types/ReplyMarkup/ReplyKeyboardRemove.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/ReplyMarkup/ReplyMarkup.cs b/src/library/Telegram.BotAPI/Available Types/ReplyMarkup/ReplyMarkup.cs similarity index 88% rename from src/Telegram.BotAPI/Available Types/ReplyMarkup/ReplyMarkup.cs rename to src/library/Telegram.BotAPI/Available Types/ReplyMarkup/ReplyMarkup.cs index 2308cfa2..fb6f15c1 100644 --- a/src/Telegram.BotAPI/Available Types/ReplyMarkup/ReplyMarkup.cs +++ b/src/library/Telegram.BotAPI/Available Types/ReplyMarkup/ReplyMarkup.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Telegram.BotAPI.Converters; diff --git a/src/library/Telegram.BotAPI/Available Types/ReplyParameters.cs b/src/library/Telegram.BotAPI/Available Types/ReplyParameters.cs new file mode 100644 index 00000000..0dd1f0e4 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/ReplyParameters.cs @@ -0,0 +1,58 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// Describes reply parameters for the message that is being sent. +/// +/// Identifier of the message that will be replied to in the current chat, or in the chat chat_id if it is specified +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class ReplyParameters(int messageId) +{ + /// + /// Identifier of the message that will be replied to in the current chat, or in the chat chat_id if it is specified + /// + [JsonPropertyName(PropertyNames.MessageId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int MessageId { get; } = messageId; + /// + /// Optional. If the message to be replied to is from a different chat, unique identifier for the chat or username of the channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object? ChatId { get; set; } + /// + /// Optional. Pass True if the message should be sent even if the specified message to be replied to is not found; can be used only for replies in the same chat and forum topic. + /// + [JsonPropertyName(PropertyNames.AllowSendingWithoutReply)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? AllowSendingWithoutReply { get; set; } + /// + /// Optional. Quoted part of the message to be replied to; 0-1024 characters after entities parsing. The quote must be an exact substring of the message to be replied to, including bold, italic, underline, strikethrough, spoiler, and custom_emoji entities. The message will fail to send if the quote isn't found in the original message. + /// + [JsonPropertyName(PropertyNames.Quote)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? Quote { get; set; } + /// + /// Optional. Mode for parsing entities in the quote. See formatting options for more details. + /// + [JsonPropertyName(PropertyNames.QuoteParseMode)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? QuoteParseMode { get; set; } + /// + /// Optional. A JSON-serialized list of special entities that appear in the quote. It can be specified instead of quote_parse_mode. + /// + [JsonPropertyName(PropertyNames.QuoteEntities)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public IEnumerable? QuoteEntities { get; set; } + /// + /// Optional. Position of the quote in the original message in UTF-16 code units + /// + [JsonPropertyName(PropertyNames.QuotePosition)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public uint? QuotePosition { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Available Types/ResponseParameters.cs b/src/library/Telegram.BotAPI/Available Types/ResponseParameters.cs new file mode 100644 index 00000000..89a01928 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/ResponseParameters.cs @@ -0,0 +1,27 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// Contains information about why a request was unsuccessful. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public sealed class ResponseParameters +{ + /// + /// Optional. The group has been migrated to a supergroup with the specified identifier. This number may be greater than 32 bits and some programming languages may have difficulty/silent defects in interpreting it. But it is smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this identifier. + /// + [JsonPropertyName(PropertyNames.MigrateToChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public long MigrateToChatId { get; set; } + /// + /// Optional. In case of exceeding flood control, the number of seconds left to wait before the request can be repeated. + /// + [JsonPropertyName(PropertyNames.RetryAfter)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public uint? RetryAfter { get; set; } +} diff --git a/src/Telegram.BotAPI/Available Types/Story.cs b/src/library/Telegram.BotAPI/Available Types/Story.cs similarity index 92% rename from src/Telegram.BotAPI/Available Types/Story.cs rename to src/library/Telegram.BotAPI/Available Types/Story.cs index 4ad44e89..ec7207e5 100644 --- a/src/Telegram.BotAPI/Available Types/Story.cs +++ b/src/library/Telegram.BotAPI/Available Types/Story.cs @@ -1,8 +1,8 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. -using Newtonsoft.Json.Serialization; using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; namespace Telegram.BotAPI.AvailableTypes; diff --git a/src/Telegram.BotAPI/Available Types/SwitchInlineQueryChosenChat.cs b/src/library/Telegram.BotAPI/Available Types/SwitchInlineQueryChosenChat.cs similarity index 97% rename from src/Telegram.BotAPI/Available Types/SwitchInlineQueryChosenChat.cs rename to src/library/Telegram.BotAPI/Available Types/SwitchInlineQueryChosenChat.cs index 0b1e584d..49d64b31 100644 --- a/src/Telegram.BotAPI/Available Types/SwitchInlineQueryChosenChat.cs +++ b/src/library/Telegram.BotAPI/Available Types/SwitchInlineQueryChosenChat.cs @@ -1,8 +1,8 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. -using Newtonsoft.Json.Serialization; using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; namespace Telegram.BotAPI.AvailableTypes; diff --git a/src/library/Telegram.BotAPI/Available Types/TextQuote.cs b/src/library/Telegram.BotAPI/Available Types/TextQuote.cs new file mode 100644 index 00000000..4c2faf04 --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/TextQuote.cs @@ -0,0 +1,39 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// This object contains information about the quoted part of a message that is replied to by the given message. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class TextQuote +{ + /// + /// Text of the quoted part of a message that is replied to by the given message + /// + [JsonPropertyName(PropertyNames.Text)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string Text { get; set; } + /// + /// Approximate quote position in the original message in UTF-16 code units as specified by the sender + /// + [JsonPropertyName(PropertyNames.Position)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public uint Position { get; set; } + /// + /// Optional. Special entities that appear in the quote. Currently, only bold, italic, underline, strikethrough, spoiler, and custom_emoji entities are kept in quotes. + /// + [JsonPropertyName(PropertyNames.Entities)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public IEnumerable? Entities { get; set; } + /// + /// Optional. True, if the quote was chosen manually by the message sender. Otherwise, the quote was added automatically by the server. + /// + [JsonPropertyName(PropertyNames.IsManual)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? IsManual { get; set; } +} diff --git a/src/Telegram.BotAPI/Available Types/User.cs b/src/library/Telegram.BotAPI/Available Types/User.cs similarity index 99% rename from src/Telegram.BotAPI/Available Types/User.cs rename to src/library/Telegram.BotAPI/Available Types/User.cs index 62051e0a..a387f6bf 100644 --- a/src/Telegram.BotAPI/Available Types/User.cs +++ b/src/library/Telegram.BotAPI/Available Types/User.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/UserProfilePhotos.cs b/src/library/Telegram.BotAPI/Available Types/UserProfilePhotos.cs similarity index 97% rename from src/Telegram.BotAPI/Available Types/UserProfilePhotos.cs rename to src/library/Telegram.BotAPI/Available Types/UserProfilePhotos.cs index b35619c7..31399bc1 100644 --- a/src/Telegram.BotAPI/Available Types/UserProfilePhotos.cs +++ b/src/library/Telegram.BotAPI/Available Types/UserProfilePhotos.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/UserShared.cs b/src/library/Telegram.BotAPI/Available Types/UserShared.cs similarity index 97% rename from src/Telegram.BotAPI/Available Types/UserShared.cs rename to src/library/Telegram.BotAPI/Available Types/UserShared.cs index a3762e88..60975db7 100644 --- a/src/Telegram.BotAPI/Available Types/UserShared.cs +++ b/src/library/Telegram.BotAPI/Available Types/UserShared.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/library/Telegram.BotAPI/Available Types/UsersShared.cs b/src/library/Telegram.BotAPI/Available Types/UsersShared.cs new file mode 100644 index 00000000..df141f1b --- /dev/null +++ b/src/library/Telegram.BotAPI/Available Types/UsersShared.cs @@ -0,0 +1,27 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Telegram.BotAPI.AvailableTypes; + +/// +/// This object contains information about the users whose identifiers were shared with the bot using a KeyboardButtonRequestUsers button. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class UsersShared +{ + /// + /// Identifier of the request + /// + [JsonPropertyName(PropertyNames.RequestId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int RequestId { get; set; } + /// + /// Identifiers of the shared users. These numbers may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting them. But they have at most 52 significant bits, so 64-bit integers or double-precision float types are safe for storing these identifiers. The bot may not have access to the users and could be unable to use these identifiers, unless the users are already known to the bot by some other means. + /// + [JsonPropertyName(PropertyNames.UserIds)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public IEnumerable UserIds { get; set; } +} diff --git a/src/Telegram.BotAPI/Available Types/Venue.cs b/src/library/Telegram.BotAPI/Available Types/Venue.cs similarity index 98% rename from src/Telegram.BotAPI/Available Types/Venue.cs rename to src/library/Telegram.BotAPI/Available Types/Venue.cs index 0839ccb7..c0db37b0 100644 --- a/src/Telegram.BotAPI/Available Types/Venue.cs +++ b/src/library/Telegram.BotAPI/Available Types/Venue.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/Video.cs b/src/library/Telegram.BotAPI/Available Types/Video.cs similarity index 99% rename from src/Telegram.BotAPI/Available Types/Video.cs rename to src/library/Telegram.BotAPI/Available Types/Video.cs index 1304e92c..19af1f09 100644 --- a/src/Telegram.BotAPI/Available Types/Video.cs +++ b/src/library/Telegram.BotAPI/Available Types/Video.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/VideoChatEnded.cs b/src/library/Telegram.BotAPI/Available Types/VideoChatEnded.cs similarity index 97% rename from src/Telegram.BotAPI/Available Types/VideoChatEnded.cs rename to src/library/Telegram.BotAPI/Available Types/VideoChatEnded.cs index f179d20f..7324c57c 100644 --- a/src/Telegram.BotAPI/Available Types/VideoChatEnded.cs +++ b/src/library/Telegram.BotAPI/Available Types/VideoChatEnded.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/VideoChatParticipantsInvited.cs b/src/library/Telegram.BotAPI/Available Types/VideoChatParticipantsInvited.cs similarity index 97% rename from src/Telegram.BotAPI/Available Types/VideoChatParticipantsInvited.cs rename to src/library/Telegram.BotAPI/Available Types/VideoChatParticipantsInvited.cs index fe2faa12..1e421851 100644 --- a/src/Telegram.BotAPI/Available Types/VideoChatParticipantsInvited.cs +++ b/src/library/Telegram.BotAPI/Available Types/VideoChatParticipantsInvited.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/VideoChatScheduled.cs b/src/library/Telegram.BotAPI/Available Types/VideoChatScheduled.cs similarity index 97% rename from src/Telegram.BotAPI/Available Types/VideoChatScheduled.cs rename to src/library/Telegram.BotAPI/Available Types/VideoChatScheduled.cs index 5a6fa2bf..342bfc9d 100644 --- a/src/Telegram.BotAPI/Available Types/VideoChatScheduled.cs +++ b/src/library/Telegram.BotAPI/Available Types/VideoChatScheduled.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/VideoChatStarted.cs b/src/library/Telegram.BotAPI/Available Types/VideoChatStarted.cs similarity index 92% rename from src/Telegram.BotAPI/Available Types/VideoChatStarted.cs rename to src/library/Telegram.BotAPI/Available Types/VideoChatStarted.cs index 9e553e58..bbf3449c 100644 --- a/src/Telegram.BotAPI/Available Types/VideoChatStarted.cs +++ b/src/library/Telegram.BotAPI/Available Types/VideoChatStarted.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/VideoNote.cs b/src/library/Telegram.BotAPI/Available Types/VideoNote.cs similarity index 98% rename from src/Telegram.BotAPI/Available Types/VideoNote.cs rename to src/library/Telegram.BotAPI/Available Types/VideoNote.cs index 5a1a7863..87162853 100644 --- a/src/Telegram.BotAPI/Available Types/VideoNote.cs +++ b/src/library/Telegram.BotAPI/Available Types/VideoNote.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/Voice.cs b/src/library/Telegram.BotAPI/Available Types/Voice.cs similarity index 93% rename from src/Telegram.BotAPI/Available Types/Voice.cs rename to src/library/Telegram.BotAPI/Available Types/Voice.cs index 5a7e26e8..354df739 100644 --- a/src/Telegram.BotAPI/Available Types/Voice.cs +++ b/src/library/Telegram.BotAPI/Available Types/Voice.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; @@ -59,9 +59,7 @@ public override int GetHashCode() /// public static bool operator ==(Voice? left, Voice? right) { -#pragma warning disable CS8604 // Possible null reference argument. return EqualityComparer.Default.Equals(left!, right!); -#pragma warning restore CS8604 // Possible null reference argument. } /// public static bool operator !=(Voice? left, Voice? right) diff --git a/src/Telegram.BotAPI/Available Types/WebAppData.cs b/src/library/Telegram.BotAPI/Available Types/WebAppData.cs similarity index 96% rename from src/Telegram.BotAPI/Available Types/WebAppData.cs rename to src/library/Telegram.BotAPI/Available Types/WebAppData.cs index 9f809dd4..ed6091a9 100644 --- a/src/Telegram.BotAPI/Available Types/WebAppData.cs +++ b/src/library/Telegram.BotAPI/Available Types/WebAppData.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/WebAppInfo.cs b/src/library/Telegram.BotAPI/Available Types/WebAppInfo.cs similarity index 97% rename from src/Telegram.BotAPI/Available Types/WebAppInfo.cs rename to src/library/Telegram.BotAPI/Available Types/WebAppInfo.cs index 1922e5cf..82c799b4 100644 --- a/src/Telegram.BotAPI/Available Types/WebAppInfo.cs +++ b/src/library/Telegram.BotAPI/Available Types/WebAppInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Available Types/WriteAccessAllowed.cs b/src/library/Telegram.BotAPI/Available Types/WriteAccessAllowed.cs similarity index 97% rename from src/Telegram.BotAPI/Available Types/WriteAccessAllowed.cs rename to src/library/Telegram.BotAPI/Available Types/WriteAccessAllowed.cs index e875b06e..5fb72733 100644 --- a/src/Telegram.BotAPI/Available Types/WriteAccessAllowed.cs +++ b/src/library/Telegram.BotAPI/Available Types/WriteAccessAllowed.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/library/Telegram.BotAPI/BotClient.Deprecated.cs b/src/library/Telegram.BotAPI/BotClient.Deprecated.cs new file mode 100644 index 00000000..0e18f91e --- /dev/null +++ b/src/library/Telegram.BotAPI/BotClient.Deprecated.cs @@ -0,0 +1,153 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System.IO; +using System.Net.Http; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace Telegram.BotAPI; + +public sealed partial class BotClient : TelegramBotClient +{ + /// + /// Default HttpClient for bot requets. + /// + [Obsolete] + public static HttpClient? DefaultHttpClient { get; private set; } + + /// + /// Set the default HttpClient for bot requets. + /// + /// for http requets. + /// Thrown when client is null. + [Obsolete] + public static HttpClient SetHttpClient(HttpClient? client = null) + { + DefaultHttpClient = client ?? new HttpClient(); + return DefaultHttpClient; + } + + /// + /// Makes a bot request using HTTP GET and returns the response. + /// + /// Response type. + /// Method name. See + /// + [Obsolete("Use IBotClient.CallApi instead.")] + public BotResponse GetRequest(string method) => this.GetRequestAsync(method).GetAwaiter().GetResult(); + + /// + /// Makes a bot request using HTTP GET and returns the response. + /// + /// Response type., + /// Method name. See + /// The cancellation token to cancel operation. + /// + [Obsolete("Use ITelegramBotClient.CallApiAsync instead.")] + public Task> GetRequestAsync(string method, CancellationToken cancellationToken = default) => ((ITelegramBotClient)this).CallMethodDirectAsync(method, cancellationToken: cancellationToken); + + /// Makes a bot request using HTTP POST and returns the response. + /// Response type. + /// Method name. See + /// json parameters + /// Options to control serialization behavior. + /// + [Obsolete("Use IBotClient.CallApi instead.")] + public BotResponse PostRequest(string method, object args, [Optional] JsonSerializerOptions serializeOptions) => this.PostRequestAsync(method, args, serializeOptions).Result; + + /// Makes a bot request using HTTP POST and returns the response. + /// Response type. + /// Method name. See + /// json parameters + /// Options to control serialization behavior. + /// The cancellation token to cancel operation. + /// + [Obsolete("Use ITelegramBotClient.CallApiAsync instead.")] + public async Task> PostRequestAsync(string method, object args, [Optional] JsonSerializerOptions? serializeOptions, CancellationToken cancellationToken = default) + { + var stream = await Tools.SerializeAsStreamAsync(args, serializeOptions ?? SerializerOptions, cancellationToken).ConfigureAwait(false); + return await this.PostRequestAsync(method, stream, cancellationToken).ConfigureAwait(false); + } + + /// Makes a bot request using HTTP POST and returns the response. + /// Response type. + /// Method name. See + /// json parameters + /// + [Obsolete("Use IBotClient.CallApi instead.")] + public BotResponse PostRequest(string method, Stream args) + { + var response = this.PostRequestAsync(method, args); + try + { + return response.Result; + } + catch (AggregateException exp) + { + throw exp.InnerException; + } + } + + /// Makes a bot request using HTTP POST and returns the response. + /// Response type. + /// Method name. See + /// json parameters + /// The cancellation token to cancel operation. + /// + [Obsolete("Use ITelegramBotClient.CallApiAsync instead.")] + public Task> PostRequestAsync(string method, Stream args, CancellationToken cancellationToken = default) => ((ITelegramBotClient)this).CallMethodDirectAsync(method, args, cancellationToken); + + /// Makes a bot request using HTTP POST and Multipart Form Data and returns the response. + /// Response type. + /// Method name. See . + /// Parameters encoded using multipart/form-data. + /// The cancellation token to cancel operation. + /// + [Obsolete("Use ITelegramBotClient.CallApiAsync instead.")] + public async Task> PostRequestAsyncMultipartFormData(string method, MultipartFormDataContent args, CancellationToken cancellationToken) + { + using var request = new HttpRequestMessage(HttpMethod.Post, this.BuildUrl(method)) + { + Content = args + }; + return await this.SendRequestAsync(request, cancellationToken).ConfigureAwait(false); + } + + internal async Task> SendRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var response = await this.httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); + try + { + response.EnsureSuccessStatusCode(); + var streamResponse = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + var botResponse = await JsonSerializer.DeserializeAsync>(streamResponse, SerializerOptions, cancellationToken: cancellationToken); + return botResponse!; + } + catch (HttpRequestException) + { + if (response.Content.Headers.ContentType.MediaType == "application/json") + { + var streamResponse = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + var botResponse = await JsonSerializer.DeserializeAsync>(streamResponse, SerializerOptions, cancellationToken: cancellationToken); + return botResponse!; + } + else + { + throw; + } + } + } + + /// + /// Build the url for the request. + /// + /// The method name. + /// The url for the request. + private string BuildUrl(string method) + { + var prefix = this.UseTestEnvironment ? "/test" : string.Empty; + return $"{this.ServerAddress}/bot{this.Token}{prefix}/{method}"; + } +} diff --git a/src/Telegram.BotAPI/BotClient.cs b/src/library/Telegram.BotAPI/BotClient.cs similarity index 55% rename from src/Telegram.BotAPI/BotClient.cs rename to src/library/Telegram.BotAPI/BotClient.cs index 06ddae80..4e26c62a 100644 --- a/src/Telegram.BotAPI/BotClient.cs +++ b/src/library/Telegram.BotAPI/BotClient.cs @@ -1,45 +1,44 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. -#region AUTHOR -//-------------------------------------------------------------------------- -// @author: Quetzal Rivera @email: QuetzalDeveloper@outlook.com -// Project name: Telegram.BotAPI Date of creation: 13-12-2019 -// Description: Library to access and interact with the Telegram Bot API. -// Review History: -// Creation: Creation | Date: 13-12-2019 -// ________________________________________________________________________ -//-------------------------------------------------------------------------- -#endregion - using System.Net.Http; namespace Telegram.BotAPI; /// -/// Telegram Bot Client. +/// Legacy Telegram Bot Client. /// -public sealed partial class BotClient +[Obsolete("This class is obsolete. Use TelegramBotClient instead.")] +public sealed partial class BotClient : TelegramBotClient { /// - /// Bot base url for download files. {0} = BotToken, {1} = FilePath + /// Initialize a Telegram Bot Client. /// - public const string BaseFilesUrl = "https://api.telegram.org/file/bot{0}/{1}"; + /// Token granted by BotFather. Required to access the Telegram bot API. + /// Optional. Provide a specific HttpClient for this instance of BotClient. + public BotClient(string botToken, HttpClient? httpClient = null) : base(botToken, httpClient) + { + } - private readonly HttpClient httpClient; + /// + /// Initialize a Telegram Bot Client. + /// + /// Options for the . + /// Optional. Provide a specific HttpClient for this instance of BotClient. + public BotClient(TelegramBotClientOptions options, HttpClient? httpClient = null) : base(options, httpClient) + { + } /// /// Initialize a Telegram Bot Client. /// /// Token granted by BotFather. Required to access the Telegram bot API. - /// Optional. Provide a specific HttpClient for this instance of BotClient. + /// Provide a specific HttpClient for this instance of BotClient. /// Optional. The server address to connect to. Default value is "https://api.telegram.org". Change this parameter if you're using a Local Bot API Server. /// Thrown when accessToken is null or empty. - public BotClient(string botToken, [Optional] HttpClient? httpClient, string serverAddress = "https://api.telegram.org") + [Obsolete("Use the constructor with BotClientOptions.")] + public BotClient(string botToken, HttpClient? httpClient, string serverAddress = "https://api.telegram.org") : base(new TelegramBotClientOptions(botToken) { ServerAddress = serverAddress }, httpClient) { - this.Token = botToken ?? throw new ArgumentNullException(nameof(botToken)); - this.httpClient = AddJsonMultipart(httpClient) ?? DefaultHttpClient ?? SetHttpClient(); - this.ServerAddress = serverAddress ?? throw new ArgumentNullException(nameof(serverAddress)); } /// Initialize a Telegram Bot Client. @@ -49,27 +48,36 @@ public BotClient(string botToken, [Optional] HttpClient? httpClient, string serv /// Optional. The server address to connect to. Default value is "https://api.telegram.org". Change this parameter if you're using a Local Bot API Server. /// Optional. Set true if the new client will use the Test Environment. If true, all requests methods will be prefixed with "/test". Example: "/test/getMe". /// Thrown when accessToken is null or empty. - public BotClient(string botToken, bool ignoreBotExceptions, [Optional] HttpClient httpClient, string serverAddress = "https://api.telegram.org", bool useTestEnvironment = false) : this(botToken, httpClient, serverAddress) + [Obsolete("Use the constructor with BotClientOptions.")] + public BotClient(string botToken, bool ignoreBotExceptions, HttpClient httpClient = null, string serverAddress = "https://api.telegram.org", bool useTestEnvironment = false) : base(new TelegramBotClientOptions(botToken) { IgnoreBotExceptions = ignoreBotExceptions, ServerAddress = serverAddress, UseTestEnvironment = useTestEnvironment }, httpClient) { - this.IgnoreBotExceptions = ignoreBotExceptions; - this.UseTestEnvironment = useTestEnvironment; } /// /// Token granted by BotFather. Required to access the Telegram bot API. /// - public string Token { get; } + public string Token => ((ITelegramBotClient)this).Options.BotToken; + /// /// Set true if you want methods to return a default value when bot requests are rejected instead of throwing a . /// - public bool IgnoreBotExceptions { get; } + public bool IgnoreBotExceptions => ((ITelegramBotClient)this).Options.IgnoreBotExceptions; + /// - /// The server address to send bot request. Default value is "https://api.telegram.org". + /// The server address to send bot request. + /// Default value is: https://api.telegram.org /// - public string ServerAddress { get; } + public string ServerAddress => ((ITelegramBotClient)this).Options.ServerAddress; + /// /// True if the current client is using the Test Environment. - /// If true, all requests methods will be prefixed with "/test". Example: "/test/getMe". + /// If true, all requests methods will be prefixed with "/test". /// - public bool UseTestEnvironment { get; } -} + public bool UseTestEnvironment => ((ITelegramBotClient)this).Options.UseTestEnvironment; + + /// + /// Bot base url for download files. {0} = BotToken, {1} = FilePath + /// + [Obsolete("Use FileUrlTemplate instead.")] + public const string BaseFilesUrl = "https://api.telegram.org/file/bot{0}/{1}"; +} \ No newline at end of file diff --git a/src/library/Telegram.BotAPI/BotRequestException.cs b/src/library/Telegram.BotAPI/BotRequestException.cs new file mode 100644 index 00000000..a4789ca5 --- /dev/null +++ b/src/library/Telegram.BotAPI/BotRequestException.cs @@ -0,0 +1,22 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI; + +/// +/// Exception generated when a request to Telegram Bot API got an error response. +/// = +/// Error code. +/// Description. +/// Parameters. +public sealed class BotRequestException(int errorCode, string description, ResponseParameters? parameters) : Exception(description) +{ + /// Error code. + public int ErrorCode { get; } = errorCode; + /// Error description. + public string Description { get; } = description; + /// Parameters. + public ResponseParameters? Parameters { get; } = parameters; +} diff --git a/src/library/Telegram.BotAPI/BotResponse.cs b/src/library/Telegram.BotAPI/BotResponse.cs new file mode 100644 index 00000000..d876ed38 --- /dev/null +++ b/src/library/Telegram.BotAPI/BotResponse.cs @@ -0,0 +1,45 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI; + +/// Represents the bot's response to the request. +/// Result type. +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public sealed class BotResponse +{ + /// + /// True, if the request was successful, otherwise false. + /// + [JsonPropertyName("ok")] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool Ok { get; set; } + /// + /// Result. + /// + [JsonPropertyName("result")] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public TResult? Result { get; set; } + /// + /// Error code. + /// + [JsonPropertyName("error_code")] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? ErrorCode { get; set; } + /// + /// Error description. + /// + [JsonPropertyName("description")] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? Description { get; set; } + /// + /// A object containing additional information about the error. + /// + [JsonPropertyName("parameters")] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ResponseParameters? Parameters { get; set; } +} diff --git a/src/Telegram.BotAPI/CommonNames.cs b/src/library/Telegram.BotAPI/CommonNames.cs similarity index 97% rename from src/Telegram.BotAPI/CommonNames.cs rename to src/library/Telegram.BotAPI/CommonNames.cs index 89e063e1..33de242f 100644 --- a/src/Telegram.BotAPI/CommonNames.cs +++ b/src/library/Telegram.BotAPI/CommonNames.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI; diff --git a/src/Telegram.BotAPI/Converters/BotCommandScopeConverter.cs b/src/library/Telegram.BotAPI/Converters/BotCommandScopeConverter.cs similarity index 98% rename from src/Telegram.BotAPI/Converters/BotCommandScopeConverter.cs rename to src/library/Telegram.BotAPI/Converters/BotCommandScopeConverter.cs index 9fa60bb3..c2f68ff2 100644 --- a/src/Telegram.BotAPI/Converters/BotCommandScopeConverter.cs +++ b/src/library/Telegram.BotAPI/Converters/BotCommandScopeConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Text.Json; diff --git a/src/library/Telegram.BotAPI/Converters/ChatBoostSourceConverter.cs b/src/library/Telegram.BotAPI/Converters/ChatBoostSourceConverter.cs new file mode 100644 index 00000000..15386ffd --- /dev/null +++ b/src/library/Telegram.BotAPI/Converters/ChatBoostSourceConverter.cs @@ -0,0 +1,60 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System.Text.Json; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.Converters; + +/// +/// Converts an to or from JSON. +/// +public sealed class ChatBoostSourceConverter : JsonConverter +{ + /// + /// Reads and converts the JSON to type . + /// + /// The reader. + /// The type to convert. + /// An object that specifies serialization options to use. + /// The converted value. + public override ChatBoostSource? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var jsonDoc = JsonSerializer.Deserialize(ref reader, options)!; + var isValid = jsonDoc.RootElement.TryGetProperty(PropertyNames.Source, out JsonElement prop); + var rawText = jsonDoc.RootElement.GetRawText(); + if (isValid) + { + if (prop.ValueKind != JsonValueKind.String) + throw new JsonException($"Property type of {PropertyNames.Source} must be a String."); + var source = prop.GetString(); + return source switch + { + "gift_code" => JsonSerializer.Deserialize(rawText, options), + "giveaway" => JsonSerializer.Deserialize(rawText, options), + "premium" => JsonSerializer.Deserialize(rawText, options), + _ => throw new JsonException($"Json object is not a valid ChatBoostSource."), + }; + } + else + { + throw new JsonException($"Missing required property: {PropertyNames.Source}"); + } + } + + /// + /// Writes a object as JSON. + /// + /// The writer to write to. + /// The value to convert to JSON. + /// An object that specifies serialization options to use. + public override void Write(Utf8JsonWriter writer, ChatBoostSource value, JsonSerializerOptions options) + { + if (value == null) + { + throw new ArgumentNullException(nameof(value)); + } + var type = value.GetType(); + JsonSerializer.Serialize(writer, value, type, options); + } +} diff --git a/src/Telegram.BotAPI/Converters/ChatMemberConverter.cs b/src/library/Telegram.BotAPI/Converters/ChatMemberConverter.cs similarity index 98% rename from src/Telegram.BotAPI/Converters/ChatMemberConverter.cs rename to src/library/Telegram.BotAPI/Converters/ChatMemberConverter.cs index 75ad69aa..eb061f8a 100644 --- a/src/Telegram.BotAPI/Converters/ChatMemberConverter.cs +++ b/src/library/Telegram.BotAPI/Converters/ChatMemberConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Text.Json; diff --git a/src/Telegram.BotAPI/Converters/InlineQueryResultConverter.cs b/src/library/Telegram.BotAPI/Converters/InlineQueryResultConverter.cs similarity index 99% rename from src/Telegram.BotAPI/Converters/InlineQueryResultConverter.cs rename to src/library/Telegram.BotAPI/Converters/InlineQueryResultConverter.cs index 726f1a0e..a4cb1701 100644 --- a/src/Telegram.BotAPI/Converters/InlineQueryResultConverter.cs +++ b/src/library/Telegram.BotAPI/Converters/InlineQueryResultConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Text.Json; diff --git a/src/Telegram.BotAPI/Converters/InputMediaConverter.cs b/src/library/Telegram.BotAPI/Converters/InputMediaConverter.cs similarity index 98% rename from src/Telegram.BotAPI/Converters/InputMediaConverter.cs rename to src/library/Telegram.BotAPI/Converters/InputMediaConverter.cs index ad568fa7..78c5c416 100644 --- a/src/Telegram.BotAPI/Converters/InputMediaConverter.cs +++ b/src/library/Telegram.BotAPI/Converters/InputMediaConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Text.Json; diff --git a/src/Telegram.BotAPI/Converters/InputMessageContentConverter.cs b/src/library/Telegram.BotAPI/Converters/InputMessageContentConverter.cs similarity index 98% rename from src/Telegram.BotAPI/Converters/InputMessageContentConverter.cs rename to src/library/Telegram.BotAPI/Converters/InputMessageContentConverter.cs index a10fbad9..2f8b7733 100644 --- a/src/Telegram.BotAPI/Converters/InputMessageContentConverter.cs +++ b/src/library/Telegram.BotAPI/Converters/InputMessageContentConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Text.Json; diff --git a/src/library/Telegram.BotAPI/Converters/MaybeInaccessibleMessageConverter.cs b/src/library/Telegram.BotAPI/Converters/MaybeInaccessibleMessageConverter.cs new file mode 100644 index 00000000..ddf3e8e8 --- /dev/null +++ b/src/library/Telegram.BotAPI/Converters/MaybeInaccessibleMessageConverter.cs @@ -0,0 +1,59 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System.Text.Json; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.Converters; + +/// +/// Converts an to or from JSON. +/// +public sealed class MaybeInaccessibleMessageConverter : JsonConverter +{ + /// + /// Reads and converts the JSON to type . + /// + /// The reader. + /// The type to convert. + /// An object that specifies serialization options to use. + /// The converted value. + public override MaybeInaccessibleMessage? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var jsonDoc = JsonSerializer.Deserialize(ref reader, options)!; + var isValid = jsonDoc.RootElement.TryGetProperty(PropertyNames.Date, out JsonElement prop); + var rawText = jsonDoc.RootElement.GetRawText(); + if (isValid) + { + var date = prop.GetUInt32(); + if (date == 0) + { + return JsonSerializer.Deserialize(rawText, options); + } + else + { + return JsonSerializer.Deserialize(rawText, options); + } + } + else + { + throw new JsonException($"Missing required property: {PropertyNames.Date}"); + } + } + + /// + /// Writes a object as JSON. + /// + /// The writer to write to. + /// The value to convert to JSON. + /// An object that specifies serialization options to use. + public override void Write(Utf8JsonWriter writer, MaybeInaccessibleMessage value, JsonSerializerOptions options) + { + if (value == null) + { + throw new ArgumentNullException(nameof(value)); + } + var type = value.GetType(); + JsonSerializer.Serialize(writer, value, type, options); + } +} diff --git a/src/Telegram.BotAPI/Converters/MenuButtonConverter.cs b/src/library/Telegram.BotAPI/Converters/MenuButtonConverter.cs similarity index 98% rename from src/Telegram.BotAPI/Converters/MenuButtonConverter.cs rename to src/library/Telegram.BotAPI/Converters/MenuButtonConverter.cs index 498717ee..59cec03c 100644 --- a/src/Telegram.BotAPI/Converters/MenuButtonConverter.cs +++ b/src/library/Telegram.BotAPI/Converters/MenuButtonConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Text.Json; diff --git a/src/library/Telegram.BotAPI/Converters/MessageOriginConverter.cs b/src/library/Telegram.BotAPI/Converters/MessageOriginConverter.cs new file mode 100644 index 00000000..06241e86 --- /dev/null +++ b/src/library/Telegram.BotAPI/Converters/MessageOriginConverter.cs @@ -0,0 +1,61 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System.Text.Json; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.Converters; + +/// +/// Converts an to or from JSON. +/// +public sealed class MessageOriginConverter : JsonConverter +{ + /// + /// Reads and converts the JSON to type . + /// + /// The reader. + /// The type to convert. + /// An object that specifies serialization options to use. + /// The converted value. + public override MessageOrigin? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var jsonDoc = JsonSerializer.Deserialize(ref reader, options)!; + var isValid = jsonDoc.RootElement.TryGetProperty(PropertyNames.Type, out JsonElement prop); + var rawText = jsonDoc.RootElement.GetRawText(); + if (isValid) + { + if (prop.ValueKind != JsonValueKind.String) + throw new JsonException($"Property type of {PropertyNames.Type} must be a String."); + var type = prop.GetString(); + return type switch + { + "user" => JsonSerializer.Deserialize(rawText, options), + "hidden_user" => JsonSerializer.Deserialize(rawText, options), + "chat" => JsonSerializer.Deserialize(rawText, options), + "channel" => JsonSerializer.Deserialize(rawText, options), + _ => throw new JsonException($"Json object is not a valid MessageOrigin."), + }; + } + else + { + throw new JsonException($"Missing required property: {PropertyNames.Type}"); + } + } + + /// + /// Writes a object as JSON. + /// + /// The writer to write to. + /// The value to convert to JSON. + /// An object that specifies serialization options to use. + public override void Write(Utf8JsonWriter writer, MessageOrigin value, JsonSerializerOptions options) + { + if (value == null) + { + throw new ArgumentNullException(nameof(value)); + } + var type = value.GetType(); + JsonSerializer.Serialize(writer, value, type, options); + } +} diff --git a/src/Telegram.BotAPI/Converters/PassportElementErrorConverter.cs b/src/library/Telegram.BotAPI/Converters/PassportElementErrorConverter.cs similarity index 98% rename from src/Telegram.BotAPI/Converters/PassportElementErrorConverter.cs rename to src/library/Telegram.BotAPI/Converters/PassportElementErrorConverter.cs index e0a566f3..0127ff1e 100644 --- a/src/Telegram.BotAPI/Converters/PassportElementErrorConverter.cs +++ b/src/library/Telegram.BotAPI/Converters/PassportElementErrorConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Text.Json; diff --git a/src/library/Telegram.BotAPI/Converters/ReactionTypeConverter.cs b/src/library/Telegram.BotAPI/Converters/ReactionTypeConverter.cs new file mode 100644 index 00000000..bce8cd0b --- /dev/null +++ b/src/library/Telegram.BotAPI/Converters/ReactionTypeConverter.cs @@ -0,0 +1,54 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System.Text.Json; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.Converters; + +/// +/// Converts an to or from JSON. +/// +public sealed class ReactionTypeConverter : JsonConverter +{ + /// + /// Reads and converts the JSON to type . + /// + /// The reader. + /// The type to convert. + /// An object that specifies serialization options to use. + /// The converted value. + public override ReactionType? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var ReactionType = JsonSerializer.Deserialize(ref reader, options)!; + var rawText = ReactionType.GetRawText(); + if (ReactionType.TryGetProperty(PropertyNames.Type, out var value)) + { + var typeName = value.GetString(); + return typeName switch + { + "emoji" => JsonSerializer.Deserialize(rawText, options), + "custom_emoji" => JsonSerializer.Deserialize(rawText, options), + _ => throw new JsonException($"Json object is not a valid reaction type."), + }; + } + + throw new JsonException($"Json object is not a valid reaction type."); + } + + /// + /// Writes a object as JSON. + /// + /// The writer to write to. + /// The value to convert to JSON. + /// An object that specifies serialization options to use. + public override void Write(Utf8JsonWriter writer, ReactionType value, JsonSerializerOptions options) + { + if (value == null) + { + throw new ArgumentNullException(nameof(value)); + } + var type = value.GetType(); + JsonSerializer.Serialize(writer, value, type, options); + } +} diff --git a/src/Telegram.BotAPI/Converters/ReplyMarkupConverter.cs b/src/library/Telegram.BotAPI/Converters/ReplyMarkupConverter.cs similarity index 98% rename from src/Telegram.BotAPI/Converters/ReplyMarkupConverter.cs rename to src/library/Telegram.BotAPI/Converters/ReplyMarkupConverter.cs index 3408617e..22cd2627 100644 --- a/src/Telegram.BotAPI/Converters/ReplyMarkupConverter.cs +++ b/src/library/Telegram.BotAPI/Converters/ReplyMarkupConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Text.Json; diff --git a/src/Telegram.BotAPI/Games/Args/GetGameScoreArgs.cs b/src/library/Telegram.BotAPI/Games/Args/GetGameScoreArgs.cs similarity index 97% rename from src/Telegram.BotAPI/Games/Args/GetGameScoreArgs.cs rename to src/library/Telegram.BotAPI/Games/Args/GetGameScoreArgs.cs index 36c94207..75a145af 100644 --- a/src/Telegram.BotAPI/Games/Args/GetGameScoreArgs.cs +++ b/src/library/Telegram.BotAPI/Games/Args/GetGameScoreArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/library/Telegram.BotAPI/Games/Args/SendGameArgs.cs b/src/library/Telegram.BotAPI/Games/Args/SendGameArgs.cs new file mode 100644 index 00000000..99503238 --- /dev/null +++ b/src/library/Telegram.BotAPI/Games/Args/SendGameArgs.cs @@ -0,0 +1,61 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.Games; + +/// +/// SendGame method arguments. +/// +/// Unique identifier for the target chat. +/// Short name of the game, serves as the unique identifier for the game. Set up your games via BotFather. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class SendGameArgs(long chatId, string gameShortName) +{ + /// + /// Unique identifier for the target chat + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public long ChatId { get; set; } = chatId; + /// + /// Short name of the game, serves as the unique identifier for the game. Set up your games via @BotFather. + /// + [JsonPropertyName(PropertyNames.GameShortName)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string GameShortName { get; set; } = gameShortName ?? throw new ArgumentNullException(nameof(gameShortName)); + /// + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + /// + [JsonPropertyName(PropertyNames.MessageThreadId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? MessageThreadId { get; set; } + /// + /// Sends the message silently. Users will receive a notification with no sound. + /// + [JsonPropertyName(PropertyNames.DisableNotification)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? DisableNotification { get; set; } + /// + /// Protects the contents of the sent message from forwarding and saving + /// + [JsonPropertyName(PropertyNames.ProtectContent)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? ProtectContent { get; set; } + /// + /// Description of the message to reply to + /// + [JsonPropertyName(PropertyNames.ReplyParameters)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyParameters? ReplyParameters { get; set; } + /// + /// A JSON-serialized object for an inline keyboard. If empty, one 'Play game_title' button will be shown. If not empty, the first button must launch the game. + /// + [JsonPropertyName(PropertyNames.ReplyMarkup)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public InlineKeyboardMarkup? ReplyMarkup { get; set; } +} diff --git a/src/Telegram.BotAPI/Games/Args/SetGameScoreArgs.cs b/src/library/Telegram.BotAPI/Games/Args/SetGameScoreArgs.cs similarity index 98% rename from src/Telegram.BotAPI/Games/Args/SetGameScoreArgs.cs rename to src/library/Telegram.BotAPI/Games/Args/SetGameScoreArgs.cs index 2f80ad31..4a0f1276 100644 --- a/src/Telegram.BotAPI/Games/Args/SetGameScoreArgs.cs +++ b/src/library/Telegram.BotAPI/Games/Args/SetGameScoreArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Games/CallbackGame.cs b/src/library/Telegram.BotAPI/Games/CallbackGame.cs similarity index 96% rename from src/Telegram.BotAPI/Games/CallbackGame.cs rename to src/library/Telegram.BotAPI/Games/CallbackGame.cs index 264bd1cd..70bbdc69 100644 --- a/src/Telegram.BotAPI/Games/CallbackGame.cs +++ b/src/library/Telegram.BotAPI/Games/CallbackGame.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Games/Game.cs b/src/library/Telegram.BotAPI/Games/Game.cs similarity index 98% rename from src/Telegram.BotAPI/Games/Game.cs rename to src/library/Telegram.BotAPI/Games/Game.cs index 092a5b6b..9eb53dc7 100644 --- a/src/Telegram.BotAPI/Games/Game.cs +++ b/src/library/Telegram.BotAPI/Games/Game.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Games/GameHighScore.cs b/src/library/Telegram.BotAPI/Games/GameHighScore.cs similarity index 98% rename from src/Telegram.BotAPI/Games/GameHighScore.cs rename to src/library/Telegram.BotAPI/Games/GameHighScore.cs index 13879464..dfba259f 100644 --- a/src/Telegram.BotAPI/Games/GameHighScore.cs +++ b/src/library/Telegram.BotAPI/Games/GameHighScore.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Games/getGameHighScores.cs b/src/library/Telegram.BotAPI/Games/getGameHighScores.cs similarity index 82% rename from src/Telegram.BotAPI/Games/getGameHighScores.cs rename to src/library/Telegram.BotAPI/Games/getGameHighScores.cs index 13af2c07..f25c9c2e 100644 --- a/src/Telegram.BotAPI/Games/getGameHighScores.cs +++ b/src/library/Telegram.BotAPI/Games/getGameHighScores.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -14,14 +14,14 @@ public static partial class GamesExtensions /// Parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static GameHighScore[] GetGameScore(this BotClient? bot, GetGameScoreArgs args) + public static GameHighScore[] GetGameScore(this ITelegramBotClient bot, GetGameScoreArgs args) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } - return bot.RPC(MethodNames.GetGameHighScores, args); + return bot.CallMethod(MethodNames.GetGameHighScores, args); } /// Use this method to get data for high score tables. Will return the score of the specified user and several of his neighbors in a game. On success, returns an Array of GameHighScore objects.This method will currently return scores for the target user, plus two of his closest neighbors on each side. Will also return the top three users if the user and his neighbors are not among them. Please note that this behavior is subject to change. ///BotClient @@ -29,7 +29,7 @@ public static GameHighScore[] GetGameScore(this BotClient? bot, GetGameScoreArgs /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task GetGameScoreAsync(this BotClient? bot, GetGameScoreArgs args, [Optional] CancellationToken cancellationToken) + public static async Task GetGameScoreAsync(this ITelegramBotClient bot, GetGameScoreArgs args, CancellationToken cancellationToken = default) { if (bot == default) { @@ -41,14 +41,14 @@ public static async Task GetGameScoreAsync(this BotClient? bot, throw new ArgumentNullException(nameof(args)); } - return await bot.RPCA(MethodNames.GetGameHighScores, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetGameHighScores, args, cancellationToken: cancellationToken).ConfigureAwait(false); } /// Use this method to get data for high score tables. Will return the score of the specified user and several of his neighbors in a game. On success, returns an Array of GameHighScore objects.This method will currently return scores for the target user, plus two of his closest neighbors on each side. Will also return the top three users if the user and his neighbors are not among them. Please note that this behavior is subject to change. ///BotClient /// Parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static T GetGameScore(this BotClient? bot, GetGameScoreArgs args) + public static T GetGameScore(this ITelegramBotClient bot, GetGameScoreArgs args) where T : IEnumerable { if (bot == default) @@ -56,7 +56,7 @@ public static T GetGameScore(this BotClient? bot, GetGameScoreArgs args) throw new ArgumentNullException(nameof(bot)); } - return bot.RPC(MethodNames.GetGameHighScores, args); + return bot.CallMethod(MethodNames.GetGameHighScores, args); } /// Use this method to get data for high score tables. Will return the score of the specified user and several of his neighbors in a game. On success, returns an Array of GameHighScore objects.This method will currently return scores for the target user, plus two of his closest neighbors on each side. Will also return the top three users if the user and his neighbors are not among them. Please note that this behavior is subject to change. ///BotClient @@ -64,7 +64,7 @@ public static T GetGameScore(this BotClient? bot, GetGameScoreArgs args) /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task GetGameScoreAsync(this BotClient? bot, GetGameScoreArgs args, [Optional] CancellationToken cancellationToken) + public static async Task GetGameScoreAsync(this ITelegramBotClient bot, GetGameScoreArgs args, CancellationToken cancellationToken = default) where T : IEnumerable { if (bot == default) @@ -77,6 +77,6 @@ public static async Task GetGameScoreAsync(this BotClient? bot, GetGameSco throw new ArgumentNullException(nameof(args)); } - return await bot.RPCA(MethodNames.GetGameHighScores, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetGameHighScores, args, cancellationToken: cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Games/sendGame.cs b/src/library/Telegram.BotAPI/Games/sendGame.cs similarity index 64% rename from src/Telegram.BotAPI/Games/sendGame.cs rename to src/library/Telegram.BotAPI/Games/sendGame.cs index f1e3f8da..34ee0480 100644 --- a/src/Telegram.BotAPI/Games/sendGame.cs +++ b/src/library/Telegram.BotAPI/Games/sendGame.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -15,14 +15,14 @@ public static partial class GamesExtensions ///Parameters /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendGame(this BotClient? bot, SendGameArgs args) + public static Message SendGame(this ITelegramBotClient bot, SendGameArgs args) { - if (bot == default) + if (bot is null) { throw new ArgumentNullException(nameof(bot)); } - return bot.RPC(MethodNames.SendGame, args); + return bot.CallMethod(MethodNames.SendGame, args); } /// Use this method to send a game. On success, the sent Message is returned. @@ -31,77 +31,75 @@ public static Message SendGame(this BotClient? bot, SendGameArgs args) ///The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendGameAsync(this BotClient? bot, SendGameArgs args, [Optional] CancellationToken cancellationToken) + public static async Task SendGameAsync(this ITelegramBotClient bot, SendGameArgs args, CancellationToken cancellationToken = default) { - if (bot == default) + if (bot is null) { throw new ArgumentNullException(nameof(bot)); } - if (args == default) + if (args is null) { throw new ArgumentNullException(nameof(args)); } - return await bot.RPCA(MethodNames.SendGame, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SendGame, args, cancellationToken: cancellationToken).ConfigureAwait(false); } /// /// Use this method to send a game. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat. /// Short name of the game, serves as the unique identifier for the game. Set up your games via @BotFather. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// A JSON-serialized object for an inline keyboard. If empty, one 'Play game_title' button will be shown. If not empty, the first button must launch the game. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendGame(this BotClient? api, long chatId, string gameShortName, [Optional] int? messageThreadId, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] InlineKeyboardMarkup? replyMarkup) + public static Message SendGame(this ITelegramBotClient client, long chatId, string gameShortName, int? messageThreadId = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, InlineKeyboardMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendGameArgs(chatId, gameShortName) { MessageThreadId = messageThreadId, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPC(MethodNames.SendGame, args); + return client.CallMethod(MethodNames.SendGame, args); } /// /// Use this method to send a game. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat. /// Short name of the game, serves as the unique identifier for the game. Set up your games via @BotFather. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// A JSON-serialized object for an inline keyboard. If empty, one 'Play game_title' button will be shown. If not empty, the first button must launch the game. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendGameAsync(this BotClient? api, long chatId, string gameShortName, [Optional] int? messageThreadId, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] InlineKeyboardMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendGameAsync(this ITelegramBotClient client, long chatId, string gameShortName, int? messageThreadId = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, InlineKeyboardMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendGameArgs(chatId, gameShortName) { MessageThreadId = messageThreadId, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCA(MethodNames.SendGame, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendGame, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Games/sendGameScore.cs b/src/library/Telegram.BotAPI/Games/sendGameScore.cs similarity index 83% rename from src/Telegram.BotAPI/Games/sendGameScore.cs rename to src/library/Telegram.BotAPI/Games/sendGameScore.cs index 7e5e89ac..9553f90e 100644 --- a/src/Telegram.BotAPI/Games/sendGameScore.cs +++ b/src/library/Telegram.BotAPI/Games/sendGameScore.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json.Linq; @@ -17,7 +17,7 @@ public static partial class GamesExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// or . On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is not greater than the user's current score in the chat and force is False. - public static Message SetGameScore(this BotClient? bot, SetGameScoreArgs args) + public static Message SetGameScore(this ITelegramBotClient bot, SetGameScoreArgs args) { if (bot == default) { @@ -27,7 +27,7 @@ public static Message SetGameScore(this BotClient? bot, SetGameScoreArgs args) { throw new ArgumentNullException(nameof(args)); } - return bot.RPC(MethodNames.SetGameScore, args); + return bot.CallMethod(MethodNames.SetGameScore, args); } /// Use this method to set the score of the specified user in a game. ///BotClient @@ -36,7 +36,7 @@ public static Message SetGameScore(this BotClient? bot, SetGameScoreArgs args) /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// or . On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is not greater than the user's current score in the chat and force is False. - public static async Task SetGameScoreAsync(this BotClient? bot, SetGameScoreArgs args, [Optional] CancellationToken cancellationToken) + public static async Task SetGameScoreAsync(this ITelegramBotClient bot, SetGameScoreArgs args, CancellationToken cancellationToken = default) { if (bot == default) { @@ -46,7 +46,7 @@ public static async Task SetGameScoreAsync(this BotClient? bot, SetGame { throw new ArgumentNullException(nameof(args)); } - return await bot.RPCA(MethodNames.SetGameScore, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetGameScore, args, cancellationToken: cancellationToken).ConfigureAwait(false); } /// Use this method to set the score of the specified user in a game. ///BotClient @@ -55,7 +55,7 @@ public static async Task SetGameScoreAsync(this BotClient? bot, SetGame /// Thrown when a required parameter is null. /// Thrown when T is not Telegram.BotAPI.AvailableTypes.Message or bool. /// or . On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is not greater than the user's current score in the chat and force is False. - public static T SetGameScore(this BotClient? bot, SetGameScoreArgs args) + public static T SetGameScore(this ITelegramBotClient bot, SetGameScoreArgs args) { if (bot == default) { @@ -69,7 +69,7 @@ public static T SetGameScore(this BotClient? bot, SetGameScoreArgs args) { throw new ArgumentException($"{nameof(T)} must be Telegram.BotAPI.AvailableTypes.Message or bool."); } - return bot.RPC(MethodNames.SetGameScore, args); + return bot.CallMethod(MethodNames.SetGameScore, args); } /// Use this method to set the score of the specified user in a game. ///BotClient @@ -79,7 +79,7 @@ public static T SetGameScore(this BotClient? bot, SetGameScoreArgs args) /// Thrown when a required parameter is null. /// Thrown when T is not Telegram.BotAPI.AvailableTypes.Message or bool. /// or . On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is not greater than the user's current score in the chat and force is False. - public static async Task SetGameScoreAsync(this BotClient? bot, SetGameScoreArgs args, [Optional] CancellationToken cancellationToken) + public static async Task SetGameScoreAsync(this ITelegramBotClient bot, SetGameScoreArgs args, CancellationToken cancellationToken = default) { if (bot == default) { @@ -93,6 +93,6 @@ public static async Task SetGameScoreAsync(this BotClient? bot, SetGameSco { throw new ArgumentException($"{nameof(T)} must be Telegram.BotAPI.AvailableTypes.Message or bool."); } - return await bot.RPCA(MethodNames.SetGameScore, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetGameScore, args, cancellationToken: cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Getting updates/AllowedUpdate.cs b/src/library/Telegram.BotAPI/Getting updates/AllowedUpdate.cs similarity index 98% rename from src/Telegram.BotAPI/Getting updates/AllowedUpdate.cs rename to src/library/Telegram.BotAPI/Getting updates/AllowedUpdate.cs index 6e8696d0..de3f1282 100644 --- a/src/Telegram.BotAPI/Getting updates/AllowedUpdate.cs +++ b/src/library/Telegram.BotAPI/Getting updates/AllowedUpdate.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI.GettingUpdates; diff --git a/src/Telegram.BotAPI/Getting updates/Args/GetUpdatesArgs.cs b/src/library/Telegram.BotAPI/Getting updates/Args/GetUpdatesArgs.cs similarity index 98% rename from src/Telegram.BotAPI/Getting updates/Args/GetUpdatesArgs.cs rename to src/library/Telegram.BotAPI/Getting updates/Args/GetUpdatesArgs.cs index 17fd3b8e..d9a159a4 100644 --- a/src/Telegram.BotAPI/Getting updates/Args/GetUpdatesArgs.cs +++ b/src/library/Telegram.BotAPI/Getting updates/Args/GetUpdatesArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Getting updates/Args/SetWebhookArgs.cs b/src/library/Telegram.BotAPI/Getting updates/Args/SetWebhookArgs.cs similarity index 98% rename from src/Telegram.BotAPI/Getting updates/Args/SetWebhookArgs.cs rename to src/library/Telegram.BotAPI/Getting updates/Args/SetWebhookArgs.cs index 287e3a85..9577a114 100644 --- a/src/Telegram.BotAPI/Getting updates/Args/SetWebhookArgs.cs +++ b/src/library/Telegram.BotAPI/Getting updates/Args/SetWebhookArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/library/Telegram.BotAPI/Getting updates/Update.cs b/src/library/Telegram.BotAPI/Getting updates/Update.cs new file mode 100644 index 00000000..d5055d06 --- /dev/null +++ b/src/library/Telegram.BotAPI/Getting updates/Update.cs @@ -0,0 +1,133 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using Telegram.BotAPI.AvailableTypes; +using Telegram.BotAPI.InlineMode; +using Telegram.BotAPI.Payments; + +namespace Telegram.BotAPI.GettingUpdates; + +/// +/// This object represents an incoming update. +/// At most one of the optional parameters can be present in any given update. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class Update +{ + /// + /// The update's unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you're using webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially. + /// + [JsonPropertyName(PropertyNames.UpdateId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int UpdateId { get; set; } + /// + /// Optional. New incoming message of any kind - text, photo, sticker, etc. + /// + [JsonPropertyName(PropertyNames.Message)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Message? Message { get; set; } + /// + /// Optional. New version of a message that is known to the bot and was edited + /// + [JsonPropertyName(PropertyNames.EditedMessage)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Message? EditedMessage { get; set; } + /// + /// Optional. New incoming channel post of any kind - text, photo, sticker, etc. + /// + [JsonPropertyName(PropertyNames.ChannelPost)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Message? ChannelPost { get; set; } + /// + /// Optional. New version of a channel post that is known to the bot and was edited + /// + [JsonPropertyName(PropertyNames.EditedChannelPost)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Message? EditedChannelPost { get; set; } + /// + /// Optional. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify "message_reaction" in the list of allowed_updates to receive these updates. The update isn't received for reactions set by bots. + /// + [JsonPropertyName(PropertyNames.MessageReaction)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public MessageReactionUpdated? MessageReaction { get; set; } + /// + /// Optional. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify "message_reaction_count" in the list of allowed_updates to receive these updates. + /// + [JsonPropertyName(PropertyNames.MessageReactionCount)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public MessageReactionCountUpdated? MessageReactionCount { get; set; } + /// + /// Optional. New incoming inline query + /// + [JsonPropertyName(PropertyNames.InlineQuery)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public InlineQuery? InlineQuery { get; set; } + /// + /// Optional. The result of an inline query that was chosen by a user and sent to their chat partner. Please see our documentation on the feedback collecting for details on how to enable these updates for your bot. + /// + [JsonPropertyName(PropertyNames.ChosenInlineResult)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ChosenInlineResult? ChosenInlineResult { get; set; } + /// + /// Optional. New incoming callback query + /// + [JsonPropertyName(PropertyNames.CallbackQuery)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public CallbackQuery? CallbackQuery { get; set; } + /// + /// Optional. New incoming shipping query. Only for invoices with flexible price + /// + [JsonPropertyName(PropertyNames.ShippingQuery)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ShippingQuery? ShippingQuery { get; set; } + /// + /// Optional. New incoming pre-checkout query. Contains full information about checkout + /// + [JsonPropertyName(PropertyNames.PreCheckoutQuery)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public PreCheckoutQuery? PreCheckoutQuery { get; set; } + /// + /// Optional. New poll state. Bots receive only updates about stopped polls and polls, which are sent by the bot + /// + [JsonPropertyName(PropertyNames.Poll)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public Poll? Poll { get; set; } + /// + /// Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself. + /// + [JsonPropertyName(PropertyNames.PollAnswer)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public PollAnswer? PollAnswer { get; set; } + /// + /// Optional. The bot's chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user. + /// + [JsonPropertyName(PropertyNames.MyChatMember)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ChatMemberUpdated? MyChatMember { get; set; } + /// + /// Optional. A chat member's status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify "chat_member" in the list of allowed_updates to receive these updates. + /// + [JsonPropertyName(PropertyNames.ChatMember)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ChatMemberUpdated? ChatMember { get; set; } + /// + /// Optional. A request to join the chat has been sent. The bot must have the can_invite_users administrator right in the chat to receive these updates. + /// + [JsonPropertyName(PropertyNames.ChatJoinRequest)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ChatJoinRequest? ChatJoinRequest { get; set; } + /// + /// Optional. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates. + /// + [JsonPropertyName(PropertyNames.ChatBoost)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ChatBoostUpdated? ChatBoost { get; set; } + /// + /// Optional. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates. + /// + [JsonPropertyName(PropertyNames.RemovedChatBoost)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ChatBoostRemoved? RemovedChatBoost { get; set; } +} diff --git a/src/Telegram.BotAPI/Getting updates/WebhookInfo.cs b/src/library/Telegram.BotAPI/Getting updates/WebhookInfo.cs similarity index 96% rename from src/Telegram.BotAPI/Getting updates/WebhookInfo.cs rename to src/library/Telegram.BotAPI/Getting updates/WebhookInfo.cs index b40b355f..84e4a262 100644 --- a/src/Telegram.BotAPI/Getting updates/WebhookInfo.cs +++ b/src/library/Telegram.BotAPI/Getting updates/WebhookInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; @@ -102,9 +102,7 @@ public override int GetHashCode() /// public static bool operator ==(WebhookInfo? left, WebhookInfo? right) { -#pragma warning disable CS8604 // Possible null reference argument. return EqualityComparer.Default.Equals(left!, right!); -#pragma warning restore CS8604 // Possible null reference argument. } /// public static bool operator !=(WebhookInfo? left, WebhookInfo? right) diff --git a/src/Telegram.BotAPI/Getting updates/deleteWebhook.cs b/src/library/Telegram.BotAPI/Getting updates/deleteWebhook.cs similarity index 78% rename from src/Telegram.BotAPI/Getting updates/deleteWebhook.cs rename to src/library/Telegram.BotAPI/Getting updates/deleteWebhook.cs index ba7e6119..56e7d611 100644 --- a/src/Telegram.BotAPI/Getting updates/deleteWebhook.cs +++ b/src/library/Telegram.BotAPI/Getting updates/deleteWebhook.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -16,7 +16,7 @@ public static partial class GettingUpdatesExtensions /// Pass True to drop all pending updates. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool DeleteWebhook(this BotClient? bot, [Optional] bool? dropPendingUpdates) + public static bool DeleteWebhook(this ITelegramBotClient bot, [Optional] bool? dropPendingUpdates) { if (bot == default) { @@ -32,11 +32,11 @@ public static bool DeleteWebhook(this BotClient? bot, [Optional] bool? dropPendi json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.DeleteWebhook, stream); + return bot.CallMethod(MethodNames.DeleteWebhook, stream); } else { - return bot.RPC(MethodNames.DeleteWebhook); + return bot.CallMethod(MethodNames.DeleteWebhook); } } /// Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success. Requires no parameters. @@ -45,7 +45,7 @@ public static bool DeleteWebhook(this BotClient? bot, [Optional] bool? dropPendi /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task DeleteWebhookAsync(this BotClient? bot, [Optional] bool? dropPendingUpdates, [Optional] CancellationToken cancellationToken) + public static async Task DeleteWebhookAsync(this ITelegramBotClient bot, [Optional] bool? dropPendingUpdates, CancellationToken cancellationToken = default) { if (bot == default) { @@ -62,11 +62,11 @@ public static async Task DeleteWebhookAsync(this BotClient? bot, [Optional await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.DeleteWebhook, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.DeleteWebhook, stream, cancellationToken).ConfigureAwait(false); } else { - return await bot.RPCA(MethodNames.DeleteWebhook, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.DeleteWebhook, cancellationToken).ConfigureAwait(false); } } } diff --git a/src/Telegram.BotAPI/Getting updates/getUpdates.cs b/src/library/Telegram.BotAPI/Getting updates/getUpdates.cs similarity index 84% rename from src/Telegram.BotAPI/Getting updates/getUpdates.cs rename to src/library/Telegram.BotAPI/Getting updates/getUpdates.cs index ccad2437..04332d09 100644 --- a/src/Telegram.BotAPI/Getting updates/getUpdates.cs +++ b/src/library/Telegram.BotAPI/Getting updates/getUpdates.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -14,34 +14,34 @@ public static partial class GettingUpdatesExtensions /// BotClient /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Update[] GetUpdates(this BotClient? bot) + public static Update[] GetUpdates(this ITelegramBotClient bot) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } - return bot.RPC(MethodNames.GetUpdates); + return bot.CallMethod(MethodNames.GetUpdates); } /// Use this method to receive incoming updates using long polling. An Array of objects is returned. /// BotClient /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task GetUpdatesAsync(this BotClient? bot) + public static async Task GetUpdatesAsync(this ITelegramBotClient bot) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } - return await bot.RPCA(MethodNames.GetUpdates).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetUpdates).ConfigureAwait(false); } /// Use this method to receive incoming updates using long polling. An Array of objects is returned. /// BotClient /// Optional parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Update[] GetUpdates(this BotClient? bot, GetUpdatesArgs args) + public static Update[] GetUpdates(this ITelegramBotClient bot, GetUpdatesArgs args) { if (bot == default) { @@ -53,7 +53,7 @@ public static Update[] GetUpdates(this BotClient? bot, GetUpdatesArgs args) throw new ArgumentNullException(nameof(args)); } - return bot.RPC(MethodNames.GetUpdates, args); + return bot.CallMethod(MethodNames.GetUpdates, args); } /// Use this method to receive incoming updates using long polling. An Array of objects is returned. /// BotClient @@ -61,7 +61,7 @@ public static Update[] GetUpdates(this BotClient? bot, GetUpdatesArgs args) /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task GetUpdatesAsync(this BotClient? bot, GetUpdatesArgs args, [Optional] CancellationToken cancellationToken) + public static async Task GetUpdatesAsync(this ITelegramBotClient bot, GetUpdatesArgs args, CancellationToken cancellationToken = default) { if (bot == default) { @@ -73,7 +73,7 @@ public static async Task GetUpdatesAsync(this BotClient? bot, GetUpdat throw new ArgumentNullException(nameof(args)); } - return await bot.RPCA(MethodNames.GetUpdates, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetUpdates, args, cancellationToken: cancellationToken).ConfigureAwait(false); } /// Use this method to receive incoming updates using long polling. An Array of objects is returned. /// BotClient @@ -83,7 +83,7 @@ public static async Task GetUpdatesAsync(this BotClient? bot, GetUpdat /// List the types of updates you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all updates regardless of type (default). If not specified, the previous setting will be used.Please note that this parameter doesn't affect updates created before the call to the getUpdates, so unwanted updates may be received for a short period of time. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Update[] GetUpdates(this BotClient? bot, [Optional] int? offset, [Optional] ushort? limit, [Optional] uint? timeout, [Optional] IEnumerable allowedUpdates) + public static Update[] GetUpdates(this ITelegramBotClient bot, [Optional] int? offset, [Optional] ushort? limit, [Optional] uint? timeout, [Optional] IEnumerable allowedUpdates) { if (bot == default) { @@ -120,7 +120,7 @@ public static Update[] GetUpdates(this BotClient? bot, [Optional] int? offset, [ json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.GetUpdates, stream); + return bot.CallMethod(MethodNames.GetUpdates, stream); } /// Use this method to receive incoming updates using long polling. An Array of objects is returned. /// BotClient @@ -131,7 +131,7 @@ public static Update[] GetUpdates(this BotClient? bot, [Optional] int? offset, [ /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task GetUpdatesAsync(this BotClient? bot, [Optional] int? offset, [Optional] ushort? limit, [Optional] uint? timeout, [Optional] IEnumerable allowedUpdates, [Optional] CancellationToken cancellationToken) + public static async Task GetUpdatesAsync(this ITelegramBotClient bot, [Optional] int? offset, [Optional] ushort? limit, [Optional] uint? timeout, [Optional] IEnumerable allowedUpdates, CancellationToken cancellationToken = default) { if (bot == default) { @@ -169,13 +169,13 @@ public static async Task GetUpdatesAsync(this BotClient? bot, [Optiona await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.GetUpdates, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetUpdates, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to receive incoming updates using long polling. An Array of objects is returned. /// BotClient /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static T GetUpdates(this BotClient? bot) + public static T GetUpdates(this ITelegramBotClient bot) where T : IEnumerable { if (bot == default) @@ -183,27 +183,27 @@ public static T GetUpdates(this BotClient? bot) throw new ArgumentNullException(nameof(bot)); } - return bot.RPC(MethodNames.GetUpdates); + return bot.CallMethod(MethodNames.GetUpdates); } /// Use this method to receive incoming updates using long polling. An Array of objects is returned. /// BotClient /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task GetUpdatesAsync(this BotClient? bot) + public static async Task GetUpdatesAsync(this ITelegramBotClient bot) where T : IEnumerable { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } - return await bot.RPCA(MethodNames.GetUpdates).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetUpdates).ConfigureAwait(false); } /// Use this method to receive incoming updates using long polling. An Array of objects is returned. /// BotClient /// Optional parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static T GetUpdates(this BotClient? bot, GetUpdatesArgs args) + public static T GetUpdates(this ITelegramBotClient bot, GetUpdatesArgs args) where T : IEnumerable { if (bot == default) @@ -216,7 +216,7 @@ public static T GetUpdates(this BotClient? bot, GetUpdatesArgs args) throw new ArgumentNullException(nameof(args)); } - return bot.RPC(MethodNames.GetUpdates, args); + return bot.CallMethod(MethodNames.GetUpdates, args); } /// Use this method to receive incoming updates using long polling. An Array of objects is returned. /// BotClient @@ -224,7 +224,7 @@ public static T GetUpdates(this BotClient? bot, GetUpdatesArgs args) /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task GetUpdatesAsync(this BotClient? bot, GetUpdatesArgs args, [Optional] CancellationToken cancellationToken) + public static async Task GetUpdatesAsync(this ITelegramBotClient bot, GetUpdatesArgs args, CancellationToken cancellationToken = default) where T : IEnumerable { if (bot == default) @@ -237,7 +237,7 @@ public static async Task GetUpdatesAsync(this BotClient? bot, GetUpdatesAr throw new ArgumentNullException(nameof(args)); } - return await bot.RPCA(MethodNames.GetUpdates, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetUpdates, args, cancellationToken: cancellationToken).ConfigureAwait(false); } /// Use this method to receive incoming updates using long polling. An Array of objects is returned. /// BotClient @@ -247,7 +247,7 @@ public static async Task GetUpdatesAsync(this BotClient? bot, GetUpdatesAr /// List the types of updates you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all updates regardless of type (default). If not specified, the previous setting will be used.Please note that this parameter doesn't affect updates created before the call to the getUpdates, so unwanted updates may be received for a short period of time. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static T GetUpdates(this BotClient? bot, [Optional] int? offset, [Optional] ushort? limit, [Optional] uint? timeout, [Optional] IEnumerable allowedUpdates) + public static T GetUpdates(this ITelegramBotClient bot, [Optional] int? offset, [Optional] ushort? limit, [Optional] uint? timeout, [Optional] IEnumerable allowedUpdates) where T : IEnumerable { if (bot == default) @@ -285,7 +285,7 @@ public static T GetUpdates(this BotClient? bot, [Optional] int? offset, [Opti json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.GetUpdates, stream); + return bot.CallMethod(MethodNames.GetUpdates, stream); } /// Use this method to receive incoming updates using long polling. An Array of objects is returned. /// BotClient @@ -296,7 +296,7 @@ public static T GetUpdates(this BotClient? bot, [Optional] int? offset, [Opti /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task GetUpdatesAsync(this BotClient? bot, [Optional] int? offset, [Optional] ushort? limit, [Optional] uint? timeout, [Optional] IEnumerable allowedUpdates, [Optional] CancellationToken cancellationToken) + public static async Task GetUpdatesAsync(this ITelegramBotClient bot, [Optional] int? offset, [Optional] ushort? limit, [Optional] uint? timeout, [Optional] IEnumerable allowedUpdates, CancellationToken cancellationToken = default) where T : IEnumerable { if (bot == default) @@ -331,6 +331,6 @@ public static async Task GetUpdatesAsync(this BotClient? bot, [Optional] i await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.GetUpdates, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetUpdates, stream, cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Telegram.BotAPI/Getting updates/getWebhookInfo.cs b/src/library/Telegram.BotAPI/Getting updates/getWebhookInfo.cs similarity index 80% rename from src/Telegram.BotAPI/Getting updates/getWebhookInfo.cs rename to src/library/Telegram.BotAPI/Getting updates/getWebhookInfo.cs index fbe11cf9..8b7befa8 100644 --- a/src/Telegram.BotAPI/Getting updates/getWebhookInfo.cs +++ b/src/library/Telegram.BotAPI/Getting updates/getWebhookInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -12,27 +12,27 @@ public static partial class GettingUpdatesExtensions /// Bot Client /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static WebhookInfo GetWebhookInfo(this BotClient? bot) + public static WebhookInfo GetWebhookInfo(this ITelegramBotClient bot) { if (bot == default) { throw new System.ArgumentNullException(nameof(bot)); } - return bot.RPC(MethodNames.GetWebhookInfo); + return bot.CallMethod(MethodNames.GetWebhookInfo); } /// Use this method to get current webhook status. On success, returns a object. If the bot is using getUpdates, will return an object with the url field empty. /// Bot Client /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task GetWebhookInfoAsync(this BotClient? bot, [Optional] CancellationToken cancellationToken) + public static async Task GetWebhookInfoAsync(this ITelegramBotClient bot, CancellationToken cancellationToken = default) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } - return await bot.RPCA(MethodNames.GetWebhookInfo, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetWebhookInfo, cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Telegram.BotAPI/Getting updates/setWebhook.cs b/src/library/Telegram.BotAPI/Getting updates/setWebhook.cs similarity index 85% rename from src/Telegram.BotAPI/Getting updates/setWebhook.cs rename to src/library/Telegram.BotAPI/Getting updates/setWebhook.cs index a09cdea5..42fe97dc 100644 --- a/src/Telegram.BotAPI/Getting updates/setWebhook.cs +++ b/src/library/Telegram.BotAPI/Getting updates/setWebhook.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -15,7 +15,7 @@ public static partial class GettingUpdatesExtensions /// Parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool SetWebhook(this BotClient? bot, SetWebhookArgs args) + public static bool SetWebhook(this ITelegramBotClient bot, SetWebhookArgs args) { if (bot == default) { @@ -27,7 +27,7 @@ public static bool SetWebhook(this BotClient? bot, SetWebhookArgs args) throw new ArgumentNullException(nameof(args)); } - return bot.RPCF(MethodNames.SetWebhook, args); + return bot.CallMethod(MethodNames.SetWebhook, args); } /// Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns True on success. /// BotClient @@ -35,7 +35,7 @@ public static bool SetWebhook(this BotClient? bot, SetWebhookArgs args) /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SetWebhookAsync(this BotClient? bot, SetWebhookArgs args, [Optional] CancellationToken cancellationToken) + public static async Task SetWebhookAsync(this ITelegramBotClient bot, SetWebhookArgs args, CancellationToken cancellationToken = default) { if (bot == default) { @@ -47,7 +47,7 @@ public static async Task SetWebhookAsync(this BotClient? bot, SetWebhookAr throw new ArgumentNullException(nameof(args)); } - return await bot.RPCAF(MethodNames.SetWebhook, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetWebhook, args, cancellationToken: cancellationToken).ConfigureAwait(false); } /// Use this method to specify a URL and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified URL, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns True on success. /// The bot client. @@ -61,7 +61,7 @@ public static async Task SetWebhookAsync(this BotClient? bot, SetWebhookAr /// A secret token to be sent in a header “X-Telegram-Bot-Api-Secret-Token” in every webhook request, 1-256 characters. Only characters A-Z, a-z, 0-9, _ and - are allowed. The header is useful to ensure that the request comes from a webhook set by you. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool SetWebhook(this BotClient? api, string url, [Optional] InputFile? certificate, [Optional] string? ipAddress, [Optional] uint? maxConnections, [Optional] IEnumerable? allowedUpdates, [Optional] bool? dropPendingUpdates, [Optional] string? secretToken) + public static bool SetWebhook(this ITelegramBotClient api, string url, [Optional] InputFile? certificate, [Optional] string? ipAddress, [Optional] uint? maxConnections, [Optional] IEnumerable? allowedUpdates, [Optional] bool? dropPendingUpdates, [Optional] string? secretToken) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new SetWebhookArgs(url) @@ -73,7 +73,7 @@ public static bool SetWebhook(this BotClient? api, string url, [Optional] InputF DropPendingUpdates = dropPendingUpdates, SecretToken = secretToken }; - return api.RPCF(MethodNames.SetWebhook, args); + return api.CallMethod(MethodNames.SetWebhook, args); } /// Use this method to specify a URL and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified URL, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns True on success. @@ -89,7 +89,7 @@ public static bool SetWebhook(this BotClient? api, string url, [Optional] InputF /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SetWebhookAsync(this BotClient? api, string url, [Optional] InputFile? certificate, [Optional] string? ipAddress, [Optional] uint? maxConnections, [Optional] IEnumerable? allowedUpdates, [Optional] bool? dropPendingUpdates, [Optional] string? secretToken, [Optional] CancellationToken cancellationToken) + public static async Task SetWebhookAsync(this ITelegramBotClient api, string url, [Optional] InputFile? certificate, [Optional] string? ipAddress, [Optional] uint? maxConnections, [Optional] IEnumerable? allowedUpdates, [Optional] bool? dropPendingUpdates, [Optional] string? secretToken, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new SetWebhookArgs(url) @@ -101,6 +101,6 @@ public static async Task SetWebhookAsync(this BotClient? api, string url, DropPendingUpdates = dropPendingUpdates, SecretToken = secretToken }; - return await api.RPCAF(MethodNames.SetWebhook, args, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.SetWebhook, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/library/Telegram.BotAPI/ITelegramBotClient.cs b/src/library/Telegram.BotAPI/ITelegramBotClient.cs new file mode 100644 index 00000000..9b9a3944 --- /dev/null +++ b/src/library/Telegram.BotAPI/ITelegramBotClient.cs @@ -0,0 +1,76 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System.Net.Http; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace Telegram.BotAPI; + +/// +/// Defines methods to make requests to the Telegram Bot API. +/// +public interface ITelegramBotClient +{ + /// + /// Options used to configure the client. + /// + TelegramBotClientOptions Options { get; } + + /// + /// Calls a method of the Telegram Bot API and returns the result. + /// + /// Result type. + /// Method name. + /// Method arguments. + /// An object containing the result of the API call. + /// The method arguments are invalid. + /// The request failed and the Bot API returned an error. + /// The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation or timeout. + /// The response could not be deserialized. + TResult CallMethod(string method, object? args = null); + + /// + /// Calls a method of the Telegram Bot API and returns the result. + /// + /// Result type. + /// Method name. + /// Method arguments. + /// A to cancel the request. + /// An object containing the result of the API call. + /// The method arguments are invalid. + /// The request failed and the Bot API returned an error. + /// The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation or timeout. + /// The response could not be deserialized. + /// The request was canceled. + Task CallMethodAsync(string method, object? args = null, CancellationToken cancellationToken = default); + + /// + /// Calls a method of the Telegram Bot API and returns the response. + /// + /// Response type. + /// Method name. + /// Method arguments. + /// A object containing the response. + /// The method arguments are invalid. + /// The request failed and the Bot API returned an error. + /// The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation or timeout. + /// The response could not be deserialized. + BotResponse CallMethodDirect(string method, object? args = null); + + /// + /// Calls a method of the Telegram Bot API and returns the response. + /// + /// Response type. + /// Method name. + /// Method arguments. + /// A to cancel the request. + /// A object containing the response. + /// The method arguments are invalid. + /// The request failed and the Bot API returned an error. + /// The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation or timeout. + /// The response could not be deserialized. + /// The request was canceled. + Task> CallMethodDirectAsync(string method, object? args = null, CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/Telegram.BotAPI/Inline mode/Args/AnswerInlineQueryArgs.cs b/src/library/Telegram.BotAPI/Inline mode/Args/AnswerInlineQueryArgs.cs similarity index 98% rename from src/Telegram.BotAPI/Inline mode/Args/AnswerInlineQueryArgs.cs rename to src/library/Telegram.BotAPI/Inline mode/Args/AnswerInlineQueryArgs.cs index af2f1763..3cec4472 100644 --- a/src/Telegram.BotAPI/Inline mode/Args/AnswerInlineQueryArgs.cs +++ b/src/library/Telegram.BotAPI/Inline mode/Args/AnswerInlineQueryArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/Args/AnswerWebAppQueryArgs.cs b/src/library/Telegram.BotAPI/Inline mode/Args/AnswerWebAppQueryArgs.cs similarity index 97% rename from src/Telegram.BotAPI/Inline mode/Args/AnswerWebAppQueryArgs.cs rename to src/library/Telegram.BotAPI/Inline mode/Args/AnswerWebAppQueryArgs.cs index 4ea9fa8f..71f42748 100644 --- a/src/Telegram.BotAPI/Inline mode/Args/AnswerWebAppQueryArgs.cs +++ b/src/library/Telegram.BotAPI/Inline mode/Args/AnswerWebAppQueryArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/ChosenInlineResult.cs b/src/library/Telegram.BotAPI/Inline mode/ChosenInlineResult.cs similarity index 98% rename from src/Telegram.BotAPI/Inline mode/ChosenInlineResult.cs rename to src/library/Telegram.BotAPI/Inline mode/ChosenInlineResult.cs index 56930e60..d08edd87 100644 --- a/src/Telegram.BotAPI/Inline mode/ChosenInlineResult.cs +++ b/src/library/Telegram.BotAPI/Inline mode/ChosenInlineResult.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InlineQuery.cs b/src/library/Telegram.BotAPI/Inline mode/InlineQuery.cs similarity index 99% rename from src/Telegram.BotAPI/Inline mode/InlineQuery.cs rename to src/library/Telegram.BotAPI/Inline mode/InlineQuery.cs index 0574c4b7..e7a62fdb 100644 --- a/src/Telegram.BotAPI/Inline mode/InlineQuery.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InlineQuery.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResult.cs b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResult.cs similarity index 96% rename from src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResult.cs rename to src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResult.cs index a5c1a5fd..c464d96f 100644 --- a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResult.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResult.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; @@ -35,8 +35,8 @@ namespace Telegram.BotAPI.InlineMode; [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] public abstract class InlineQueryResult : ICustomizableReplyMarkup { - /// Type of the result. - public abstract string Type { get; } + /// Type of the result. + public abstract string Type { get; } /// Unique identifier for this result, 1-64 Bytes. [JsonPropertyName(PropertyNames.Id)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] diff --git a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultArticle.cs b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultArticle.cs similarity index 99% rename from src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultArticle.cs rename to src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultArticle.cs index 095e04e8..0c509a7c 100644 --- a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultArticle.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultArticle.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultAudio.cs b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultAudio.cs similarity index 99% rename from src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultAudio.cs rename to src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultAudio.cs index 85e32599..9cad4a4f 100644 --- a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultAudio.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultAudio.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedAudio.cs b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedAudio.cs similarity index 97% rename from src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedAudio.cs rename to src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedAudio.cs index add855be..d34a5190 100644 --- a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedAudio.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedAudio.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedDocument.cs b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedDocument.cs similarity index 99% rename from src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedDocument.cs rename to src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedDocument.cs index 2448fbf4..cb066b62 100644 --- a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedDocument.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedDocument.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedGif.cs b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedGif.cs similarity index 99% rename from src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedGif.cs rename to src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedGif.cs index 4c018e74..4a21e040 100644 --- a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedGif.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedGif.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedMpeg4Gif.cs b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedMpeg4Gif.cs similarity index 99% rename from src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedMpeg4Gif.cs rename to src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedMpeg4Gif.cs index e2f2c0b2..244162d6 100644 --- a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedMpeg4Gif.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedMpeg4Gif.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedPhoto.cs b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedPhoto.cs similarity index 99% rename from src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedPhoto.cs rename to src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedPhoto.cs index 44da86d9..018c734c 100644 --- a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedPhoto.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedPhoto.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedSticker.cs b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedSticker.cs similarity index 98% rename from src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedSticker.cs rename to src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedSticker.cs index 9a47a502..3d30e497 100644 --- a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedSticker.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedSticker.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedVideo.cs b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedVideo.cs similarity index 99% rename from src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedVideo.cs rename to src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedVideo.cs index bb059dcd..484d268b 100644 --- a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedVideo.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedVideo.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedVoice.cs b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedVoice.cs similarity index 99% rename from src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedVoice.cs rename to src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedVoice.cs index 6a25820a..ea35ecf3 100644 --- a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedVoice.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultCachedVoice.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultContact.cs b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultContact.cs similarity index 99% rename from src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultContact.cs rename to src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultContact.cs index b100f321..cdbded86 100644 --- a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultContact.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultContact.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultDocument.cs b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultDocument.cs similarity index 99% rename from src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultDocument.cs rename to src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultDocument.cs index d3c44418..adeb891d 100644 --- a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultDocument.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultDocument.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultGame.cs b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultGame.cs similarity index 98% rename from src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultGame.cs rename to src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultGame.cs index 83825219..4fd1d453 100644 --- a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultGame.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultGame.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultGif.cs b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultGif.cs similarity index 99% rename from src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultGif.cs rename to src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultGif.cs index 47e85446..12ad95f0 100644 --- a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultGif.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultGif.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultLocation.cs b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultLocation.cs similarity index 99% rename from src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultLocation.cs rename to src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultLocation.cs index f15c7ec0..6a773ee9 100644 --- a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultLocation.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultLocation.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultMpeg4Gif.cs b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultMpeg4Gif.cs similarity index 99% rename from src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultMpeg4Gif.cs rename to src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultMpeg4Gif.cs index 89ca25e8..656090e3 100644 --- a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultMpeg4Gif.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultMpeg4Gif.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultPhoto.cs b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultPhoto.cs similarity index 99% rename from src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultPhoto.cs rename to src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultPhoto.cs index 0eb6cfa1..a6c535a6 100644 --- a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultPhoto.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultPhoto.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultType.cs b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultType.cs similarity index 96% rename from src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultType.cs rename to src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultType.cs index cfbe8767..c53d66ac 100644 --- a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultType.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultType.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI.InlineMode; diff --git a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultVenue.cs b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultVenue.cs similarity index 99% rename from src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultVenue.cs rename to src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultVenue.cs index de5edd8f..132c96ff 100644 --- a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultVenue.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultVenue.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultVideo.cs b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultVideo.cs similarity index 99% rename from src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultVideo.cs rename to src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultVideo.cs index 95fbd114..1b46221b 100644 --- a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultVideo.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultVideo.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultVoice.cs b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultVoice.cs similarity index 99% rename from src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultVoice.cs rename to src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultVoice.cs index 2313241b..d09a6b8e 100644 --- a/src/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultVoice.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResult/InlineQueryResultVoice.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InlineQueryResultsButton.cs b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResultsButton.cs similarity index 98% rename from src/Telegram.BotAPI/Inline mode/InlineQueryResultsButton.cs rename to src/library/Telegram.BotAPI/Inline mode/InlineQueryResultsButton.cs index 27633c0b..04362bdc 100644 --- a/src/Telegram.BotAPI/Inline mode/InlineQueryResultsButton.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InlineQueryResultsButton.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InputMessageContent/InputContactMessageContent.cs b/src/library/Telegram.BotAPI/Inline mode/InputMessageContent/InputContactMessageContent.cs similarity index 98% rename from src/Telegram.BotAPI/Inline mode/InputMessageContent/InputContactMessageContent.cs rename to src/library/Telegram.BotAPI/Inline mode/InputMessageContent/InputContactMessageContent.cs index 4b4ecaf4..80b43d17 100644 --- a/src/Telegram.BotAPI/Inline mode/InputMessageContent/InputContactMessageContent.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InputMessageContent/InputContactMessageContent.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Telegram.BotAPI.AvailableTypes; diff --git a/src/Telegram.BotAPI/Inline mode/InputMessageContent/InputInvoiceMessageContent.cs b/src/library/Telegram.BotAPI/Inline mode/InputMessageContent/InputInvoiceMessageContent.cs similarity index 99% rename from src/Telegram.BotAPI/Inline mode/InputMessageContent/InputInvoiceMessageContent.cs rename to src/library/Telegram.BotAPI/Inline mode/InputMessageContent/InputInvoiceMessageContent.cs index ed205935..753cbb43 100644 --- a/src/Telegram.BotAPI/Inline mode/InputMessageContent/InputInvoiceMessageContent.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InputMessageContent/InputInvoiceMessageContent.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InputMessageContent/InputLocationMessageContent.cs b/src/library/Telegram.BotAPI/Inline mode/InputMessageContent/InputLocationMessageContent.cs similarity index 99% rename from src/Telegram.BotAPI/Inline mode/InputMessageContent/InputLocationMessageContent.cs rename to src/library/Telegram.BotAPI/Inline mode/InputMessageContent/InputLocationMessageContent.cs index 6548d50a..fb4e5298 100644 --- a/src/Telegram.BotAPI/Inline mode/InputMessageContent/InputLocationMessageContent.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InputMessageContent/InputLocationMessageContent.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/InputMessageContent/InputMessageContent.cs b/src/library/Telegram.BotAPI/Inline mode/InputMessageContent/InputMessageContent.cs similarity index 95% rename from src/Telegram.BotAPI/Inline mode/InputMessageContent/InputMessageContent.cs rename to src/library/Telegram.BotAPI/Inline mode/InputMessageContent/InputMessageContent.cs index 360df209..4a9f4aee 100644 --- a/src/Telegram.BotAPI/Inline mode/InputMessageContent/InputMessageContent.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InputMessageContent/InputMessageContent.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Telegram.BotAPI.Converters; diff --git a/src/library/Telegram.BotAPI/Inline mode/InputMessageContent/InputTextMessageContent.cs b/src/library/Telegram.BotAPI/Inline mode/InputMessageContent/InputTextMessageContent.cs new file mode 100644 index 00000000..0dfd8cb6 --- /dev/null +++ b/src/library/Telegram.BotAPI/Inline mode/InputMessageContent/InputTextMessageContent.cs @@ -0,0 +1,42 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.InlineMode; + +/// +/// Represents the content of a text message to be sent as the result of an inline query. +/// +/// Text of the message to be sent, 1-4096 characters. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public sealed class InputTextMessageContent(string messageText) : InputMessageContent +{ + /// + /// Text of the message to be sent, 1-4096 characters + /// + [JsonPropertyName(PropertyNames.MessageText)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string MessageText { get; set; } = messageText ?? throw new ArgumentNullException(nameof(messageText)); + /// + /// Optional. Mode for parsing entities in the message text. See formatting options for more details. + /// + [JsonPropertyName(PropertyNames.ParseMode)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? ParseMode { get; set; } + /// + /// Optional. List of special entities that appear in message text, which can be specified instead of parse_mode + /// + [JsonPropertyName(PropertyNames.Entities)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public IEnumerable? Entities { get; set; } + /// + /// Optional. Link preview generation options for the message + /// + [JsonPropertyName(PropertyNames.LinkPreviewOptions)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public LinkPreviewOptions? LinkPreviewOptions { get; set; } +} diff --git a/src/Telegram.BotAPI/Inline mode/InputMessageContent/InputVenueMessageContent.cs b/src/library/Telegram.BotAPI/Inline mode/InputMessageContent/InputVenueMessageContent.cs similarity index 99% rename from src/Telegram.BotAPI/Inline mode/InputMessageContent/InputVenueMessageContent.cs rename to src/library/Telegram.BotAPI/Inline mode/InputMessageContent/InputVenueMessageContent.cs index 259319c9..d9967f78 100644 --- a/src/Telegram.BotAPI/Inline mode/InputMessageContent/InputVenueMessageContent.cs +++ b/src/library/Telegram.BotAPI/Inline mode/InputMessageContent/InputVenueMessageContent.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/SentWebAppMessage.cs b/src/library/Telegram.BotAPI/Inline mode/SentWebAppMessage.cs similarity index 95% rename from src/Telegram.BotAPI/Inline mode/SentWebAppMessage.cs rename to src/library/Telegram.BotAPI/Inline mode/SentWebAppMessage.cs index a082e178..41d878e1 100644 --- a/src/Telegram.BotAPI/Inline mode/SentWebAppMessage.cs +++ b/src/library/Telegram.BotAPI/Inline mode/SentWebAppMessage.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Inline mode/answerInlineQuery.cs b/src/library/Telegram.BotAPI/Inline mode/answerInlineQuery.cs similarity index 79% rename from src/Telegram.BotAPI/Inline mode/answerInlineQuery.cs rename to src/library/Telegram.BotAPI/Inline mode/answerInlineQuery.cs index b15c5c17..f101a3fb 100644 --- a/src/Telegram.BotAPI/Inline mode/answerInlineQuery.cs +++ b/src/library/Telegram.BotAPI/Inline mode/answerInlineQuery.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -18,7 +18,7 @@ public static partial class InlineModeExtensions /// Parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool AnswerInlineQuery(this BotClient? bot, AnswerInlineQueryArgs args) + public static bool AnswerInlineQuery(this ITelegramBotClient bot, AnswerInlineQueryArgs args) { if (bot == default) { @@ -32,10 +32,10 @@ public static bool AnswerInlineQuery(this BotClient? bot, AnswerInlineQueryArgs var stream = new MemoryStream(); using var json = new Utf8JsonWriter(stream); - JsonSerializer.Serialize(json, args, typeof(AnswerInlineQueryArgs), BotClient.DefaultSerializerOptions); + JsonSerializer.Serialize(json, args, typeof(AnswerInlineQueryArgs), TelegramBotClient.SerializerOptions); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.AnswerInlineQuery, stream); + return bot.CallMethod(MethodNames.AnswerInlineQuery, stream); } /// Use this method to send answers to an inline query. On success, True is returned. /// No more than 50 results per query are allowed. @@ -44,7 +44,7 @@ public static bool AnswerInlineQuery(this BotClient? bot, AnswerInlineQueryArgs /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task AnswerInlineQueryAsync(this BotClient? bot, AnswerInlineQueryArgs args, [Optional] CancellationToken cancellationToken) + public static async Task AnswerInlineQueryAsync(this ITelegramBotClient bot, AnswerInlineQueryArgs args, CancellationToken cancellationToken = default) { if (bot == default) { @@ -57,9 +57,9 @@ public static async Task AnswerInlineQueryAsync(this BotClient? bot, Answe } var stream = new MemoryStream(); - await JsonSerializer.SerializeAsync(stream, args, typeof(AnswerInlineQueryArgs), BotClient.DefaultSerializerOptions, cancellationToken: cancellationToken).ConfigureAwait(false); + await JsonSerializer.SerializeAsync(stream, args, typeof(AnswerInlineQueryArgs), TelegramBotClient.SerializerOptions, cancellationToken: cancellationToken).ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.AnswerInlineQuery, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.AnswerInlineQuery, stream, cancellationToken).ConfigureAwait(false); } /// @@ -74,7 +74,7 @@ public static async Task AnswerInlineQueryAsync(this BotClient? bot, Answe /// A JSON-serialized object describing a button to be shown above inline query results. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool AnswerInlineQuery(this BotClient api, string inlineQueryId, IEnumerable results, [Optional] uint? cacheTime, [Optional] bool? isPersonal, [Optional] string? nextOffset, [Optional] InlineQueryResultsButton? button) + public static bool AnswerInlineQuery(this ITelegramBotClient api, string inlineQueryId, IEnumerable results, uint? cacheTime = null, bool? isPersonal = null, string? nextOffset = null, InlineQueryResultsButton? button = null) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new AnswerInlineQueryArgs(inlineQueryId, results) @@ -84,7 +84,7 @@ public static bool AnswerInlineQuery(this BotClient api, string inlineQueryId, I NextOffset = nextOffset, Button = button }; - return api.RPC(MethodNames.AnswerInlineQuery, args); + return api.CallMethod(MethodNames.AnswerInlineQuery, args); } /// @@ -100,7 +100,7 @@ public static bool AnswerInlineQuery(this BotClient api, string inlineQueryId, I /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task AnswerInlineQueryAsync(this BotClient api, string inlineQueryId, IEnumerable results, [Optional] uint? cacheTime, [Optional] bool? isPersonal, [Optional] string? nextOffset, [Optional] InlineQueryResultsButton? button, [Optional] CancellationToken cancellationToken) + public static async Task AnswerInlineQueryAsync(this ITelegramBotClient api, string inlineQueryId, IEnumerable results, uint? cacheTime = null, bool? isPersonal = null, string? nextOffset = null, InlineQueryResultsButton? button = null, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new AnswerInlineQueryArgs(inlineQueryId, results) @@ -110,6 +110,6 @@ public static async Task AnswerInlineQueryAsync(this BotClient api, string NextOffset = nextOffset, Button = button }; - return await api.RPCA(MethodNames.AnswerInlineQuery, args, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.AnswerInlineQuery, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Inline mode/answerWebAppQuery.cs b/src/library/Telegram.BotAPI/Inline mode/answerWebAppQuery.cs similarity index 80% rename from src/Telegram.BotAPI/Inline mode/answerWebAppQuery.cs rename to src/library/Telegram.BotAPI/Inline mode/answerWebAppQuery.cs index d761637c..fa858f73 100644 --- a/src/Telegram.BotAPI/Inline mode/answerWebAppQuery.cs +++ b/src/library/Telegram.BotAPI/Inline mode/answerWebAppQuery.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -15,11 +15,11 @@ public static partial class InlineModeExtensions /// A JSON-serialized object describing the message to be sent. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static SentWebAppMessage AnswerWebAppQuery(this BotClient? api, string webAppQueryId, InlineQueryResult result) + public static SentWebAppMessage AnswerWebAppQuery(this ITelegramBotClient api, string webAppQueryId, InlineQueryResult result) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new AnswerWebAppQueryArgs(webAppQueryId, result); - return api.RPC(MethodNames.AnswerWebAppQuery, args); + return api.CallMethod(MethodNames.AnswerWebAppQuery, args); } /// Use this method to set the result of an interaction with a Web App and send a corresponding message on behalf of the user to the chat from which the query originated. On success, a SentWebAppMessage object is returned. @@ -29,10 +29,10 @@ public static SentWebAppMessage AnswerWebAppQuery(this BotClient? api, string we /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task AnswerWebAppQueryAsync(this BotClient? api, string webAppQueryId, InlineQueryResult result, [Optional] CancellationToken cancellationToken) + public static async Task AnswerWebAppQueryAsync(this ITelegramBotClient api, string webAppQueryId, InlineQueryResult result, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new AnswerWebAppQueryArgs(webAppQueryId, result); - return await api.RPCA(MethodNames.AnswerWebAppQuery, args, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.AnswerWebAppQuery, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/MethodNames.cs b/src/library/Telegram.BotAPI/MethodNames.cs similarity index 94% rename from src/Telegram.BotAPI/MethodNames.cs rename to src/library/Telegram.BotAPI/MethodNames.cs index ccf2bf8a..521d2836 100644 --- a/src/Telegram.BotAPI/MethodNames.cs +++ b/src/library/Telegram.BotAPI/MethodNames.cs @@ -1,9 +1,11 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI; -/// Contains contant strings with all Bot API methods. +/// +/// Contains contant strings with all Bot API methods. +/// public static partial class MethodNames { #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member @@ -20,6 +22,7 @@ public static partial class MethodNames public const string CloseForumTopic = "closeForumTopic"; public const string CloseGeneralForumTopic = "closeGeneralForumTopic"; public const string CopyMessage = "copyMessage"; + public const string CopyMessages = "copyMessages"; public const string CreateChatInviteLink = "createChatInviteLink"; public const string CreateForumTopic = "createForumTopic"; public const string CreateInvoiceLink = "createInvoiceLink"; @@ -29,6 +32,7 @@ public static partial class MethodNames public const string DeleteChatStickerSet = "deleteChatStickerSet"; public const string DeleteForumTopic = "deleteForumTopic"; public const string DeleteMessage = "deleteMessage"; + public const string DeleteMessages = "deleteMessages"; public const string DeleteMyCommands = "deleteMyCommands"; public const string DeleteStickerFromSet = "deleteStickerFromSet"; public const string DeleteStickerSet = "deleteStickerSet"; @@ -43,6 +47,7 @@ public static partial class MethodNames public const string EditMessageText = "editMessageText"; public const string ExportChatInviteLink = "exportChatInviteLink"; public const string ForwardMessage = "forwardMessage"; + public const string ForwardMessages = "forwardMessages"; public const string GetChat = "getChat"; public const string GetChatAdministrators = "getChatAdministrators"; public const string GetChatMember = "getChatMember"; @@ -60,6 +65,7 @@ public static partial class MethodNames public const string GetMyShortDescription = "getMyShortDescription"; public const string GetStickerSet = "getStickerSet"; public const string GetUpdates = "getUpdates"; + public const string GetUserChatBoosts = "getUserChatBoosts"; public const string GetUserProfilePhotos = "getUserProfilePhotos"; public const string GetWebhookInfo = "getWebhookInfo"; public const string HideGeneralForumTopic = "hideGeneralForumTopic"; @@ -69,7 +75,6 @@ public static partial class MethodNames public const string PromoteChatMember = "promoteChatMember"; public const string ReopenForumTopic = "reopenForumTopic"; public const string ReopenGeneralForumTopic = "reopenGeneralForumTopic"; - public const string ReplyKeyboardMarkup = "ReplyKeyboardMarkup"; public const string RestrictChatMember = "restrictChatMember"; public const string RevokeChatInviteLink = "revokeChatInviteLink"; public const string SendAnimation = "sendAnimation"; @@ -97,8 +102,8 @@ public static partial class MethodNames public const string SetChatPhoto = "setChatPhoto"; public const string SetChatStickerSet = "setChatStickerSet"; public const string SetChatTitle = "setChatTitle"; - public const string SetCustomEmojiStickerSetThumbnail = "setCustomEmojiStickerSetThumbnail"; public const string SetGameScore = "setGameScore"; + public const string SetMessageReaction = "setMessageReaction"; public const string SetMyCommands = "setMyCommands"; public const string SetMyDefaultAdministratorRights = "setMyDefaultAdministratorRights"; public const string SetMyDescription = "setMyDescription"; diff --git a/src/Telegram.BotAPI/Payments/Args/AnswerShippingQueryArgs.cs b/src/library/Telegram.BotAPI/Payments/Args/AnswerShippingQueryArgs.cs similarity index 98% rename from src/Telegram.BotAPI/Payments/Args/AnswerShippingQueryArgs.cs rename to src/library/Telegram.BotAPI/Payments/Args/AnswerShippingQueryArgs.cs index cdabdf4b..abd0b53f 100644 --- a/src/Telegram.BotAPI/Payments/Args/AnswerShippingQueryArgs.cs +++ b/src/library/Telegram.BotAPI/Payments/Args/AnswerShippingQueryArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Payments/Args/CreateInvoiceLinkArgs.cs b/src/library/Telegram.BotAPI/Payments/Args/CreateInvoiceLinkArgs.cs similarity index 99% rename from src/Telegram.BotAPI/Payments/Args/CreateInvoiceLinkArgs.cs rename to src/library/Telegram.BotAPI/Payments/Args/CreateInvoiceLinkArgs.cs index 4e98fc49..17847229 100644 --- a/src/Telegram.BotAPI/Payments/Args/CreateInvoiceLinkArgs.cs +++ b/src/library/Telegram.BotAPI/Payments/Args/CreateInvoiceLinkArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Payments/Args/SendInvoiceArgs.cs b/src/library/Telegram.BotAPI/Payments/Args/SendInvoiceArgs.cs similarity index 56% rename from src/Telegram.BotAPI/Payments/Args/SendInvoiceArgs.cs rename to src/library/Telegram.BotAPI/Payments/Args/SendInvoiceArgs.cs index e1631bb2..63013545 100644 --- a/src/Telegram.BotAPI/Payments/Args/SendInvoiceArgs.cs +++ b/src/library/Telegram.BotAPI/Payments/Args/SendInvoiceArgs.cs @@ -1,16 +1,15 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using Telegram.BotAPI.AvailableTypes; - namespace Telegram.BotAPI.Payments; /// SendInvoice method arguments. [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class SendInvoiceArgs : SendMessageBase, ICustomizableReplyMarkup +public class SendInvoiceArgs { /// /// Initialize a new instance of . @@ -23,8 +22,9 @@ public class SendInvoiceArgs : SendMessageBase, ICustomizableReplyMarkupThree-letter ISO 4217 currency code, see more on currencies. /// Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) /// - public SendInvoiceArgs(long chatId, string title, string description, string payload, string providerToken, string currency, IEnumerable prices) : base(chatId) + public SendInvoiceArgs(long chatId, string title, string description, string payload, string providerToken, string currency, IEnumerable prices) { + this.ChatId = chatId; this.Title = title ?? throw new ArgumentNullException(nameof(title)); this.Description = description ?? throw new ArgumentNullException(nameof(description)); this.Payload = payload ?? throw new ArgumentNullException(nameof(payload)); @@ -43,8 +43,9 @@ public SendInvoiceArgs(long chatId, string title, string description, string pay /// Three-letter ISO 4217 currency code, see more on currencies. /// Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) /// - public SendInvoiceArgs(string chatId, string title, string description, string payload, string providerToken, string currency, IEnumerable prices) : base(chatId) + public SendInvoiceArgs(string chatId, string title, string description, string payload, string providerToken, string currency, IEnumerable prices) { + this.ChatId = chatId ?? throw new ArgumentNullException(nameof(chatId)); this.Title = title ?? throw new ArgumentNullException(nameof(title)); this.Description = description ?? throw new ArgumentNullException(nameof(description)); this.Payload = payload ?? throw new ArgumentNullException(nameof(payload)); @@ -53,90 +54,165 @@ public SendInvoiceArgs(string chatId, string title, string description, string p this.Prices = prices ?? throw new ArgumentNullException(nameof(prices)); } - /// Product name, 1-32 characters. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object ChatId { get; set; } + /// + /// Product name, 1-32 characters + /// [JsonPropertyName(PropertyNames.Title)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string Title { get; } - /// Product description, 1-255 characters. + public string Title { get; set; } + /// + /// Product description, 1-255 characters + /// [JsonPropertyName(PropertyNames.Description)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string Description { get; } - /// Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. + public string Description { get; set; } + /// + /// Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. + /// [JsonPropertyName(PropertyNames.Payload)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string Payload { get; } - /// Payments provider token, obtained via Botfather. + public string Payload { get; set; } + /// + /// Payment provider token, obtained via @BotFather + /// [JsonPropertyName(PropertyNames.ProviderToken)] - public string ProviderToken { get; } - /// Three-letter ISO 4217 currency code, see more on currencies. + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string ProviderToken { get; set; } + /// + /// Three-letter ISO 4217 currency code, see more on currencies + /// [JsonPropertyName(PropertyNames.Currency)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string Currency { get; } - /// Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) + public string Currency { get; set; } + /// + /// Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) + /// [JsonPropertyName(PropertyNames.Prices)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public IEnumerable Prices { get; } - /// Optional. The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. + public IEnumerable Prices { get; set; } + /// + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + /// + [JsonPropertyName(PropertyNames.MessageThreadId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? MessageThreadId { get; set; } + /// + /// The maximum accepted amount for tips in the smallest units of the currency (integer, not float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0 + /// [JsonPropertyName(PropertyNames.MaxTipAmount)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public uint? MaxTipAmount { get; set; } - /// Optional. An array of suggested amounts of tip in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount. + /// + /// A JSON-serialized array of suggested amounts of tips in the smallest units of the currency (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount. + /// [JsonPropertyName(PropertyNames.SuggestedTipAmounts)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public IEnumerable? SuggestedTipAmounts { get; set; } - /// Optional. Unique deep-linking parameter. If left empty, forwarded copies of the sent message will have a Pay button, allowing multiple users to pay directly from the forwarded message, using the same invoice. If non-empty, forwarded copies of the sent message will have a URL button with a deep link to the bot (instead of a Pay button), with the value used as the start parameter + /// + /// Unique deep-linking parameter. If left empty, forwarded copies of the sent message will have a Pay button, allowing multiple users to pay directly from the forwarded message, using the same invoice. If non-empty, forwarded copies of the sent message will have a URL button with a deep link to the bot (instead of a Pay button), with the value used as the start parameter + /// [JsonPropertyName(PropertyNames.StartParameter)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? StartParameter { get; set; } - /// Optional. JSON-encoded data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. + /// + /// JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. + /// [JsonPropertyName(PropertyNames.ProviderData)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? ProviderData { get; set; } - /// Optional. URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for. + /// + /// URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for. + /// [JsonPropertyName(PropertyNames.PhotoUrl)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? PhotoUrl { get; set; } - /// Optional. Photo size. + /// + /// Photo size in bytes + /// [JsonPropertyName(PropertyNames.PhotoSize)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public uint? PhotoSize { get; set; } - /// Optional. Photo width. + /// + /// Photo width + /// [JsonPropertyName(PropertyNames.PhotoWidth)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public uint? PhotoWidth { get; set; } - /// Optional. Photo height. + /// + /// Photo height + /// [JsonPropertyName(PropertyNames.PhotoHeight)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public uint? PhotoHeight { get; set; } - /// Optional. Pass True, if you require the user's full name to complete the order. + /// + /// Pass True if you require the user's full name to complete the order + /// [JsonPropertyName(PropertyNames.NeedName)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? NeedName { get; set; } - /// Optional. Pass True, if you require the user's phone number to complete the order. + /// + /// Pass True if you require the user's phone number to complete the order + /// [JsonPropertyName(PropertyNames.NeedPhoneNumber)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? NeedPhoneNumber { get; set; } - /// Optional. Pass True, if you require the user's email address to complete the order. + /// + /// Pass True if you require the user's email address to complete the order + /// [JsonPropertyName(PropertyNames.NeedEmail)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? NeedEmail { get; set; } - /// Optional. Pass True, if you require the user's shipping address to complete the order. + /// + /// Pass True if you require the user's shipping address to complete the order + /// [JsonPropertyName(PropertyNames.NeedShippingAddress)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? NeedShippingAddress { get; set; } - /// Optional. Pass True, if user's phone number should be sent to provider. + /// + /// Pass True if the user's phone number should be sent to provider + /// [JsonPropertyName(PropertyNames.SendPhoneNumberToProvider)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? SendPhoneNumberToProvider { get; set; } - /// Optional. Pass True, if user's email address should be sent to provider. + /// + /// Pass True if the user's email address should be sent to provider + /// [JsonPropertyName(PropertyNames.SendEmailToProvider)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? SendEmailToProvider { get; set; } - /// Optional. Pass True, if the final price depends on the shipping method. + /// + /// Pass True if the final price depends on the shipping method + /// [JsonPropertyName(PropertyNames.IsFlexible)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? IsFlexible { get; set; } - /// Optional. A object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button. + /// + /// Sends the message silently. Users will receive a notification with no sound. + /// + [JsonPropertyName(PropertyNames.DisableNotification)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? DisableNotification { get; set; } + /// + /// Protects the contents of the sent message from forwarding and saving + /// + [JsonPropertyName(PropertyNames.ProtectContent)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? ProtectContent { get; set; } + /// + /// Description of the message to reply to + /// + [JsonPropertyName(PropertyNames.ReplyParameters)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyParameters? ReplyParameters { get; set; } + /// + /// A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button. + /// [JsonPropertyName(PropertyNames.ReplyMarkup)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public InlineKeyboardMarkup? ReplyMarkup { get; set; } diff --git a/src/Telegram.BotAPI/Payments/Invoice.cs b/src/library/Telegram.BotAPI/Payments/Invoice.cs similarity index 98% rename from src/Telegram.BotAPI/Payments/Invoice.cs rename to src/library/Telegram.BotAPI/Payments/Invoice.cs index a3f00ff0..8330714a 100644 --- a/src/Telegram.BotAPI/Payments/Invoice.cs +++ b/src/library/Telegram.BotAPI/Payments/Invoice.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Payments/LabeledPrice.cs b/src/library/Telegram.BotAPI/Payments/LabeledPrice.cs similarity index 98% rename from src/Telegram.BotAPI/Payments/LabeledPrice.cs rename to src/library/Telegram.BotAPI/Payments/LabeledPrice.cs index 74647566..ecd6dfdc 100644 --- a/src/Telegram.BotAPI/Payments/LabeledPrice.cs +++ b/src/library/Telegram.BotAPI/Payments/LabeledPrice.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Payments/OrderInfo.cs b/src/library/Telegram.BotAPI/Payments/OrderInfo.cs similarity index 98% rename from src/Telegram.BotAPI/Payments/OrderInfo.cs rename to src/library/Telegram.BotAPI/Payments/OrderInfo.cs index dea693ed..62511d1b 100644 --- a/src/Telegram.BotAPI/Payments/OrderInfo.cs +++ b/src/library/Telegram.BotAPI/Payments/OrderInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Payments/PreCheckoutQuery.cs b/src/library/Telegram.BotAPI/Payments/PreCheckoutQuery.cs similarity index 99% rename from src/Telegram.BotAPI/Payments/PreCheckoutQuery.cs rename to src/library/Telegram.BotAPI/Payments/PreCheckoutQuery.cs index bbfff04b..f50d93fb 100644 --- a/src/Telegram.BotAPI/Payments/PreCheckoutQuery.cs +++ b/src/library/Telegram.BotAPI/Payments/PreCheckoutQuery.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Payments/ShippingAddress.cs b/src/library/Telegram.BotAPI/Payments/ShippingAddress.cs similarity index 98% rename from src/Telegram.BotAPI/Payments/ShippingAddress.cs rename to src/library/Telegram.BotAPI/Payments/ShippingAddress.cs index 25a262f8..54f7402e 100644 --- a/src/Telegram.BotAPI/Payments/ShippingAddress.cs +++ b/src/library/Telegram.BotAPI/Payments/ShippingAddress.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Payments/ShippingOption.cs b/src/library/Telegram.BotAPI/Payments/ShippingOption.cs similarity index 98% rename from src/Telegram.BotAPI/Payments/ShippingOption.cs rename to src/library/Telegram.BotAPI/Payments/ShippingOption.cs index d61e8903..ad1c9da4 100644 --- a/src/Telegram.BotAPI/Payments/ShippingOption.cs +++ b/src/library/Telegram.BotAPI/Payments/ShippingOption.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Payments/ShippingQuery.cs b/src/library/Telegram.BotAPI/Payments/ShippingQuery.cs similarity index 98% rename from src/Telegram.BotAPI/Payments/ShippingQuery.cs rename to src/library/Telegram.BotAPI/Payments/ShippingQuery.cs index a86daf5e..e77016ab 100644 --- a/src/Telegram.BotAPI/Payments/ShippingQuery.cs +++ b/src/library/Telegram.BotAPI/Payments/ShippingQuery.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Payments/SuccessfulPayment.cs b/src/library/Telegram.BotAPI/Payments/SuccessfulPayment.cs similarity index 99% rename from src/Telegram.BotAPI/Payments/SuccessfulPayment.cs rename to src/library/Telegram.BotAPI/Payments/SuccessfulPayment.cs index e5379fd2..875820dc 100644 --- a/src/Telegram.BotAPI/Payments/SuccessfulPayment.cs +++ b/src/library/Telegram.BotAPI/Payments/SuccessfulPayment.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Payments/answerPreCheckoutQuery.cs b/src/library/Telegram.BotAPI/Payments/answerPreCheckoutQuery.cs similarity index 89% rename from src/Telegram.BotAPI/Payments/answerPreCheckoutQuery.cs rename to src/library/Telegram.BotAPI/Payments/answerPreCheckoutQuery.cs index 4173bcaf..a78b50ee 100644 --- a/src/Telegram.BotAPI/Payments/answerPreCheckoutQuery.cs +++ b/src/library/Telegram.BotAPI/Payments/answerPreCheckoutQuery.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -19,7 +19,7 @@ public static partial class PaymentsExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// On success, True is returned. - public static bool AnswerPreCheckoutQuery(this BotClient? bot, string preCheckoutQueryId, bool ok, [Optional] string errorMessage) + public static bool AnswerPreCheckoutQuery(this ITelegramBotClient bot, string preCheckoutQueryId, bool ok, [Optional] string errorMessage) { if (bot == default) { @@ -43,7 +43,7 @@ public static bool AnswerPreCheckoutQuery(this BotClient? bot, string preCheckou json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.AnswerPreCheckoutQuery, stream); + return bot.CallMethod(MethodNames.AnswerPreCheckoutQuery, stream); } /// Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent. /// Bot Client @@ -54,7 +54,7 @@ public static bool AnswerPreCheckoutQuery(this BotClient? bot, string preCheckou /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task AnswerPreCheckoutQueryAsync(this BotClient? bot, string preCheckoutQueryId, bool ok, [Optional] string errorMessage, [Optional] CancellationToken cancellationToken) + public static async Task AnswerPreCheckoutQueryAsync(this ITelegramBotClient bot, string preCheckoutQueryId, bool ok, [Optional] string errorMessage, CancellationToken cancellationToken = default) { if (bot == default) { @@ -79,6 +79,6 @@ public static async Task AnswerPreCheckoutQueryAsync(this BotClient? bot, await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.AnswerPreCheckoutQuery, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.AnswerPreCheckoutQuery, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Payments/answerShippingQuery.cs b/src/library/Telegram.BotAPI/Payments/answerShippingQuery.cs similarity index 80% rename from src/Telegram.BotAPI/Payments/answerShippingQuery.cs rename to src/library/Telegram.BotAPI/Payments/answerShippingQuery.cs index b2e65342..12b72d48 100644 --- a/src/Telegram.BotAPI/Payments/answerShippingQuery.cs +++ b/src/library/Telegram.BotAPI/Payments/answerShippingQuery.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -14,11 +14,11 @@ public static partial class PaymentsExtensions /// Parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool AnswerShippingQuery(this BotClient? api, AnswerShippingQueryArgs args) + public static bool AnswerShippingQuery(this ITelegramBotClient api, AnswerShippingQueryArgs args) { if (api == null) { throw new ArgumentNullException(nameof(api)); } if (args == default) { throw new ArgumentNullException(nameof(args)); } - return api.RPC(MethodNames.AnswerShippingQuery, args); + return api.CallMethod(MethodNames.AnswerShippingQuery, args); } /// If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned. @@ -27,11 +27,11 @@ public static bool AnswerShippingQuery(this BotClient? api, AnswerShippingQueryA /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task AnswerShippingQueryAsync(this BotClient? api, AnswerShippingQueryArgs args, [Optional] CancellationToken cancellationToken) + public static async Task AnswerShippingQueryAsync(this ITelegramBotClient api, AnswerShippingQueryArgs args, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } if (args == default) { throw new ArgumentNullException(nameof(args)); } - return await api.RPCA(MethodNames.AnswerShippingQuery, args, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.AnswerShippingQuery, args, cancellationToken).ConfigureAwait(false); } /// If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned. @@ -42,7 +42,7 @@ public static async Task AnswerShippingQueryAsync(this BotClient? api, Ans /// Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool AnswerShippingQuery(this BotClient? api, string shippingQueryId, bool ok, [Optional] IEnumerable? shippingOptions, [Optional] string? errorMessage) + public static bool AnswerShippingQuery(this ITelegramBotClient api, string shippingQueryId, bool ok, [Optional] IEnumerable? shippingOptions, [Optional] string? errorMessage) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new AnswerShippingQueryArgs(shippingQueryId, ok) @@ -50,7 +50,7 @@ public static bool AnswerShippingQuery(this BotClient? api, string shippingQuery ShippingOptions = shippingOptions, ErrorMessage = errorMessage }; - return api.RPC(MethodNames.AnswerShippingQuery, args); + return api.CallMethod(MethodNames.AnswerShippingQuery, args); } /// If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned. @@ -62,7 +62,7 @@ public static bool AnswerShippingQuery(this BotClient? api, string shippingQuery /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task AnswerShippingQueryAsync(this BotClient? api, string shippingQueryId, bool ok, [Optional] IEnumerable? shippingOptions, [Optional] string? errorMessage, [Optional] CancellationToken cancellationToken) + public static async Task AnswerShippingQueryAsync(this ITelegramBotClient api, string shippingQueryId, bool ok, [Optional] IEnumerable? shippingOptions, [Optional] string? errorMessage, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new AnswerShippingQueryArgs(shippingQueryId, ok) @@ -70,6 +70,6 @@ public static async Task AnswerShippingQueryAsync(this BotClient? api, str ShippingOptions = shippingOptions, ErrorMessage = errorMessage }; - return await api.RPCA(MethodNames.AnswerShippingQuery, args, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.AnswerShippingQuery, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Payments/createInvoiceLink.cs b/src/library/Telegram.BotAPI/Payments/createInvoiceLink.cs similarity index 81% rename from src/Telegram.BotAPI/Payments/createInvoiceLink.cs rename to src/library/Telegram.BotAPI/Payments/createInvoiceLink.cs index a89cb612..a1190fae 100644 --- a/src/Telegram.BotAPI/Payments/createInvoiceLink.cs +++ b/src/library/Telegram.BotAPI/Payments/createInvoiceLink.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -17,11 +17,11 @@ public static partial class PaymentsExtensions /// Parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static string CreateInvoiceLink(this BotClient? api, CreateInvoiceLinkArgs args) + public static string CreateInvoiceLink(this ITelegramBotClient api, CreateInvoiceLinkArgs args) { if (api == null) { throw new ArgumentNullException(nameof(api)); } if (args == default) { throw new ArgumentNullException(nameof(args)); } - return api.RPC(MethodNames.CreateInvoiceLink, args); + return api.CallMethod(MethodNames.CreateInvoiceLink, args); } /// @@ -32,11 +32,11 @@ public static string CreateInvoiceLink(this BotClient? api, CreateInvoiceLinkArg /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task CreateInvoiceLinkAsync(this BotClient? api, CreateInvoiceLinkArgs args, [Optional] CancellationToken cancellationToken) + public static async Task CreateInvoiceLinkAsync(this ITelegramBotClient api, CreateInvoiceLinkArgs args, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } if (args == default) { throw new ArgumentNullException(nameof(args)); } - return await api.RPCA(MethodNames.CreateInvoiceLink, args, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.CreateInvoiceLink, args, cancellationToken).ConfigureAwait(false); } /// @@ -65,7 +65,7 @@ public static async Task CreateInvoiceLinkAsync(this BotClient? api, Cre /// Pass True, if the final price depends on the shipping method. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static string CreateInvoiceLink(this BotClient? api, string title, string description, string payload, string providerToken, string currency, IEnumerable prices, [Optional] uint? maxTipAmount, [Optional] IEnumerable? suggestedTipAmounts, [Optional] string? providerData, [Optional] string? photoUrl, [Optional] uint? photoSize, [Optional] uint? photoWidth, [Optional] uint? photoHeight, [Optional] bool? needName, [Optional] bool? needPhoneNumber, [Optional] bool? needEmail, [Optional] bool? needShippingAddress, [Optional] bool? sendPhoneNumberToProvider, [Optional] bool? sendEmailToProvider, [Optional] bool? isFlexible) + public static string CreateInvoiceLink(this ITelegramBotClient api, string title, string description, string payload, string providerToken, string currency, IEnumerable prices, [Optional] uint? maxTipAmount, [Optional] IEnumerable? suggestedTipAmounts, [Optional] string? providerData, [Optional] string? photoUrl, [Optional] uint? photoSize, [Optional] uint? photoWidth, [Optional] uint? photoHeight, [Optional] bool? needName, [Optional] bool? needPhoneNumber, [Optional] bool? needEmail, [Optional] bool? needShippingAddress, [Optional] bool? sendPhoneNumberToProvider, [Optional] bool? sendEmailToProvider, [Optional] bool? isFlexible) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new CreateInvoiceLinkArgs(title, description, payload, providerToken, currency, prices) @@ -85,7 +85,7 @@ public static string CreateInvoiceLink(this BotClient? api, string title, string SendEmailToProvider = sendEmailToProvider, IsFlexible = isFlexible }; - return api.RPC(MethodNames.CreateInvoiceLink, args); + return api.CallMethod(MethodNames.CreateInvoiceLink, args); } /// Use this method to create a link for an invoice. Returns the created invoice link as String on success. @@ -113,7 +113,7 @@ public static string CreateInvoiceLink(this BotClient? api, string title, string /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task CreateInvoiceLinkAsync(this BotClient? api, string title, string description, string payload, string providerToken, string currency, IEnumerable prices, [Optional] uint? maxTipAmount, [Optional] IEnumerable? suggestedTipAmounts, [Optional] string? providerData, [Optional] string? photoUrl, [Optional] uint? photoSize, [Optional] uint? photoWidth, [Optional] uint? photoHeight, [Optional] bool? needName, [Optional] bool? needPhoneNumber, [Optional] bool? needEmail, [Optional] bool? needShippingAddress, [Optional] bool? sendPhoneNumberToProvider, [Optional] bool? sendEmailToProvider, [Optional] bool? isFlexible, [Optional] CancellationToken cancellationToken) + public static async Task CreateInvoiceLinkAsync(this ITelegramBotClient api, string title, string description, string payload, string providerToken, string currency, IEnumerable prices, [Optional] uint? maxTipAmount, [Optional] IEnumerable? suggestedTipAmounts, [Optional] string? providerData, [Optional] string? photoUrl, [Optional] uint? photoSize, [Optional] uint? photoWidth, [Optional] uint? photoHeight, [Optional] bool? needName, [Optional] bool? needPhoneNumber, [Optional] bool? needEmail, [Optional] bool? needShippingAddress, [Optional] bool? sendPhoneNumberToProvider, [Optional] bool? sendEmailToProvider, [Optional] bool? isFlexible, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new CreateInvoiceLinkArgs(title, description, payload, providerToken, currency, prices) @@ -133,6 +133,6 @@ public static async Task CreateInvoiceLinkAsync(this BotClient? api, str SendEmailToProvider = sendEmailToProvider, IsFlexible = isFlexible }; - return await api.RPCA(MethodNames.CreateInvoiceLink, args, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.CreateInvoiceLink, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Payments/sendInvoice.cs b/src/library/Telegram.BotAPI/Payments/sendInvoice.cs similarity index 76% rename from src/Telegram.BotAPI/Payments/sendInvoice.cs rename to src/library/Telegram.BotAPI/Payments/sendInvoice.cs index 30a422a0..97864938 100644 --- a/src/Telegram.BotAPI/Payments/sendInvoice.cs +++ b/src/library/Telegram.BotAPI/Payments/sendInvoice.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -15,19 +15,19 @@ public static partial class PaymentsExtensions /// Parameters /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendInvoice(this BotClient? bot, SendInvoiceArgs args) + public static Message SendInvoice(this ITelegramBotClient bot, SendInvoiceArgs args) { - if (bot == default) + if (bot is null) { throw new ArgumentNullException(nameof(bot)); } - if (args == default) + if (args is null) { throw new ArgumentNullException(nameof(args)); } - return bot.RPC(MethodNames.SendInvoice, args); + return bot.CallMethod(MethodNames.SendInvoice, args); } /// Use this method to send invoices. On success, the sent Message is returned. /// BotClient @@ -35,25 +35,25 @@ public static Message SendInvoice(this BotClient? bot, SendInvoiceArgs args) /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendInvoiceAsync(this BotClient? bot, SendInvoiceArgs args, [Optional] CancellationToken cancellationToken) + public static async Task SendInvoiceAsync(this ITelegramBotClient bot, SendInvoiceArgs args, CancellationToken cancellationToken = default) { - if (bot == default) + if (bot is null) { throw new ArgumentNullException(nameof(bot)); } - if (args == default) + if (args is null) { throw new ArgumentNullException(nameof(args)); } - return await bot.RPCA(MethodNames.SendInvoice, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SendInvoice, args, cancellationToken: cancellationToken).ConfigureAwait(false); } /// /// Use this method to send invoices. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Product name, 1-32 characters. /// Product description, 1-255 characters. @@ -79,14 +79,14 @@ public static async Task SendInvoiceAsync(this BotClient? bot, SendInvo /// Pass True if the final price depends on the shipping method. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendInvoice(this BotClient? api, long chatId, string title, string description, string payload, string providerToken, string currency, IEnumerable prices, [Optional] int? messageThreadId, [Optional] uint? maxTipAmount, [Optional] IEnumerable? suggestedTipAmounts, [Optional] string? startParameter, [Optional] string? providerData, [Optional] string? photoUrl, [Optional] uint? photoSize, [Optional] uint? photoWidth, [Optional] uint? photoHeight, [Optional] bool? needName, [Optional] bool? needPhoneNumber, [Optional] bool? needEmail, [Optional] bool? needShippingAddress, [Optional] bool? sendPhoneNumberToProvider, [Optional] bool? sendEmailToProvider, [Optional] bool? isFlexible, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] InlineKeyboardMarkup? replyMarkup) + public static Message SendInvoice(this ITelegramBotClient client, long chatId, string title, string description, string payload, string providerToken, string currency, IEnumerable prices, int? messageThreadId = null, uint? maxTipAmount = null, IEnumerable? suggestedTipAmounts = null, string? startParameter = null, string? providerData = null, string? photoUrl = null, uint? photoSize = null, uint? photoWidth = null, uint? photoHeight = null, bool? needName = null, bool? needPhoneNumber = null, bool? needEmail = null, bool? needShippingAddress = null, bool? sendPhoneNumberToProvider = null, bool? sendEmailToProvider = null, bool? isFlexible = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, InlineKeyboardMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendInvoiceArgs(chatId, title, description, payload, providerToken, currency, prices) { MessageThreadId = messageThreadId, @@ -107,17 +107,16 @@ public static Message SendInvoice(this BotClient? api, long chatId, string title IsFlexible = isFlexible, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPC(MethodNames.SendInvoice, args); + return client.CallMethod(MethodNames.SendInvoice, args); } /// /// Use this method to send invoices. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Product name, 1-32 characters. /// Product description, 1-255 characters. @@ -143,14 +142,14 @@ public static Message SendInvoice(this BotClient? api, long chatId, string title /// Pass True if the final price depends on the shipping method. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendInvoice(this BotClient? api, string chatId, string title, string description, string payload, string providerToken, string currency, IEnumerable prices, [Optional] int? messageThreadId, [Optional] uint? maxTipAmount, [Optional] IEnumerable? suggestedTipAmounts, [Optional] string? startParameter, [Optional] string? providerData, [Optional] string? photoUrl, [Optional] uint? photoSize, [Optional] uint? photoWidth, [Optional] uint? photoHeight, [Optional] bool? needName, [Optional] bool? needPhoneNumber, [Optional] bool? needEmail, [Optional] bool? needShippingAddress, [Optional] bool? sendPhoneNumberToProvider, [Optional] bool? sendEmailToProvider, [Optional] bool? isFlexible, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] InlineKeyboardMarkup? replyMarkup) + public static Message SendInvoice(this ITelegramBotClient client, string chatId, string title, string description, string payload, string providerToken, string currency, IEnumerable prices, int? messageThreadId = null, uint? maxTipAmount = null, IEnumerable? suggestedTipAmounts = null, string? startParameter = null, string? providerData = null, string? photoUrl = null, uint? photoSize = null, uint? photoWidth = null, uint? photoHeight = null, bool? needName = null, bool? needPhoneNumber = null, bool? needEmail = null, bool? needShippingAddress = null, bool? sendPhoneNumberToProvider = null, bool? sendEmailToProvider = null, bool? isFlexible = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, InlineKeyboardMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendInvoiceArgs(chatId, title, description, payload, providerToken, currency, prices) { MessageThreadId = messageThreadId, @@ -171,17 +170,16 @@ public static Message SendInvoice(this BotClient? api, string chatId, string tit IsFlexible = isFlexible, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPC(MethodNames.SendInvoice, args); + return client.CallMethod(MethodNames.SendInvoice, args); } /// /// Use this method to send invoices. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Product name, 1-32 characters. /// Product description, 1-255 characters. @@ -207,15 +205,15 @@ public static Message SendInvoice(this BotClient? api, string chatId, string tit /// Pass True if the final price depends on the shipping method. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendInvoiceAsync(this BotClient? api, long chatId, string title, string description, string payload, string providerToken, string currency, IEnumerable prices, [Optional] int? messageThreadId, [Optional] uint? maxTipAmount, [Optional] IEnumerable? suggestedTipAmounts, [Optional] string? startParameter, [Optional] string? providerData, [Optional] string? photoUrl, [Optional] uint? photoSize, [Optional] uint? photoWidth, [Optional] uint? photoHeight, [Optional] bool? needName, [Optional] bool? needPhoneNumber, [Optional] bool? needEmail, [Optional] bool? needShippingAddress, [Optional] bool? sendPhoneNumberToProvider, [Optional] bool? sendEmailToProvider, [Optional] bool? isFlexible, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] InlineKeyboardMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendInvoiceAsync(this ITelegramBotClient client, long chatId, string title, string description, string payload, string providerToken, string currency, IEnumerable prices, int? messageThreadId = null, uint? maxTipAmount = null, IEnumerable? suggestedTipAmounts = null, string? startParameter = null, string? providerData = null, string? photoUrl = null, uint? photoSize = null, uint? photoWidth = null, uint? photoHeight = null, bool? needName = null, bool? needPhoneNumber = null, bool? needEmail = null, bool? needShippingAddress = null, bool? sendPhoneNumberToProvider = null, bool? sendEmailToProvider = null, bool? isFlexible = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, InlineKeyboardMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendInvoiceArgs(chatId, title, description, payload, providerToken, currency, prices) { MessageThreadId = messageThreadId, @@ -236,17 +234,16 @@ public static async Task SendInvoiceAsync(this BotClient? api, long cha IsFlexible = isFlexible, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCA(MethodNames.SendInvoice, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendInvoice, args, cancellationToken).ConfigureAwait(false); } /// /// Use this method to send invoices. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Product name, 1-32 characters. /// Product description, 1-255 characters. @@ -272,15 +269,15 @@ public static async Task SendInvoiceAsync(this BotClient? api, long cha /// Pass True if the final price depends on the shipping method. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendInvoiceAsync(this BotClient? api, string chatId, string title, string description, string payload, string providerToken, string currency, IEnumerable prices, [Optional] int? messageThreadId, [Optional] uint? maxTipAmount, [Optional] IEnumerable? suggestedTipAmounts, [Optional] string? startParameter, [Optional] string? providerData, [Optional] string? photoUrl, [Optional] uint? photoSize, [Optional] uint? photoWidth, [Optional] uint? photoHeight, [Optional] bool? needName, [Optional] bool? needPhoneNumber, [Optional] bool? needEmail, [Optional] bool? needShippingAddress, [Optional] bool? sendPhoneNumberToProvider, [Optional] bool? sendEmailToProvider, [Optional] bool? isFlexible, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] InlineKeyboardMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task SendInvoiceAsync(this ITelegramBotClient client, string chatId, string title, string description, string payload, string providerToken, string currency, IEnumerable prices, int? messageThreadId = null, uint? maxTipAmount = null, IEnumerable? suggestedTipAmounts = null, string? startParameter = null, string? providerData = null, string? photoUrl = null, uint? photoSize = null, uint? photoWidth = null, uint? photoHeight = null, bool? needName = null, bool? needPhoneNumber = null, bool? needEmail = null, bool? needShippingAddress = null, bool? sendPhoneNumberToProvider = null, bool? sendEmailToProvider = null, bool? isFlexible = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, InlineKeyboardMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendInvoiceArgs(chatId, title, description, payload, providerToken, currency, prices) { MessageThreadId = messageThreadId, @@ -301,10 +298,9 @@ public static async Task SendInvoiceAsync(this BotClient? api, string c IsFlexible = isFlexible, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCA(MethodNames.SendInvoice, args, cancellationToken).ConfigureAwait(false); + return await client.CallMethodAsync(MethodNames.SendInvoice, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/PropertyNames.cs b/src/library/Telegram.BotAPI/PropertyNames.cs similarity index 86% rename from src/Telegram.BotAPI/PropertyNames.cs rename to src/library/Telegram.BotAPI/PropertyNames.cs index 163e392d..e05fc6b7 100644 --- a/src/Telegram.BotAPI/PropertyNames.cs +++ b/src/library/Telegram.BotAPI/PropertyNames.cs @@ -1,15 +1,21 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI; -/// Contains contant strings with all Bot API property names. +/// +/// Contains contant strings with all Bot API property names. +/// public static partial class PropertyNames { #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member public const string AddedToAttachmentMenu = "added_to_attachment_menu"; + public const string AddDate = "add_date"; public const string Address = "address"; + public const string AdditionalChatCount = "additional_chat_count"; + public const string AccentColorId = "accent_color_id"; public const string Action = "action"; + public const string ActorChat = "actor_chat"; public const string ActiveUsernames = "active_usernames"; public const string AllowedUpdates = "allowed_updates"; public const string AllowUserChats = "allow_user_chats"; @@ -25,9 +31,14 @@ public static partial class PropertyNames public const string AudioFileId = "audio_file_id"; public const string AudioUrl = "audio_url"; public const string AuthorSignature = "author_signature"; + public const string AvailableReactions = "available_reactions"; + public const string BackgroundCustomEmojiId = "background_custom_emoji_id"; public const string BigFileId = "big_file_id"; public const string BigFileUniqueId = "big_file_unique_id"; public const string Bio = "bio"; + public const string Boost = "boost"; + public const string Boosts = "boosts"; + public const string BoostId = "boost_id"; public const string BotAdministratorRights = "bot_administrator_rights"; public const string BotIsMember = "bot_is_member"; public const string BotUsername = "bot_username"; @@ -72,6 +83,8 @@ public static partial class PropertyNames public const string ChannelChatCreated = "channel_chat_created"; public const string ChannelPost = CommonNames.ChannelPost; public const string Chat = CommonNames.Chat; + public const string ChatBoost = "chat_boost"; + public const string Chats = "chats"; public const string ChatId = "chat_id"; public const string ChatIsChannel = "chat_is_channel"; public const string ChatIsCreated = "chat_is_created"; @@ -91,6 +104,8 @@ public static partial class PropertyNames public const string Contact = CommonNames.Contact; public const string CorrectOptionId = "correct_option_id"; public const string CountryCode = "country_code"; + public const string CountryCodes = "country_codes"; + public const string CustomEmoji = "custom_emoji"; public const string CreatesJoinRequest = "creates_join_request"; public const string Creator = "creator"; public const string Credentials = "credentials"; @@ -107,7 +122,6 @@ public static partial class PropertyNames public const string DisableContentTypeDetection = "disable_content_type_detection"; public const string DisableEditMessage = "disable_edit_message"; public const string DisableNotification = "disable_notification"; - public const string DisableWebPagePreview = "disable_web_page_preview"; public const string Distance = "distance"; public const string Document = CommonNames.Document; public const string DocumentFileId = "document_file_id"; @@ -129,7 +143,9 @@ public static partial class PropertyNames public const string Explanation = "explanation"; public const string ExplanationEntities = "explanation_entities"; public const string ExplanationParseMode = "explanation_parse_mode"; + public const string ExpirationDate = "expiration_date"; public const string ExpireDate = "expire_date"; + public const string ExternalReply = "external_reply"; public const string FieldName = "field_name"; public const string FileDate = "file_date"; public const string FileHash = "file_hash"; @@ -148,12 +164,7 @@ public static partial class PropertyNames public const string ForumTopicCreated = "forum_topic_created"; public const string ForumTopicEdited = "forum_topic_edited"; public const string ForumTopicReopened = "forum_topic_reopened"; - public const string ForwardDate = "forward_date"; - public const string ForwardFrom = "forward_from"; - public const string ForwardFromChat = "forward_from_chat"; - public const string ForwardFromMessageId = "forward_from_message_id"; - public const string ForwardSenderName = "forward_sender_name"; - public const string ForwardSignature = "forward_signature"; + public const string ForwardOrigin = "forward_origin"; public const string ForwardText = "forward_text"; public const string FoursquareId = "foursquare_id"; public const string FoursquareType = "foursquare_type"; @@ -171,18 +182,26 @@ public static partial class PropertyNames public const string GifHeight = "gif_height"; public const string GifUrl = "gif_url"; public const string GifWidth = "gif_width"; + public const string Giveaway = "giveaway"; + public const string GiveawayCompleted = "giveaway_completed"; + public const string GiveawayCreated = "giveaway_created"; + public const string GiveawayMessage = "giveaway_message"; + public const string GiveawayMessageId = "giveaway_message_id"; + public const string GiveawayWinners = "giveaway_winners"; public const string GooglePlaceId = "google_place_id"; public const string GooglePlaceType = "google_place_type"; public const string GroupChatCreated = "group_chat_created"; - public const string HasSpoiler = "has_spoiler"; + public const string HasAggressiveAntiSpamEnabled = "has_aggressive_anti_spam_enabled"; public const string HasCustomCertificate = "has_custom_certificate"; public const string Hash = "hash"; - public const string HasAggressiveAntiSpamEnabled = "has_aggressive_anti_spam_enabled"; public const string HasHiddenMembers = "has_hidden_members"; - public const string HasPrivateForwards = "has_private_forwards"; public const string HasMediaSpoiler = "has_media_spoiler"; - public const string HasRestrictedVoiceAndVideoMessages = "has_restricted_voice_and_video_messages"; + public const string HasPrivateForwards = "has_private_forwards"; public const string HasProtectedContent = "has_protected_content"; + public const string HasPublicWinners = "has_public_winners"; + public const string HasRestrictedVoiceAndVideoMessages = "has_restricted_voice_and_video_messages"; + public const string HasSpoiler = "has_spoiler"; + public const string HasVisibleHistory = "has_visible_history"; public const string Heading = "heading"; public const string Height = "height"; public const string HideUrl = "hide_url"; @@ -203,10 +222,13 @@ public static partial class PropertyNames public const string IsAnimated = "is_animated"; public const string IsAnonymous = "is_anonymous"; public const string IsAutomaticForward = "is_automatic_forward"; + public const string IsBig = "is_big"; public const string IsBot = "is_bot"; public const string IsClosed = "is_closed"; + public const string IsDisabled = "is_disabled"; public const string IsFlexible = "is_flexible"; public const string IsForum = "is_forum"; + public const string IsManual = "is_manual"; public const string IsMember = "is_member"; public const string IsPersistent = "is_persistent"; public const string IsPersonal = "is_personal"; @@ -214,6 +236,7 @@ public static partial class PropertyNames public const string IsPrimary = "is_primary"; public const string IsRevoked = "is_revoked"; public const string IsTopicMessage = "is_topic_message"; + public const string IsUnclaimed = "is_unclaimed"; public const string IsVideo = "is_video"; public const string JoinByRequest = "join_by_request"; public const string JoinToSendMessages = "join_to_send_messages"; @@ -231,12 +254,14 @@ public static partial class PropertyNames public const string Length = "length"; public const string Limit = "limit"; public const string LinkedChatId = "linked_chat_id"; + public const string LinkPreviewOptions = "link_preview_options"; public const string LivePeriod = "live_period"; public const string Location = CommonNames.Location; public const string LoginUrl = "login_url"; public const string Longitude = "longitude"; public const string MaskPosition = "mask_position"; public const string MaxConnections = "max_connections"; + public const string MaxQuantity = "max_quantity"; public const string MaxTipAmount = "max_tip_amount"; public const string Media = "media"; public const string MediaGroupId = "media_group_id"; @@ -246,8 +271,11 @@ public static partial class PropertyNames public const string MessageAutoDeleteTime = "message_auto_delete_time"; public const string MessageAutoDeleteTimerChanged = "message_auto_delete_timer_changed "; public const string MessageId = "message_id"; + public const string MessageIds = "message_ids"; public const string MessageText = "message_text"; public const string MessageThreadId = "message_thread_id"; + public const string MessageReaction = "message_reaction"; + public const string MessageReactionCount = "message_reaction_count"; public const string MigrateFromChatId = "migrate_from_chat_id"; public const string MigrateToChatId = "migrate_to_chat_id"; public const string MimeType = "mime_type"; @@ -267,16 +295,20 @@ public static partial class PropertyNames public const string NewChatMembers = "new_chat_members"; public const string NewChatPhoto = "new_chat_photo"; public const string NewChatTitle = "new_chat_title"; + public const string NewReaction = "new_reaction"; public const string NextOffset = "next_offset"; public const string Offset = "offset"; public const string Ok = "ok"; public const string OldChatMember = "old_chat_member"; + public const string OldReaction = "old_reaction"; public const string OneTimeKeyboard = "one_time_keyboard"; public const string OnlyIfBanned = "only_if_banned"; + public const string OnlyNewMembers = "only_new_members"; public const string OpenPeriod = "open_period"; public const string OptionIds = "option_ids"; public const string Options = "options"; public const string OrderInfo = "order_info"; + public const string Origin = "origin"; public const string ParseMode = "parse_mode"; public const string PassportData = "passport_data"; public const string Pay = "pay"; @@ -285,6 +317,11 @@ public static partial class PropertyNames public const string PendingUpdateCount = "pending_update_count"; public const string Performer = "performer"; public const string Permissions = "permissions"; + public const string PreferSmallMedia = "prefer_small_media"; + public const string PreferLargeMedia = "prefer_large_media"; + public const string PremiumSubscriptionMonthCount = "premium_subscription_month_count"; + public const string ProfileAccentColorId = "profile_accent_color_id"; + public const string ProfileBackgroundCustomEmojiId = "profile_background_custom_emoji_id"; public const string ProtectContent = "protect_content"; public const string PremiumAnimation = "premium_animation"; public const string PhoneNumber = "phone_number"; @@ -303,6 +340,7 @@ public static partial class PropertyNames public const string Position = "position"; public const string PostCode = "post_code"; public const string PreCheckoutQuery = CommonNames.PreCheckoutQuery; + public const string PrizeDescription = "prize_description"; public const string Prices = "prices"; public const string ProviderData = "provider_data"; public const string ProviderPaymentChargeId = "provider_payment_charge_id"; @@ -311,9 +349,19 @@ public static partial class PropertyNames public const string ProximityAlertTriggered = "proximity_alert_triggered"; public const string Query = "query"; public const string Question = "question"; + public const string Quote = "quote"; + public const string QuoteEntities = "quote_entities"; + public const string QuoteParseMode = "quote_parse_mode"; + public const string QuotePosition = "quote_position"; + public const string Reaction = "reaction"; + public const string Reactions = "reactions"; + public const string RemoveDate = "remove_date"; public const string RemoveKeyboard = "remove_keyboard"; public const string Rights = "rights"; + public const string RemoveCaption = "remove_caption"; + public const string RemovedChatBoost = "removed_chat_boost"; public const string ReplyMarkup = "reply_markup"; + public const string ReplyParameters = "reply_parameters"; public const string ReplyToMessage = "reply_to_message"; public const string ReplyToMessageId = "reply_to_message_id"; public const string RequestChat = "request_chat"; @@ -322,6 +370,7 @@ public static partial class PropertyNames public const string RequestLocation = "request_location"; public const string RequestPoll = "request_poll"; public const string RequestUser = "request_user"; + public const string RequestUsers = "request_users"; public const string RequestWriteAccess = "request_write_access"; public const string ResizeKeyboard = "resize_keyboard"; public const string ResultId = "result_id"; @@ -340,6 +389,8 @@ public static partial class PropertyNames public const string SendEmailToProvider = "send_email_to_provider"; public const string SenderChat = "sender_chat"; public const string SenderChatId = "sender_chat_id"; + public const string SenderUser = "sender_user"; + public const string SenderUserName = "sender_user_name"; public const string SendPhoneNumberToProvider = "send_phone_number_to_provider"; public const string SetName = "set_name"; public const string ShippingAddress = "shipping_address"; @@ -348,6 +399,7 @@ public static partial class PropertyNames public const string ShippingQuery = CommonNames.ShippingQuery; public const string ShippingQueryId = "shipping_query_id"; public const string ShowAlert = "show_alert"; + public const string ShowAboveText = "show_above_text"; public const string ShortDescription = "short_description"; public const string SlowModeDelay = "slow_mode_delay"; public const string SmallFileId = "small_file_id"; @@ -390,6 +442,7 @@ public static partial class PropertyNames public const string Translation = "translation"; public const string Traveler = "traveler"; public const string Type = "type"; + public const string UnclaimedPrizeCount = "unclaimed_prize_count"; public const string UntilDate = "until_date"; public const string UpdateId = "update_id"; public const string Url = "url"; @@ -398,11 +451,12 @@ public static partial class PropertyNames public const string UserAdministratorRights = "user_administrator_rights"; public const string UserChatId = "user__chat_id"; public const string UserId = "user_id"; + public const string UserIds = "user_ids"; public const string UserIsBot = "user_is_bot"; public const string UserIsPremium = "user_is_premium"; public const string Username = "username"; public const string Users = "users"; - public const string UserShared = "user_shared"; + public const string UsersShared = "users_shared"; public const string Value = "value"; public const string Vcard = "vcard"; public const string Venue = CommonNames.Venue; @@ -425,12 +479,16 @@ public static partial class PropertyNames public const string VoiceUrl = "voice_url"; public const string VoterChat = "voter_chat"; public const string VoterCount = "voter_count"; + public const string WasRefunded = "was_refunded"; public const string Watcher = "watcher"; public const string WebApp = CommonNames.WebApp; public const string WebAppName = "web_app_name"; public const string WebAppData = "web_app_data"; public const string WebAppQueryId = "web_app_query_id"; public const string Width = "width"; + public const string Winners = "winners"; + public const string WinnerCount = "winners_count"; + public const string WinnersSelectionDate = "winners_selection_date"; public const string WriteAccessAllowed = "write_access_allowed"; public const string XShift = "x_shift"; public const string YShift = "y_shift"; diff --git a/src/Telegram.BotAPI/README.md b/src/library/Telegram.BotAPI/README.md similarity index 57% rename from src/Telegram.BotAPI/README.md rename to src/library/Telegram.BotAPI/README.md index 86cf5d59..a22708b7 100644 --- a/src/Telegram.BotAPI/README.md +++ b/src/library/Telegram.BotAPI/README.md @@ -1,17 +1,17 @@ # Telegram.BotAPI -[![Compatible with Bot API v6.9](https://img.shields.io/badge/Bot%20API%20version-v6.9-blue?style=flat-square)](https://core.telegram.org/bots/api#september-22-2023) +[![Compatible with Bot API v7.0](https://img.shields.io/badge/Bot%20API%20version-v7.0-blue?style=flat-square)](https://core.telegram.org/bots/api#december-29-2023) **Telegram.BotAPI** is one of the most complete libraries available to interact with the Telegram Bot API in your .NET projects. Free and open source. -It contains all the methods and types available in the Bot API 6.9 released on September 22, 2023. +It contains all the methods and types available in the Bot API 7.0 released on December 29, 2023. --- ## Features -- Contains pre-defined methods for all Bot API 6.9 methods. -- Contains classes for each object type used in the Bot API 6.9. +- Contains pre-defined methods for all Bot API 7.0 methods. +- Contains classes for each object type used in the Bot API 7.0. - Sync and async methods. - Support [System.Text.Json](https://www.nuget.org/packages/System.Text.Json/) and [Newtonsoft.Json](https://www.nuget.org/packages/Newtonsoft.Json/). @@ -19,14 +19,14 @@ It contains all the methods and types available in the Bot API 6.9 released on S ## How to use -First, get your **bot token** from [BotFather](https://t.me/BotFather) and use it to create a new instance of `Telegram.BotAPI.BotClient` as follows. +First, get your **bot token** from [BotFather](https://t.me/BotFather) and use it to create a new instance of `Telegram.BotAPI.TelegramBotClient` as follows. ```CSharp using Telegram.BotAPI; var botToken = "bot123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"; -// You need a BotClient instance if you want access to the Bot API methods. -var api = new BotClient(botToken); +// You need a TelegramBotClient instance if you want access to the Bot API methods. +var client = new TelegramBotClient(botToken); ``` The methods and types are organized in namespaces according to their corresponding section on the [Official Bot API website](https://core.telegram.org/bots/api). So if you want to use a method or type, you must first include the corresponding namespace. @@ -35,7 +35,7 @@ Currently the following namespaces are available: | Name | Description | | :------------------------------- | :----------------------------------------------- | -| Telegram.BotAPI | Contains the BotClient and other utilities | +| Telegram.BotAPI | Contains the TelegramBotClient and other utilities | | Telegram.BotAPI.GettingUpdates | Contains methods and types for getting updates | | Telegram.BotAPI.AvailableTypes | Contains available types | | Telegram.BotAPI.AvailableMethods | Contains available methods | @@ -46,12 +46,12 @@ Currently the following namespaces are available: | Telegram.BotAPI.TelegramPassport | Contains methods and types for Telegram Passport | | Telegram.BotAPI.Games | Contains methods and types for games | -Once the namespaces are included, you are ready to start managing your bot. For example, you can use the [getMe](https://core.telegram.org/bots/api#sendmessage) method to get basic information about your bot. +Once the namespaces are included, you are ready to start managing your bot. For example, you can use the [getMe](https://core.telegram.org/bots/api#getme) method to get basic information about your bot. ```CSharp using Telegram.BotAPI.AvailableMethods; -var me = api.GetMe(); +var me = client.GetMe(); Console.WriteLine("My name is {0}.", me.FirstName); ``` @@ -59,7 +59,7 @@ Console.WriteLine("My name is {0}.", me.FirstName); Every time a user interacts with a bot, bot will receive a new update. Updates contain information about user events, such as a new message or when a button is clicked. If you want your bot to reply to a message, then your bot must be able to get updates first. -Currently, there are two ways to get updates: [Long Polling](###Long-Polling) and [webhooks](###Webhooks). +Currently, there are two ways to get updates: [Long Polling](#long-polling) and [webhooks](#webhooks). ### Long Polling @@ -69,7 +69,7 @@ To get updates using **Long Polling**, you must create a perpetual loop and chec using System.Linq; using Telegram.BotAPI.GettingUpdates; -var updates = api.GetUpdates(); +var updates = client.GetUpdates(); while (true) { if (updates.Any()) @@ -79,11 +79,11 @@ while (true) // Process update } var offset = updates.Last().UpdateId + 1; - updates = api.GetUpdates(offset); + updates = client.GetUpdates(offset); } else { - updates = api.GetUpdates(); + updates = client.GetUpdates(); } } ``` @@ -96,12 +96,16 @@ To receive updates through webhook, you must create a web application. In your A using Telegram.BotAPI.GettingUpdates; [HttpPost] -public IActionResult Post([FromBody] Update update) +public IActionResult Post( + // The secret token is optional, but it's highly recommended to use it. + [FromHeader(Name = "X-Telegram-Bot-Api-Secret-Token")] string secretToken, + [FromBody] Update update) { - if (update == null) + if (update is null) { return BadRequest(); } + // Check if the secret token is valid // Process your update return Ok(); } @@ -114,9 +118,8 @@ api.DeleteWebhook(true); // Delete old webhook api.SetWebhook("https://example.com/"); // Set new webhook ``` -> It's high recommended to use a secret path to access the api controller. - -> Using webhook will disable the `getUpdates` method. Use `deleteWebhook` to enable it again. +> It's high recommended to configurate a secret token to access the api controller through the setWebhook method. This will prevent third parties from accessing your api controller. +> Using a webhook will disable the `getUpdates` method. Use `deleteWebhook` to enable it again. ## Sending messages @@ -133,7 +136,7 @@ Your bot can also send multimedia messages like photos, gifs, videos, and others ## Uploading files -You can send attached files using InputFile objects. You have two ways to do it. +You can also send attached files using InputFile objects. You have two ways to do it: By using an InputFile object directly or by using an AttachedFile object. ### Option 1 @@ -163,6 +166,50 @@ var files = new AttachedFile[] api.SendDocument(chatId, "attach://file56", attachedFiles: files); ``` +## Making custom requests + +The library already includes all types and methods available in the Bot API. However, if you want to use your own types or if you want to be the first one to use new features when they are released, you can use the `CallMethod` and/or `CallMethodDirect` methods defined in the ITelegramBotClient instance. + +```CSharp +var args = new Dictionary() { + { "chat_id", 123456789 }, + { "text", "Hello World!" } +}; +// Message is the type you want to use to deserialize the response result. It can be an in-built type or a custom type created by you. +var message = client.CallMethod("sendMessage", args); +``` + +The previous method is used by all extension methods defined in the library. You can also create your own extension methods to make custom requests if you want. + +```CSharp +public static class TelegramBotClientExtensions +{ + public static Message SendHelloWorld(this ITelegramBotClient client, long chatId) + { + var args = new Dictionary() { + { "chat_id", chatId }, + { "text", "Hello World!" } + }; + return client.CallMethod("sendMessage", args); + } +} +``` + +The library also includes the classes `MethodNames` and `PropertyNames` that contain the names of all methods and properties. + +The `CallMethod` will trigger an exception if the response status code is not OK. If you don't like this behavior, you can use the `CallMethodDirect` method instead. + +```CSharp +var args = new Dictionary() { + { "chat_id", 123456789 }, + { "text", "Hello World!" } +}; +// BotResponse +var response = client.CallMethodDirect("sendMessage", args); +``` + +You'll get a `BotResponse` object as a response. This object contains the status code, the deserialized result or null (if error), the error description and also some error parameters if available. + --- ## Examples diff --git a/src/library/Telegram.BotAPI/Stickers/Args/AddStickerToSetArgs.cs b/src/library/Telegram.BotAPI/Stickers/Args/AddStickerToSetArgs.cs new file mode 100644 index 00000000..251a1767 --- /dev/null +++ b/src/library/Telegram.BotAPI/Stickers/Args/AddStickerToSetArgs.cs @@ -0,0 +1,34 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using Telegram.BotAPI.AvailableMethods; + +namespace Telegram.BotAPI.Stickers; + +/// +/// AddStickerToSet method arguments. +/// +/// User identifier of sticker set owner. +/// Sticker set name. +/// A object with information about the added sticker. If exactly the same sticker had already been added to the set, then the set isn't changed. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class AddStickerToSetArgs(long userId, string name, InputSticker sticker) : AttachedFilesArgsBase +{ + /// User identifier of sticker set owner. + [JsonPropertyName(PropertyNames.UserId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public long UserId { get; } = userId; + /// Sticker set name. + [JsonPropertyName(PropertyNames.Name)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string Name { get; } = name ?? throw new ArgumentNullException(nameof(name)); + /// + /// A object with information about the added sticker. If exactly the same sticker had already been added to the set, then the set isn't changed. + /// + [JsonPropertyName(PropertyNames.Sticker)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public InputSticker Sticker { get; } = sticker ?? throw new ArgumentNullException(nameof(sticker)); +} diff --git a/src/Telegram.BotAPI/Stickers/Args/CreateNewStickerSetArgs.cs b/src/library/Telegram.BotAPI/Stickers/Args/CreateNewStickerSetArgs.cs similarity index 55% rename from src/Telegram.BotAPI/Stickers/Args/CreateNewStickerSetArgs.cs rename to src/library/Telegram.BotAPI/Stickers/Args/CreateNewStickerSetArgs.cs index 17ac6d8e..ad537505 100644 --- a/src/Telegram.BotAPI/Stickers/Args/CreateNewStickerSetArgs.cs +++ b/src/library/Telegram.BotAPI/Stickers/Args/CreateNewStickerSetArgs.cs @@ -1,65 +1,52 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; using Newtonsoft.Json.Serialization; -using System.Linq; -using Telegram.BotAPI.AvailableTypes; +using Telegram.BotAPI.AvailableMethods; namespace Telegram.BotAPI.Stickers; /// CreateNewStickerSet method arguments. +/// User identifier of created sticker set owner. +/// Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only english letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in “_by_<bot username>”. <bot_username> is case insensitive. 1-64 characters. +/// Sticker set title, 1-64 characters. +/// A list of 1-50 initial stickers to be added to the sticker set. +/// Format of stickers in the set, must be one of “static”, “animated”, “video”. +/// [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class CreateNewStickerSetArgs : IMultipartForm +public class CreateNewStickerSetArgs(long userId, string name, string title, IEnumerable stickers, string stickerFormat) : AttachedFilesArgsBase { - /// - /// Initialize a new instance of . - /// - /// User identifier of created sticker set owner. - /// Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only english letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in “_by_<bot username>”. <bot_username> is case insensitive. 1-64 characters. - /// Sticker set title, 1-64 characters. - /// A list of 1-50 initial stickers to be added to the sticker set. - /// Format of stickers in the set, must be one of “static”, “animated”, “video”. - /// - public CreateNewStickerSetArgs(long userId, string name, string title, IEnumerable stickers, string stickerFormat) - { - this.UserId = userId; - this.Name = name ?? throw new ArgumentNullException(nameof(name)); - this.Title = title ?? throw new ArgumentNullException(nameof(title)); - this.Stickers = stickers ?? throw new ArgumentNullException(nameof(stickers)); - this.StickerFormat = stickerFormat ?? throw new ArgumentNullException(nameof(stickerFormat)); - } - /// /// User identifier of created sticker set owner. /// [JsonPropertyName(PropertyNames.UserId)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public long UserId { get; } + public long UserId { get; } = userId; /// /// Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only english letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in “_by_<bot username>”. <bot_username> is case insensitive. 1-64 characters. /// [JsonPropertyName(PropertyNames.Name)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string Name { get; } + public string Name { get; } = name ?? throw new ArgumentNullException(nameof(name)); /// /// Sticker set title, 1-64 characters. /// [JsonPropertyName(PropertyNames.Title)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string Title { get; } + public string Title { get; } = title ?? throw new ArgumentNullException(nameof(title)); /// /// A list of 1-50 initial stickers to be added to the sticker set. /// [JsonPropertyName(PropertyNames.Stickers)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public IEnumerable Stickers { get; } + public IEnumerable Stickers { get; } = stickers ?? throw new ArgumentNullException(nameof(stickers)); /// /// Format of stickers in the set, must be one of “static”, “animated”, “video”. /// [JsonPropertyName(PropertyNames.StickerFormat)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string StickerFormat { get; } + public string StickerFormat { get; } = stickerFormat ?? throw new ArgumentNullException(nameof(stickerFormat)); /// /// Optional. Type of stickers in the set, pass “regular”, “mask”, or “custom_emoji”. By default, a regular sticker set is created. /// @@ -72,11 +59,4 @@ public CreateNewStickerSetArgs(long userId, string name, string title, IEnumerab [JsonPropertyName(PropertyNames.NeedsRepainting)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool? NeedsRepainting { get; set; } - - /// - [System.Text.Json.Serialization.JsonIgnore] - public IEnumerable AttachedFiles { get; set; } = new HashSet(); - - /// - public bool UseMultipart() => this.AttachedFiles.Any(); } diff --git a/src/Telegram.BotAPI/Stickers/Args/SendStickerArgs.cs b/src/library/Telegram.BotAPI/Stickers/Args/SendStickerArgs.cs similarity index 55% rename from src/Telegram.BotAPI/Stickers/Args/SendStickerArgs.cs rename to src/library/Telegram.BotAPI/Stickers/Args/SendStickerArgs.cs index 6fdfa607..bbcdc110 100644 --- a/src/Telegram.BotAPI/Stickers/Args/SendStickerArgs.cs +++ b/src/library/Telegram.BotAPI/Stickers/Args/SendStickerArgs.cs @@ -1,16 +1,16 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; using Newtonsoft.Json.Serialization; -using System.Linq; +using Telegram.BotAPI.AvailableMethods; using Telegram.BotAPI.AvailableTypes; namespace Telegram.BotAPI.Stickers; /// SendSticker method arguments [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class SendStickerArgs : SendMessageWithReplyMarkupBase, IMultipartForm +public class SendStickerArgs : AttachedFilesArgsBase { /// /// Initialize a new instance of . @@ -18,8 +18,9 @@ public class SendStickerArgs : SendMessageWithReplyMarkupBase, IMultipartForm /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .webp file from the Internet, or upload a new one using multipart/form-data. /// - public SendStickerArgs(long chatId, InputFile sticker) : base(chatId) + public SendStickerArgs(long chatId, InputFile sticker) { + this.ChatId = chatId; this.Sticker = sticker ?? throw new ArgumentNullException(nameof(sticker)); } /// @@ -28,8 +29,9 @@ public SendStickerArgs(long chatId, InputFile sticker) : base(chatId) /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .webp file from the Internet, or upload a new one using multipart/form-data. /// - public SendStickerArgs(long chatId, string sticker) : base(chatId) + public SendStickerArgs(long chatId, string sticker) { + this.ChatId = chatId; this.Sticker = sticker ?? throw new ArgumentNullException(nameof(sticker)); } /// @@ -38,8 +40,9 @@ public SendStickerArgs(long chatId, string sticker) : base(chatId) /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .webp file from the Internet, or upload a new one using multipart/form-data. /// - public SendStickerArgs(string chatId, InputFile sticker) : base(chatId) + public SendStickerArgs(string chatId, InputFile sticker) { + this.ChatId = chatId; this.Sticker = sticker ?? throw new ArgumentNullException(nameof(sticker)); } /// @@ -48,36 +51,58 @@ public SendStickerArgs(string chatId, InputFile sticker) : base(chatId) /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). /// Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .webp file from the Internet, or upload a new one using multipart/form-data. /// - public SendStickerArgs(string chatId, string sticker) : base(chatId) + public SendStickerArgs(string chatId, string sticker) { + this.ChatId = chatId; this.Sticker = sticker ?? throw new ArgumentNullException(nameof(sticker)); } - /// Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .webp file from the Internet, or upload a new one using multipart/form-data. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object ChatId { get; set; } + /// + /// Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker from the Internet, or upload a new .WEBP or .TGS sticker using multipart/form-data. More information on Sending Files ». Video stickers can only be sent by a file_id. Animated stickers can't be sent via an HTTP URL. + /// [JsonPropertyName(PropertyNames.Sticker)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public object Sticker { get; set; } /// + /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + /// + [JsonPropertyName(PropertyNames.MessageThreadId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? MessageThreadId { get; set; } + /// /// Emoji associated with the sticker; only for just uploaded stickers /// [JsonPropertyName(PropertyNames.Emoji)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? Emoji { get; set; } - - /// - [System.Text.Json.Serialization.JsonIgnore] - public IEnumerable AttachedFiles { get; set; } = new HashSet(); - - bool IMultipartForm.UseMultipart() - { - if (this.Sticker != default) - { - if (this.Sticker.GetType() == typeof(InputFile)) - { - return true; - } - } - - return this.AttachedFiles.Any(); - } + /// + /// Sends the message silently. Users will receive a notification with no sound. + /// + [JsonPropertyName(PropertyNames.DisableNotification)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? DisableNotification { get; set; } + /// + /// Protects the contents of the sent message from forwarding and saving + /// + [JsonPropertyName(PropertyNames.ProtectContent)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool? ProtectContent { get; set; } + /// + /// Description of the message to reply to + /// + [JsonPropertyName(PropertyNames.ReplyParameters)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyParameters? ReplyParameters { get; set; } + /// + /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. + /// + [JsonPropertyName(PropertyNames.ReplyMarkup)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ReplyMarkup? ReplyMarkup { get; set; } } diff --git a/src/Telegram.BotAPI/Stickers/Args/SetStickerMaskPositionArgs.cs b/src/library/Telegram.BotAPI/Stickers/Args/SetStickerMaskPositionArgs.cs similarity index 97% rename from src/Telegram.BotAPI/Stickers/Args/SetStickerMaskPositionArgs.cs rename to src/library/Telegram.BotAPI/Stickers/Args/SetStickerMaskPositionArgs.cs index cafaca87..e0f7c550 100644 --- a/src/Telegram.BotAPI/Stickers/Args/SetStickerMaskPositionArgs.cs +++ b/src/library/Telegram.BotAPI/Stickers/Args/SetStickerMaskPositionArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Stickers/Args/SetStickerSetThumbnailArgs.cs b/src/library/Telegram.BotAPI/Stickers/Args/SetStickerSetThumbnailArgs.cs similarity index 51% rename from src/Telegram.BotAPI/Stickers/Args/SetStickerSetThumbnailArgs.cs rename to src/library/Telegram.BotAPI/Stickers/Args/SetStickerSetThumbnailArgs.cs index 87ab2ce6..286e6267 100644 --- a/src/Telegram.BotAPI/Stickers/Args/SetStickerSetThumbnailArgs.cs +++ b/src/library/Telegram.BotAPI/Stickers/Args/SetStickerSetThumbnailArgs.cs @@ -1,55 +1,33 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; using Newtonsoft.Json.Serialization; -using System.Linq; -using Telegram.BotAPI.AvailableTypes; +using Telegram.BotAPI.AvailableMethods; namespace Telegram.BotAPI.Stickers; -/// SetStickerSetThumb method arguments. +/// +/// SetStickerSetThumb method arguments. +/// +/// Sticker set name +/// User identifier of the sticker set owner +/// [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class SetStickerSetThumbnailArgs : IMultipartForm +public class SetStickerSetThumbnailArgs(string name, long userId) : AttachedFilesArgsBase { - /// - /// Initialize a new instance of the class using required parameters. - /// - /// Sticker set name - /// User identifier of the sticker set owner - /// - public SetStickerSetThumbnailArgs(string name, long userId) - { - this.Name = name ?? throw new ArgumentNullException(nameof(name)); - this.UserId = userId; - } - /// Sticker set name [JsonPropertyName(PropertyNames.Name)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public string Name { get; } + public string Name { get; } = name ?? throw new ArgumentNullException(nameof(name)); /// User identifier of the sticker set owner [JsonPropertyName(PropertyNames.UserId)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public long UserId { get; } + public long UserId { get; } = userId; /// - /// Optional. A .WEBP or .PNG image with the thumbnail, must be up to 128 kilobytes in size and have a width and height of exactly 100px, or a .TGS animation with a thumbnail up to 32 kilobytes in size (see https://core.telegram.org/stickers#animated-sticker-requirements for animated sticker technical requirements), or a WEBM video with the thumbnail up to 32 kilobytes in size; see https://core.telegram.org/stickers#video-sticker-requirements for video sticker technical requirements. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». Animated and video sticker set thumbnails can't be uploaded via HTTP URL. If omitted, then the thumbnail is dropped and the first sticker is used as the thumbnail. + /// Optional. A .WEBP or .PNG image with the thumbnail, must be up to 128 kilobytes in size and have a width and height of exactly 100px, or a .TGS animation with a thumbnail up to 32 kilobytes in size (see https://core.telegram.org/stickers#animated-sticker-requirements for animated sticker technical requirements), or a WEBM video with the thumbnail up to 32 kilobytes in size; see https://core.telegram.org/stickers#video-sticker-requirements for video sticker technical requirements. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». Animated and video sticker set thumbnails can't be uploaded via HTTP URL. If omitted, then the thumbnail is dropped and the first sticker is used as the thumbnail. /// [JsonPropertyName(PropertyNames.Thumbnail)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public object? Thumbnail { get; set; } - - /// - [System.Text.Json.Serialization.JsonIgnore] - public IEnumerable AttachedFiles { get; set; } = new HashSet(); - - bool IMultipartForm.UseMultipart() - { - if (this.Thumbnail != default && this.Thumbnail.GetType() == typeof(InputFile)) - { - return true; - } - - return this.AttachedFiles.Any(); - } } diff --git a/src/Telegram.BotAPI/Stickers/Args/UploadStickerFileArgs.cs b/src/library/Telegram.BotAPI/Stickers/Args/UploadStickerFileArgs.cs similarity index 86% rename from src/Telegram.BotAPI/Stickers/Args/UploadStickerFileArgs.cs rename to src/library/Telegram.BotAPI/Stickers/Args/UploadStickerFileArgs.cs index 93782378..6832ff46 100644 --- a/src/Telegram.BotAPI/Stickers/Args/UploadStickerFileArgs.cs +++ b/src/library/Telegram.BotAPI/Stickers/Args/UploadStickerFileArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; @@ -15,8 +15,8 @@ public class UploadStickerFileArgs /// Initialize a new instance of the class. /// /// User identifier of sticker file owner. - /// A file with the sticker in .WEBP, .PNG, .TGS, or .WEBM format. See https://core.telegram.org/stickers for technical requirements. More information on Sending Files - /// Format of the sticker, must be one of static, animated, video + /// A file with the sticker in .WEBP, .PNG, .TGS, or .WEBM format. See https://core.telegram.org/stickers for technical requirements. More information on Sending Files � + /// Format of the sticker, must be one of �static�, �animated�, �video� /// public UploadStickerFileArgs(long userId, InputFile sticker, string stickerFormat) { @@ -30,13 +30,13 @@ public UploadStickerFileArgs(long userId, InputFile sticker, string stickerForma [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public long UserId { get; } /// - /// A file with the sticker in .WEBP, .PNG, .TGS, or .WEBM format. See https://core.telegram.org/stickers for technical requirements. More information on Sending Files + /// A file with the sticker in .WEBP, .PNG, .TGS, or .WEBM format. See https://core.telegram.org/stickers for technical requirements. More information on Sending Files � /// [JsonPropertyName(PropertyNames.Sticker)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public InputFile Sticker { get; } /// - /// Format of the sticker, must be one of static, animated, video + /// Format of the sticker, must be one of �static�, �animated�, �video� /// [JsonPropertyName(PropertyNames.StickerFormat)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] diff --git a/src/Telegram.BotAPI/Stickers/InputSticker.cs b/src/library/Telegram.BotAPI/Stickers/InputSticker.cs similarity index 98% rename from src/Telegram.BotAPI/Stickers/InputSticker.cs rename to src/library/Telegram.BotAPI/Stickers/InputSticker.cs index ea8e6389..6efb315d 100644 --- a/src/Telegram.BotAPI/Stickers/InputSticker.cs +++ b/src/library/Telegram.BotAPI/Stickers/InputSticker.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Stickers/MaskPosition.cs b/src/library/Telegram.BotAPI/Stickers/MaskPosition.cs similarity index 98% rename from src/Telegram.BotAPI/Stickers/MaskPosition.cs rename to src/library/Telegram.BotAPI/Stickers/MaskPosition.cs index 6809c099..6146926b 100644 --- a/src/Telegram.BotAPI/Stickers/MaskPosition.cs +++ b/src/library/Telegram.BotAPI/Stickers/MaskPosition.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Stickers/Sticker.cs b/src/library/Telegram.BotAPI/Stickers/Sticker.cs similarity index 99% rename from src/Telegram.BotAPI/Stickers/Sticker.cs rename to src/library/Telegram.BotAPI/Stickers/Sticker.cs index 4d8a01b0..00604656 100644 --- a/src/Telegram.BotAPI/Stickers/Sticker.cs +++ b/src/library/Telegram.BotAPI/Stickers/Sticker.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Stickers/StickerSet.cs b/src/library/Telegram.BotAPI/Stickers/StickerSet.cs similarity index 98% rename from src/Telegram.BotAPI/Stickers/StickerSet.cs rename to src/library/Telegram.BotAPI/Stickers/StickerSet.cs index 3f7f3e2b..965ee6dc 100644 --- a/src/Telegram.BotAPI/Stickers/StickerSet.cs +++ b/src/library/Telegram.BotAPI/Stickers/StickerSet.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Stickers/addStickerToSet.cs b/src/library/Telegram.BotAPI/Stickers/addStickerToSet.cs similarity index 80% rename from src/Telegram.BotAPI/Stickers/addStickerToSet.cs rename to src/library/Telegram.BotAPI/Stickers/addStickerToSet.cs index 36d36926..3c8d1e95 100644 --- a/src/Telegram.BotAPI/Stickers/addStickerToSet.cs +++ b/src/library/Telegram.BotAPI/Stickers/addStickerToSet.cs @@ -1,7 +1,6 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. -using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Telegram.BotAPI.AvailableTypes; @@ -17,7 +16,7 @@ public static partial class StickersExtensions /// Parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool AddStickerToSet(this BotClient? bot, AddStickerToSetArgs args) + public static bool AddStickerToSet(this ITelegramBotClient bot, AddStickerToSetArgs args) { if (bot == default) { @@ -29,7 +28,7 @@ public static bool AddStickerToSet(this BotClient? bot, AddStickerToSetArgs args throw new ArgumentNullException(nameof(args)); } - return bot.RPCF(MethodNames.AddStickerToSet, args); + return bot.CallMethod(MethodNames.AddStickerToSet, args); } /// @@ -40,7 +39,7 @@ public static bool AddStickerToSet(this BotClient? bot, AddStickerToSetArgs args /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task AddStickerToSetAsync(this BotClient? bot, AddStickerToSetArgs args, [Optional] CancellationToken cancellationToken) + public static async Task AddStickerToSetAsync(this ITelegramBotClient bot, AddStickerToSetArgs args, CancellationToken cancellationToken = default) { if (bot == default) { @@ -52,7 +51,7 @@ public static async Task AddStickerToSetAsync(this BotClient? bot, AddStic throw new ArgumentNullException(nameof(args)); } - return await bot.RPCAF(MethodNames.AddStickerToSet, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.AddStickerToSet, args, cancellationToken: cancellationToken).ConfigureAwait(false); } /// @@ -65,14 +64,14 @@ public static async Task AddStickerToSetAsync(this BotClient? bot, AddStic /// Optional. A list of files to attach to the request. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool AddStickerToSet(this BotClient? api, long userId, string name, InputSticker sticker, [Optional] IEnumerable? attachedFiles) + public static bool AddStickerToSet(this ITelegramBotClient api, long userId, string name, InputSticker sticker, [Optional] IEnumerable? attachedFiles) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new AddStickerToSetArgs(userId, name, sticker) { AttachedFiles = attachedFiles ?? Array.Empty() }; - return api.RPCF(MethodNames.AddStickerToSet, args); + return api.CallMethod(MethodNames.AddStickerToSet, args); } /// @@ -86,12 +85,13 @@ public static bool AddStickerToSet(this BotClient? api, long userId, string name /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task AddStickerToSetAsync(this BotClient? api, long userId, string name, InputSticker sticker, [Optional] IEnumerable? attachedFiles, [Optional] CancellationToken cancellationToken) + public static async Task AddStickerToSetAsync(this ITelegramBotClient api, long userId, string name, InputSticker sticker, [Optional] IEnumerable? attachedFiles, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } - var args = new AddStickerToSetArgs(userId, name, sticker) { + var args = new AddStickerToSetArgs(userId, name, sticker) + { AttachedFiles = attachedFiles ?? Array.Empty() }; - return await api.RPCAF(MethodNames.AddStickerToSet, args, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.AddStickerToSet, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Stickers/createNewStickerSet.cs b/src/library/Telegram.BotAPI/Stickers/createNewStickerSet.cs similarity index 81% rename from src/Telegram.BotAPI/Stickers/createNewStickerSet.cs rename to src/library/Telegram.BotAPI/Stickers/createNewStickerSet.cs index 8784193b..e84b2ae8 100644 --- a/src/Telegram.BotAPI/Stickers/createNewStickerSet.cs +++ b/src/library/Telegram.BotAPI/Stickers/createNewStickerSet.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -16,7 +16,7 @@ public static partial class StickersExtensions /// Parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool CreateNewStickerSet(this BotClient? bot, CreateNewStickerSetArgs args) + public static bool CreateNewStickerSet(this ITelegramBotClient bot, CreateNewStickerSetArgs args) { if (bot == default) { @@ -28,7 +28,7 @@ public static bool CreateNewStickerSet(this BotClient? bot, CreateNewStickerSetA throw new ArgumentNullException(nameof(args)); } - return bot.RPCF(MethodNames.CreateNewStickerSet, args); + return bot.CallMethod(MethodNames.CreateNewStickerSet, args); } /// @@ -39,7 +39,7 @@ public static bool CreateNewStickerSet(this BotClient? bot, CreateNewStickerSetA /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task CreateNewStickerSetAsync(this BotClient? bot, CreateNewStickerSetArgs args, [Optional] CancellationToken cancellationToken) + public static async Task CreateNewStickerSetAsync(this ITelegramBotClient bot, CreateNewStickerSetArgs args, CancellationToken cancellationToken = default) { if (bot == default) { @@ -51,7 +51,7 @@ public static async Task CreateNewStickerSetAsync(this BotClient? bot, Cre throw new ArgumentNullException(nameof(args)); } - return await bot.RPCAF(MethodNames.CreateNewStickerSet, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.CreateNewStickerSet, args, cancellationToken: cancellationToken).ConfigureAwait(false); } /// @@ -68,7 +68,7 @@ public static async Task CreateNewStickerSetAsync(this BotClient? bot, Cre /// Optional. A list of files to attach to the request. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool CreateNewStickerSet(this BotClient? api, long userId, string name, string title, IEnumerable stickers, string stickerFormat, [Optional] string? stickerType, [Optional] bool? needsRepainting, [Optional] IEnumerable? attachedFiles) + public static bool CreateNewStickerSet(this ITelegramBotClient api, long userId, string name, string title, IEnumerable stickers, string stickerFormat, [Optional] string? stickerType, [Optional] bool? needsRepainting, [Optional] IEnumerable? attachedFiles) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new CreateNewStickerSetArgs(userId, name, title, stickers, stickerFormat) @@ -77,7 +77,7 @@ public static bool CreateNewStickerSet(this BotClient? api, long userId, string NeedsRepainting = needsRepainting, AttachedFiles = attachedFiles ?? Array.Empty() }; - return api.RPCF(MethodNames.CreateNewStickerSet, args); + return api.CallMethod(MethodNames.CreateNewStickerSet, args); } /// @@ -95,7 +95,7 @@ public static bool CreateNewStickerSet(this BotClient? api, long userId, string /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task CreateNewStickerSetAsync(this BotClient? api, long userId, string name, string title, IEnumerable stickers, string stickerFormat, [Optional] string? stickerType, [Optional] bool? needsRepainting, [Optional] IEnumerable? attachedFiles, [Optional] CancellationToken cancellationToken) + public static async Task CreateNewStickerSetAsync(this ITelegramBotClient api, long userId, string name, string title, IEnumerable stickers, string stickerFormat, [Optional] string? stickerType, [Optional] bool? needsRepainting, [Optional] IEnumerable? attachedFiles, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var args = new CreateNewStickerSetArgs(userId, name, title, stickers, stickerFormat) @@ -104,6 +104,6 @@ public static async Task CreateNewStickerSetAsync(this BotClient? api, lon NeedsRepainting = needsRepainting, AttachedFiles = attachedFiles ?? Array.Empty() }; - return await api.RPCAF(MethodNames.CreateNewStickerSet, args, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.CreateNewStickerSet, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Stickers/deleteStickerFromSet.cs b/src/library/Telegram.BotAPI/Stickers/deleteStickerFromSet.cs similarity index 81% rename from src/Telegram.BotAPI/Stickers/deleteStickerFromSet.cs rename to src/library/Telegram.BotAPI/Stickers/deleteStickerFromSet.cs index 536a988b..0a6c9923 100644 --- a/src/Telegram.BotAPI/Stickers/deleteStickerFromSet.cs +++ b/src/library/Telegram.BotAPI/Stickers/deleteStickerFromSet.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -15,7 +15,7 @@ public static partial class StickersExtensions /// File identifier of the sticker. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool DeleteStickerFromSet(this BotClient? bot, string sticker) + public static bool DeleteStickerFromSet(this ITelegramBotClient bot, string sticker) { if (bot == default) { @@ -29,7 +29,7 @@ public static bool DeleteStickerFromSet(this BotClient? bot, string sticker) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.DeleteStickerFromSet, stream); + return bot.CallMethod(MethodNames.DeleteStickerFromSet, stream); } /// Use this method to delete a sticker from a set created by the bot. Returns True on success. /// BotClient @@ -37,7 +37,7 @@ public static bool DeleteStickerFromSet(this BotClient? bot, string sticker) /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task DeleteStickerFromSetAsync(this BotClient? bot, string sticker, [Optional] CancellationToken cancellationToken) + public static async Task DeleteStickerFromSetAsync(this ITelegramBotClient bot, string sticker, CancellationToken cancellationToken = default) { if (bot == default) { @@ -52,6 +52,6 @@ public static async Task DeleteStickerFromSetAsync(this BotClient? bot, st await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.DeleteStickerFromSet, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.DeleteStickerFromSet, stream, cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Telegram.BotAPI/Stickers/deleteStickerSet.cs b/src/library/Telegram.BotAPI/Stickers/deleteStickerSet.cs similarity index 83% rename from src/Telegram.BotAPI/Stickers/deleteStickerSet.cs rename to src/library/Telegram.BotAPI/Stickers/deleteStickerSet.cs index 2031d594..b4832bc2 100644 --- a/src/Telegram.BotAPI/Stickers/deleteStickerSet.cs +++ b/src/library/Telegram.BotAPI/Stickers/deleteStickerSet.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -18,7 +18,7 @@ public static partial class StickersExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static bool DeleteStickerSet(this BotClient api, string name) + public static bool DeleteStickerSet(this ITelegramBotClient api, string name) { if (api == null) { @@ -32,7 +32,7 @@ public static bool DeleteStickerSet(this BotClient api, string name) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.DeleteStickerSet, stream); + return api.CallMethod(MethodNames.DeleteStickerSet, stream); } /// @@ -44,7 +44,7 @@ public static bool DeleteStickerSet(this BotClient api, string name) /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static async Task DeleteStickerSetAsync(this BotClient api, string name, [Optional] CancellationToken cancellationToken) + public static async Task DeleteStickerSetAsync(this ITelegramBotClient api, string name, CancellationToken cancellationToken = default) { if (api == null) { @@ -57,7 +57,7 @@ public static async Task DeleteStickerSetAsync(this BotClient api, string json.WriteEndObject(); await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.DeleteStickerSet, stream, cancellationToken) + return await api.CallMethodAsync(MethodNames.DeleteStickerSet, stream, cancellationToken) .ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Stickers/getCustomEmojiStickers.cs b/src/library/Telegram.BotAPI/Stickers/getCustomEmojiStickers.cs similarity index 85% rename from src/Telegram.BotAPI/Stickers/getCustomEmojiStickers.cs rename to src/library/Telegram.BotAPI/Stickers/getCustomEmojiStickers.cs index 59fec793..70231da2 100644 --- a/src/Telegram.BotAPI/Stickers/getCustomEmojiStickers.cs +++ b/src/library/Telegram.BotAPI/Stickers/getCustomEmojiStickers.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -18,7 +18,7 @@ public static partial class StickersExtensions /// List of custom emoji identifiers. At most 200 custom emoji identifiers can be specified. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Sticker[] GetCustomEmojiStickers(this BotClient? api, IEnumerable customEmojiIds) + public static Sticker[] GetCustomEmojiStickers(this ITelegramBotClient api, IEnumerable customEmojiIds) { if (api == null) { throw new ArgumentNullException(nameof(api)); } if (customEmojiIds == null) { throw new ArgumentNullException(nameof(customEmojiIds)); } @@ -34,7 +34,7 @@ public static Sticker[] GetCustomEmojiStickers(this BotClient? api, IEnumerable< json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.GetCustomEmojiStickers, stream); + return api.CallMethod(MethodNames.GetCustomEmojiStickers, stream); } /// @@ -45,7 +45,7 @@ public static Sticker[] GetCustomEmojiStickers(this BotClient? api, IEnumerable< /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task GetCustomEmojiStickersAsync(this BotClient? api, IEnumerable customEmojiIds, [Optional] CancellationToken cancellationToken) + public static async Task GetCustomEmojiStickersAsync(this ITelegramBotClient api, IEnumerable customEmojiIds, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } if (customEmojiIds == null) { throw new ArgumentNullException(nameof(customEmojiIds)); } @@ -62,6 +62,6 @@ public static async Task GetCustomEmojiStickersAsync(this BotClient? await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.GetCustomEmojiStickers, stream, cancellationToken).ConfigureAwait(false); + return await api.CallMethodAsync(MethodNames.GetCustomEmojiStickers, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Stickers/getStickerSet.cs b/src/library/Telegram.BotAPI/Stickers/getStickerSet.cs similarity index 81% rename from src/Telegram.BotAPI/Stickers/getStickerSet.cs rename to src/library/Telegram.BotAPI/Stickers/getStickerSet.cs index 8addd457..056f3473 100644 --- a/src/Telegram.BotAPI/Stickers/getStickerSet.cs +++ b/src/library/Telegram.BotAPI/Stickers/getStickerSet.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -16,7 +16,7 @@ public static partial class StickersExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// object. - public static StickerSet GetStickerSet(this BotClient? bot, string name) + public static StickerSet GetStickerSet(this ITelegramBotClient bot, string name) { if (bot == default) { @@ -30,7 +30,7 @@ public static StickerSet GetStickerSet(this BotClient? bot, string name) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.GetStickerSet, stream); + return bot.CallMethod(MethodNames.GetStickerSet, stream); } /// Use this method to get a sticker set. On success, a StickerSet object is returned. /// BotClient @@ -39,7 +39,7 @@ public static StickerSet GetStickerSet(this BotClient? bot, string name) /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task GetStickerSetAsync(this BotClient? bot, string name, [Optional] CancellationToken cancellationToken) + public static async Task GetStickerSetAsync(this ITelegramBotClient bot, string name, CancellationToken cancellationToken = default) { if (bot == default) { @@ -54,6 +54,6 @@ public static async Task GetStickerSetAsync(this BotClient? bot, str await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.GetStickerSet, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.GetStickerSet, stream, cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Telegram.BotAPI/Stickers/sendSticker.cs b/src/library/Telegram.BotAPI/Stickers/sendSticker.cs similarity index 61% rename from src/Telegram.BotAPI/Stickers/sendSticker.cs rename to src/library/Telegram.BotAPI/Stickers/sendSticker.cs index cdca787f..35f1d83c 100644 --- a/src/Telegram.BotAPI/Stickers/sendSticker.cs +++ b/src/library/Telegram.BotAPI/Stickers/sendSticker.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -11,295 +11,287 @@ namespace Telegram.BotAPI.Stickers; public static partial class StickersExtensions { /// Use this method to send static .WEBP or animated .TGS stickers. On success, the sent Message is returned.. - /// BotClient + /// The bot client /// Parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendSticker(this BotClient? bot, SendStickerArgs args) + public static Message SendSticker(this ITelegramBotClient client, SendStickerArgs args) { - if (bot == default) + if (client is null) { - throw new ArgumentNullException(nameof(bot)); + throw new ArgumentNullException(nameof(client)); } - if (args == default) + if (args is null) { throw new ArgumentNullException(nameof(args)); } - return bot.RPCF(MethodNames.SendSticker, args); + return client.CallMethod(MethodNames.SendSticker, args); } /// Use this method to send static .WEBP or animated .TGS stickers. On success, the sent Message is returned.. - /// BotClient + /// The bot client /// Parameters. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendStickerAsync(this BotClient? bot, SendStickerArgs args, [Optional] CancellationToken cancellationToken) + public static Task SendStickerAsync(this ITelegramBotClient client, SendStickerArgs args, CancellationToken cancellationToken = default) { - if (bot == default) + if (client is null) { - throw new ArgumentNullException(nameof(bot)); + throw new ArgumentNullException(nameof(client)); } - if (args == default) + if (args is null) { throw new ArgumentNullException(nameof(args)); } - return await bot.RPCAF(MethodNames.SendSticker, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return client.CallMethodAsync(MethodNames.SendSticker, args, cancellationToken: cancellationToken); } /// /// Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker from the Internet, or upload a new .WEBP or .TGS sticker using multipart/form-data. More information on Sending Files ». Video stickers can only be sent by a file_id. Animated stickers can't be sent via an HTTP URL. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. - /// Emoji associated with the sticker; only for just uploaded stickers + /// Emoji associated with the sticker; only for just uploaded stickers. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendSticker(this BotClient? api, long chatId, InputFile sticker, [Optional] int? messageThreadId, [Optional] string? emoji, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendSticker(this ITelegramBotClient client, long chatId, InputFile sticker, int? messageThreadId = null, string? emoji = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendStickerArgs(chatId, sticker) { MessageThreadId = messageThreadId, Emoji = emoji, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPCF(MethodNames.SendSticker, args); + return client.CallMethod(MethodNames.SendSticker, args); } /// /// Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker from the Internet, or upload a new .WEBP or .TGS sticker using multipart/form-data. More information on Sending Files ». Video stickers can only be sent by a file_id. Animated stickers can't be sent via an HTTP URL. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. - /// Emoji associated with the sticker; only for just uploaded stickers + /// Emoji associated with the sticker; only for just uploaded stickers. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendSticker(this BotClient? api, long chatId, string sticker, [Optional] int? messageThreadId, [Optional] string? emoji, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendSticker(this ITelegramBotClient client, long chatId, string sticker, int? messageThreadId = null, string? emoji = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendStickerArgs(chatId, sticker) { MessageThreadId = messageThreadId, Emoji = emoji, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPCF(MethodNames.SendSticker, args); + return client.CallMethod(MethodNames.SendSticker, args); } /// /// Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker from the Internet, or upload a new .WEBP or .TGS sticker using multipart/form-data. More information on Sending Files ». Video stickers can only be sent by a file_id. Animated stickers can't be sent via an HTTP URL. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. - /// Emoji associated with the sticker; only for just uploaded stickers + /// Emoji associated with the sticker; only for just uploaded stickers. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendSticker(this BotClient? api, string chatId, InputFile sticker, [Optional] int? messageThreadId, [Optional] string? emoji, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendSticker(this ITelegramBotClient client, string chatId, InputFile sticker, int? messageThreadId = null, string? emoji = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendStickerArgs(chatId, sticker) { MessageThreadId = messageThreadId, Emoji = emoji, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPCF(MethodNames.SendSticker, args); + return client.CallMethod(MethodNames.SendSticker, args); } /// /// Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker from the Internet, or upload a new .WEBP or .TGS sticker using multipart/form-data. More information on Sending Files ». Video stickers can only be sent by a file_id. Animated stickers can't be sent via an HTTP URL. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. - /// Emoji associated with the sticker; only for just uploaded stickers + /// Emoji associated with the sticker; only for just uploaded stickers. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Message SendSticker(this BotClient? api, string chatId, string sticker, [Optional] int? messageThreadId, [Optional] string? emoji, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup) + public static Message SendSticker(this ITelegramBotClient client, string chatId, string sticker, int? messageThreadId = null, string? emoji = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendStickerArgs(chatId, sticker) { MessageThreadId = messageThreadId, Emoji = emoji, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return api.RPCF(MethodNames.SendSticker, args); + return client.CallMethod(MethodNames.SendSticker, args); } /// /// Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker from the Internet, or upload a new .WEBP or .TGS sticker using multipart/form-data. More information on Sending Files ». Video stickers can only be sent by a file_id. Animated stickers can't be sent via an HTTP URL. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. - /// Emoji associated with the sticker; only for just uploaded stickers + /// Emoji associated with the sticker; only for just uploaded stickers. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendStickerAsync(this BotClient? api, long chatId, InputFile sticker, [Optional] int? messageThreadId, [Optional] string? emoji, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static Task SendStickerAsync(this ITelegramBotClient client, long chatId, InputFile sticker, int? messageThreadId = null, string? emoji = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendStickerArgs(chatId, sticker) { MessageThreadId = messageThreadId, Emoji = emoji, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCAF(MethodNames.SendSticker, args, cancellationToken).ConfigureAwait(false); + return client.CallMethodAsync(MethodNames.SendSticker, args, cancellationToken); } /// /// Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker from the Internet, or upload a new .WEBP or .TGS sticker using multipart/form-data. More information on Sending Files ». Video stickers can only be sent by a file_id. Animated stickers can't be sent via an HTTP URL. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. - /// Emoji associated with the sticker; only for just uploaded stickers + /// Emoji associated with the sticker; only for just uploaded stickers. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendStickerAsync(this BotClient? api, long chatId, string sticker, [Optional] int? messageThreadId, [Optional] string? emoji, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static Task SendStickerAsync(this ITelegramBotClient client, long chatId, string sticker, int? messageThreadId = null, string? emoji = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendStickerArgs(chatId, sticker) { MessageThreadId = messageThreadId, Emoji = emoji, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCAF(MethodNames.SendSticker, args, cancellationToken).ConfigureAwait(false); + return client.CallMethodAsync(MethodNames.SendSticker, args, cancellationToken); } /// /// Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker from the Internet, or upload a new .WEBP or .TGS sticker using multipart/form-data. More information on Sending Files ». Video stickers can only be sent by a file_id. Animated stickers can't be sent via an HTTP URL. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. - /// Emoji associated with the sticker; only for just uploaded stickers + /// Emoji associated with the sticker; only for just uploaded stickers. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendStickerAsync(this BotClient? api, string chatId, InputFile sticker, [Optional] int? messageThreadId, [Optional] string? emoji, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static Task SendStickerAsync(this ITelegramBotClient client, string chatId, InputFile sticker, int? messageThreadId = null, string? emoji = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendStickerArgs(chatId, sticker) { MessageThreadId = messageThreadId, Emoji = emoji, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCAF(MethodNames.SendSticker, args, cancellationToken).ConfigureAwait(false); + return client.CallMethodAsync(MethodNames.SendSticker, args, cancellationToken); } /// /// Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned. /// - /// The bot client. + /// The bot client. /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). - /// Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ┬╗. + /// Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker from the Internet, or upload a new .WEBP or .TGS sticker using multipart/form-data. More information on Sending Files ». Video stickers can only be sent by a file_id. Animated stickers can't be sent via an HTTP URL. /// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only. - /// Emoji associated with the sticker; only for just uploaded stickers + /// Emoji associated with the sticker; only for just uploaded stickers. /// Sends the message silently. Users will receive a notification with no sound. /// Protects the contents of the sent message from forwarding and saving. - /// If the message is a reply, ID of the original message. - /// Pass True if the message should be sent even if the specified replied-to message is not found. + /// Description of the message to reply to. /// Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SendStickerAsync(this BotClient? api, string chatId, string sticker, [Optional] int? messageThreadId, [Optional] string? emoji, [Optional] bool? disableNotification, [Optional] bool? protectContent, [Optional] int? replyToMessageId, [Optional] bool? allowSendingWithoutReply, [Optional] ReplyMarkup? replyMarkup, [Optional] CancellationToken cancellationToken) + public static Task SendStickerAsync(this ITelegramBotClient client, string chatId, string sticker, int? messageThreadId = null, string? emoji = null, bool? disableNotification = null, bool? protectContent = null, ReplyParameters? replyParameters = null, ReplyMarkup? replyMarkup = null, CancellationToken cancellationToken = default) { - if (api == null) { throw new ArgumentNullException(nameof(api)); } + if (client is null) + throw new ArgumentNullException(nameof(client)); var args = new SendStickerArgs(chatId, sticker) { MessageThreadId = messageThreadId, Emoji = emoji, DisableNotification = disableNotification, ProtectContent = protectContent, - ReplyToMessageId = replyToMessageId, - AllowSendingWithoutReply = allowSendingWithoutReply, + ReplyParameters = replyParameters, ReplyMarkup = replyMarkup }; - return await api.RPCAF(MethodNames.SendSticker, args, cancellationToken).ConfigureAwait(false); + return client.CallMethodAsync(MethodNames.SendSticker, args, cancellationToken); } } diff --git a/src/Telegram.BotAPI/Stickers/setStickerEmojiList.cs b/src/library/Telegram.BotAPI/Stickers/setStickerEmojiList.cs similarity index 88% rename from src/Telegram.BotAPI/Stickers/setStickerEmojiList.cs rename to src/library/Telegram.BotAPI/Stickers/setStickerEmojiList.cs index 83b3823b..18fde9ff 100644 --- a/src/Telegram.BotAPI/Stickers/setStickerEmojiList.cs +++ b/src/library/Telegram.BotAPI/Stickers/setStickerEmojiList.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -19,7 +19,7 @@ public static partial class StickersExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static bool SetStickerEmojiList(this BotClient api, string sticker, T emojiList) + public static bool SetStickerEmojiList(this ITelegramBotClient api, string sticker, T emojiList) where T : IEnumerable { if (api == null) @@ -40,7 +40,7 @@ public static bool SetStickerEmojiList(this BotClient api, string sticker, T json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.SetStickerEmojiList, stream); + return api.CallMethod(MethodNames.SetStickerEmojiList, stream); } /// @@ -53,7 +53,7 @@ public static bool SetStickerEmojiList(this BotClient api, string sticker, T /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static async Task SetStickerEmojiListAsync(this BotClient api, string sticker, T emojiList, [Optional] CancellationToken cancellationToken) + public static async Task SetStickerEmojiListAsync(this ITelegramBotClient api, string sticker, T emojiList, CancellationToken cancellationToken = default) where T : IEnumerable { if (api == null) @@ -73,7 +73,7 @@ public static async Task SetStickerEmojiListAsync(this BotClient api, s json.WriteEndObject(); await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.SetStickerEmojiList, stream, cancellationToken) + return await api.CallMethodAsync(MethodNames.SetStickerEmojiList, stream, cancellationToken) .ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Stickers/setStickerKeywords.cs b/src/library/Telegram.BotAPI/Stickers/setStickerKeywords.cs similarity index 87% rename from src/Telegram.BotAPI/Stickers/setStickerKeywords.cs rename to src/library/Telegram.BotAPI/Stickers/setStickerKeywords.cs index f82b4a14..61f990d6 100644 --- a/src/Telegram.BotAPI/Stickers/setStickerKeywords.cs +++ b/src/library/Telegram.BotAPI/Stickers/setStickerKeywords.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -19,7 +19,7 @@ public static partial class StickersExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static bool SetStickerKeywords(this BotClient api, string sticker, [Optional] T? keywords) + public static bool SetStickerKeywords(this ITelegramBotClient api, string sticker, [Optional] T? keywords) where T : IEnumerable { if (api == null) @@ -43,7 +43,7 @@ public static bool SetStickerKeywords(this BotClient api, string sticker, [Op json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.SetStickerKeywords, stream); + return api.CallMethod(MethodNames.SetStickerKeywords, stream); } /// @@ -56,7 +56,7 @@ public static bool SetStickerKeywords(this BotClient api, string sticker, [Op /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static async Task SetStickerKeywordsAsync(this BotClient api, string sticker, [Optional] T? keywords, [Optional] CancellationToken cancellationToken) + public static async Task SetStickerKeywordsAsync(this ITelegramBotClient api, string sticker, [Optional] T? keywords, CancellationToken cancellationToken = default) where T : IEnumerable { if (api == null) @@ -79,7 +79,7 @@ public static async Task SetStickerKeywordsAsync(this BotClient api, st json.WriteEndObject(); await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.SetStickerKeywords, stream, cancellationToken) + return await api.CallMethodAsync(MethodNames.SetStickerKeywords, stream, cancellationToken) .ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Stickers/setStickerMaskPosition.cs b/src/library/Telegram.BotAPI/Stickers/setStickerMaskPosition.cs similarity index 81% rename from src/Telegram.BotAPI/Stickers/setStickerMaskPosition.cs rename to src/library/Telegram.BotAPI/Stickers/setStickerMaskPosition.cs index 818aefda..094113cd 100644 --- a/src/Telegram.BotAPI/Stickers/setStickerMaskPosition.cs +++ b/src/library/Telegram.BotAPI/Stickers/setStickerMaskPosition.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -16,14 +16,14 @@ public static partial class StickersExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static bool SetStickerMaskPosition(this BotClient api, SetStickerMaskPositionArgs args) + public static bool SetStickerMaskPosition(this ITelegramBotClient api, SetStickerMaskPositionArgs args) { if (api == null) { throw new ArgumentNullException(nameof(api)); } - return api.RPC(MethodNames.SetStickerMaskPosition, args); + return api.CallMethod(MethodNames.SetStickerMaskPosition, args); } /// @@ -35,14 +35,14 @@ public static bool SetStickerMaskPosition(this BotClient api, SetStickerMaskPosi /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static async Task SetStickerMaskPositionAsync(this BotClient api, SetStickerMaskPositionArgs args, [Optional] CancellationToken cancellationToken) + public static async Task SetStickerMaskPositionAsync(this ITelegramBotClient api, SetStickerMaskPositionArgs args, CancellationToken cancellationToken = default) { if (api == null) { throw new ArgumentNullException(nameof(api)); } - return await api.RPCA(MethodNames.SetStickerMaskPosition, args, cancellationToken) + return await api.CallMethodAsync(MethodNames.SetStickerMaskPosition, args, cancellationToken) .ConfigureAwait(false); } @@ -55,7 +55,7 @@ public static async Task SetStickerMaskPositionAsync(this BotClient api /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static bool SetStickerMaskPosition(this BotClient api, string sticker, [Optional] MaskPosition? maskPosition) + public static bool SetStickerMaskPosition(this ITelegramBotClient api, string sticker, [Optional] MaskPosition? maskPosition) { if (api == null) { @@ -66,7 +66,7 @@ public static bool SetStickerMaskPosition(this BotClient api, string sticker, [O { MaskPosition = maskPosition }; - return api.RPC(MethodNames.SetStickerMaskPosition, args); + return api.CallMethod(MethodNames.SetStickerMaskPosition, args); } /// @@ -79,7 +79,7 @@ public static bool SetStickerMaskPosition(this BotClient api, string sticker, [O /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static async Task SetStickerMaskPositionAsync(this BotClient api, string sticker, [Optional] MaskPosition? maskPosition, [Optional] CancellationToken cancellationToken) + public static async Task SetStickerMaskPositionAsync(this ITelegramBotClient api, string sticker, [Optional] MaskPosition? maskPosition, CancellationToken cancellationToken = default) { if (api == null) { @@ -90,7 +90,7 @@ public static async Task SetStickerMaskPositionAsync(this BotClient api, s { MaskPosition = maskPosition }; - return await api.RPCA(MethodNames.SetStickerMaskPosition, args, cancellationToken) + return await api.CallMethodAsync(MethodNames.SetStickerMaskPosition, args, cancellationToken) .ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Stickers/setStickerPositionInSet.cs b/src/library/Telegram.BotAPI/Stickers/setStickerPositionInSet.cs similarity index 84% rename from src/Telegram.BotAPI/Stickers/setStickerPositionInSet.cs rename to src/library/Telegram.BotAPI/Stickers/setStickerPositionInSet.cs index 6ec1ab1d..4c3a5b50 100644 --- a/src/Telegram.BotAPI/Stickers/setStickerPositionInSet.cs +++ b/src/library/Telegram.BotAPI/Stickers/setStickerPositionInSet.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -17,7 +17,7 @@ public static partial class StickersExtensions /// New sticker position in the set, zero-based. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool SetStickerPositionInSet(this BotClient? bot, string sticker, int position) + public static bool SetStickerPositionInSet(this ITelegramBotClient bot, string sticker, int position) { if (bot == default) { @@ -32,7 +32,7 @@ public static bool SetStickerPositionInSet(this BotClient? bot, string sticker, json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.SetStickerPositionInSet, stream); + return bot.CallMethod(MethodNames.SetStickerPositionInSet, stream); } /// Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success. /// BotClient @@ -41,7 +41,7 @@ public static bool SetStickerPositionInSet(this BotClient? bot, string sticker, /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SetStickerPositionInSetAsync(this BotClient? bot, string sticker, int position, [Optional] CancellationToken cancellationToken) + public static async Task SetStickerPositionInSetAsync(this ITelegramBotClient bot, string sticker, int position, CancellationToken cancellationToken = default) { if (bot == default) { @@ -57,6 +57,6 @@ public static async Task SetStickerPositionInSetAsync(this BotClient? bot, await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.SetStickerPositionInSet, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetStickerPositionInSet, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Stickers/setStickerSetThumbnail.cs b/src/library/Telegram.BotAPI/Stickers/setStickerSetThumbnail.cs similarity index 78% rename from src/Telegram.BotAPI/Stickers/setStickerSetThumbnail.cs rename to src/library/Telegram.BotAPI/Stickers/setStickerSetThumbnail.cs index 3ceaad9f..d055f504 100644 --- a/src/Telegram.BotAPI/Stickers/setStickerSetThumbnail.cs +++ b/src/library/Telegram.BotAPI/Stickers/setStickerSetThumbnail.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -17,7 +17,7 @@ public static partial class StickersExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static bool SetStickerSetThumbnail(this BotClient? bot, SetStickerSetThumbnailArgs args) + public static bool SetStickerSetThumbnail(this ITelegramBotClient bot, SetStickerSetThumbnailArgs args) { if (bot == default) { @@ -29,7 +29,7 @@ public static bool SetStickerSetThumbnail(this BotClient? bot, SetStickerSetThum throw new ArgumentNullException(nameof(args)); } - return bot.RPCF(MethodNames.SetStickerSetThumbnail, args); + return bot.CallMethod(MethodNames.SetStickerSetThumbnail, args); } /// Use this method to set the thumbnail of a sticker set. Animated thumbnails can be set for animated sticker sets only. Returns True on success. /// BotClient @@ -38,7 +38,7 @@ public static bool SetStickerSetThumbnail(this BotClient? bot, SetStickerSetThum /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static async Task SetStickerSetThumbAsync(this BotClient? bot, SetStickerSetThumbnailArgs args, [Optional] CancellationToken cancellationToken) + public static async Task SetStickerSetThumbAsync(this ITelegramBotClient bot, SetStickerSetThumbnailArgs args, CancellationToken cancellationToken = default) { if (bot == default) { @@ -50,7 +50,7 @@ public static async Task SetStickerSetThumbAsync(this BotClient? bot, SetS throw new ArgumentNullException(nameof(args)); } - return await bot.RPCAF(MethodNames.SetStickerSetThumbnail, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetStickerSetThumbnail, args, cancellationToken: cancellationToken).ConfigureAwait(false); } /// Use this method to set the thumbnail of a sticker set. Animated thumbnails can be set for animated sticker sets only. Returns True on success. @@ -60,7 +60,7 @@ public static async Task SetStickerSetThumbAsync(this BotClient? bot, SetS /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static bool SetStickerSetThumbnail(this BotClient? bot, string name, long userId) + public static bool SetStickerSetThumbnail(this ITelegramBotClient bot, string name, long userId) { if (bot == default) { @@ -85,17 +85,17 @@ public static bool SetStickerSetThumbnail(this BotClient? bot, string name, long json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.SetStickerSetThumbnail, stream); + return bot.CallMethod(MethodNames.SetStickerSetThumbnail, stream); } /// Use this method to set the thumbnail of a sticker set. Animated thumbnails can be set for animated sticker sets only. Returns True on success. /// BotClient /// Sticker set name /// User identifier of the sticker set owner - /// Optional. A .WEBP or .PNG image with the thumbnail, must be up to 128 kilobytes in size and have a width and height of exactly 100px, or a .TGS animation with a thumbnail up to 32 kilobytes in size (see https://core.telegram.org/stickers#animated-sticker-requirements for animated sticker technical requirements), or a WEBM video with the thumbnail up to 32 kilobytes in size; see https://core.telegram.org/stickers#video-sticker-requirements for video sticker technical requirements. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». Animated and video sticker set thumbnails can't be uploaded via HTTP URL. If omitted, then the thumbnail is dropped and the first sticker is used as the thumbnail. + /// Optional. A .WEBP or .PNG image with the thumbnail, must be up to 128 kilobytes in size and have a width and height of exactly 100px, or a .TGS animation with a thumbnail up to 32 kilobytes in size (see https://core.telegram.org/stickers#animated-sticker-requirements for animated sticker technical requirements), or a WEBM video with the thumbnail up to 32 kilobytes in size; see https://core.telegram.org/stickers#video-sticker-requirements for video sticker technical requirements. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». Animated and video sticker set thumbnails can't be uploaded via HTTP URL. If omitted, then the thumbnail is dropped and the first sticker is used as the thumbnail. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static bool SetStickerSetThumbnail(this BotClient? bot, string name, long userId, string thumbnail) + public static bool SetStickerSetThumbnail(this ITelegramBotClient bot, string name, long userId, string thumbnail) { if (bot == default) { @@ -126,17 +126,17 @@ public static bool SetStickerSetThumbnail(this BotClient? bot, string name, long json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.SetStickerSetThumbnail, stream); + return bot.CallMethod(MethodNames.SetStickerSetThumbnail, stream); } /// Use this method to set the thumbnail of a sticker set. Animated thumbnails can be set for animated sticker sets only. Returns True on success. /// BotClient /// Sticker set name /// User identifier of the sticker set owner - /// Optional. A .WEBP or .PNG image with the thumbnail, must be up to 128 kilobytes in size and have a width and height of exactly 100px, or a .TGS animation with a thumbnail up to 32 kilobytes in size (see https://core.telegram.org/stickers#animated-sticker-requirements for animated sticker technical requirements), or a WEBM video with the thumbnail up to 32 kilobytes in size; see https://core.telegram.org/stickers#video-sticker-requirements for video sticker technical requirements. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». Animated and video sticker set thumbnails can't be uploaded via HTTP URL. If omitted, then the thumbnail is dropped and the first sticker is used as the thumbnail. + /// Optional. A .WEBP or .PNG image with the thumbnail, must be up to 128 kilobytes in size and have a width and height of exactly 100px, or a .TGS animation with a thumbnail up to 32 kilobytes in size (see https://core.telegram.org/stickers#animated-sticker-requirements for animated sticker technical requirements), or a WEBM video with the thumbnail up to 32 kilobytes in size; see https://core.telegram.org/stickers#video-sticker-requirements for video sticker technical requirements. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». Animated and video sticker set thumbnails can't be uploaded via HTTP URL. If omitted, then the thumbnail is dropped and the first sticker is used as the thumbnail. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static bool SetStickerSetThumbnail(this BotClient? bot, string name, long userId, InputFile thumbnail) + public static bool SetStickerSetThumbnail(this ITelegramBotClient bot, string name, long userId, InputFile thumbnail) { if (bot == default) { @@ -154,7 +154,7 @@ public static bool SetStickerSetThumbnail(this BotClient? bot, string name, long } var args = new SetStickerSetThumbnailArgs(name, userId) { Thumbnail = thumbnail }; - return bot.RPCF(MethodNames.SetStickerSetThumbnail, args); + return bot.CallMethod(MethodNames.SetStickerSetThumbnail, args); } /// Use this method to set the thumbnail of a sticker set. Animated thumbnails can be set for animated sticker sets only. Returns True on success. /// BotClient @@ -164,7 +164,7 @@ public static bool SetStickerSetThumbnail(this BotClient? bot, string name, long /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static async Task SetStickerSetThumbAsync(this BotClient? bot, string name, long userId, [Optional] CancellationToken cancellationToken) + public static async Task SetStickerSetThumbAsync(this ITelegramBotClient bot, string name, long userId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -189,18 +189,18 @@ public static async Task SetStickerSetThumbAsync(this BotClient? bot, stri json.WriteEndObject(); await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.SetStickerSetThumbnail, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetStickerSetThumbnail, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to set the thumbnail of a sticker set. Animated thumbnails can be set for animated sticker sets only. Returns True on success. /// BotClient /// Sticker set name /// User identifier of the sticker set owner - /// Optional. A .WEBP or .PNG image with the thumbnail, must be up to 128 kilobytes in size and have a width and height of exactly 100px, or a .TGS animation with a thumbnail up to 32 kilobytes in size (see https://core.telegram.org/stickers#animated-sticker-requirements for animated sticker technical requirements), or a WEBM video with the thumbnail up to 32 kilobytes in size; see https://core.telegram.org/stickers#video-sticker-requirements for video sticker technical requirements. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». Animated and video sticker set thumbnails can't be uploaded via HTTP URL. If omitted, then the thumbnail is dropped and the first sticker is used as the thumbnail. + /// Optional. A .WEBP or .PNG image with the thumbnail, must be up to 128 kilobytes in size and have a width and height of exactly 100px, or a .TGS animation with a thumbnail up to 32 kilobytes in size (see https://core.telegram.org/stickers#animated-sticker-requirements for animated sticker technical requirements), or a WEBM video with the thumbnail up to 32 kilobytes in size; see https://core.telegram.org/stickers#video-sticker-requirements for video sticker technical requirements. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». Animated and video sticker set thumbnails can't be uploaded via HTTP URL. If omitted, then the thumbnail is dropped and the first sticker is used as the thumbnail. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static async Task SetStickerSetThumbAsync(this BotClient? bot, string name, long userId, string thumbnail, [Optional] CancellationToken cancellationToken) + public static async Task SetStickerSetThumbAsync(this ITelegramBotClient bot, string name, long userId, string thumbnail, CancellationToken cancellationToken = default) { if (bot == default) { @@ -231,18 +231,18 @@ public static async Task SetStickerSetThumbAsync(this BotClient? bot, stri json.WriteEndObject(); await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.SetStickerSetThumbnail, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetStickerSetThumbnail, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to set the thumbnail of a sticker set. Animated thumbnails can be set for animated sticker sets only. Returns True on success. /// BotClient /// Sticker set name /// User identifier of the sticker set owner - /// Optional. A .WEBP or .PNG image with the thumbnail, must be up to 128 kilobytes in size and have a width and height of exactly 100px, or a .TGS animation with a thumbnail up to 32 kilobytes in size (see https://core.telegram.org/stickers#animated-sticker-requirements for animated sticker technical requirements), or a WEBM video with the thumbnail up to 32 kilobytes in size; see https://core.telegram.org/stickers#video-sticker-requirements for video sticker technical requirements. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». Animated and video sticker set thumbnails can't be uploaded via HTTP URL. If omitted, then the thumbnail is dropped and the first sticker is used as the thumbnail. + /// Optional. A .WEBP or .PNG image with the thumbnail, must be up to 128 kilobytes in size and have a width and height of exactly 100px, or a .TGS animation with a thumbnail up to 32 kilobytes in size (see https://core.telegram.org/stickers#animated-sticker-requirements for animated sticker technical requirements), or a WEBM video with the thumbnail up to 32 kilobytes in size; see https://core.telegram.org/stickers#video-sticker-requirements for video sticker technical requirements. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More information on Sending Files ». Animated and video sticker set thumbnails can't be uploaded via HTTP URL. If omitted, then the thumbnail is dropped and the first sticker is used as the thumbnail. /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static async Task SetStickerSetThumbAsync(this BotClient? bot, string name, long userId, InputFile thumbnail, [Optional] CancellationToken cancellationToken) + public static async Task SetStickerSetThumbAsync(this ITelegramBotClient bot, string name, long userId, InputFile thumbnail, CancellationToken cancellationToken = default) { if (bot == default) { @@ -260,6 +260,6 @@ public static async Task SetStickerSetThumbAsync(this BotClient? bot, stri } var args = new SetStickerSetThumbnailArgs(name, userId) { Thumbnail = thumbnail }; - return await bot.RPCAF(MethodNames.SetStickerSetThumbnail, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetStickerSetThumbnail, args, cancellationToken: cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Stickers/setStickerSetTitle.cs b/src/library/Telegram.BotAPI/Stickers/setStickerSetTitle.cs similarity index 84% rename from src/Telegram.BotAPI/Stickers/setStickerSetTitle.cs rename to src/library/Telegram.BotAPI/Stickers/setStickerSetTitle.cs index 4cc1e984..10bc0c45 100644 --- a/src/Telegram.BotAPI/Stickers/setStickerSetTitle.cs +++ b/src/library/Telegram.BotAPI/Stickers/setStickerSetTitle.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -19,7 +19,7 @@ public static partial class StickersExtensions /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static bool SetStickerSetTitle(this BotClient api, string name, string title) + public static bool SetStickerSetTitle(this ITelegramBotClient api, string name, string title) { if (api == null) { @@ -34,7 +34,7 @@ public static bool SetStickerSetTitle(this BotClient api, string name, string ti json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return api.RPC(MethodNames.SetStickerSetTitle, stream); + return api.CallMethod(MethodNames.SetStickerSetTitle, stream); } /// @@ -47,7 +47,7 @@ public static bool SetStickerSetTitle(this BotClient api, string name, string ti /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. /// True - public static async Task SetStickerSetTitleAsync(this BotClient api, string name, string title, [Optional] CancellationToken cancellationToken) + public static async Task SetStickerSetTitleAsync(this ITelegramBotClient api, string name, string title, CancellationToken cancellationToken = default) { if (api == null) { @@ -61,7 +61,7 @@ public static async Task SetStickerSetTitleAsync(this BotClient api, strin json.WriteEndObject(); await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await api.RPCA(MethodNames.SetStickerSetTitle, stream, cancellationToken) + return await api.CallMethodAsync(MethodNames.SetStickerSetTitle, stream, cancellationToken) .ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Stickers/uploadStickerFile.cs b/src/library/Telegram.BotAPI/Stickers/uploadStickerFile.cs similarity index 72% rename from src/Telegram.BotAPI/Stickers/uploadStickerFile.cs rename to src/library/Telegram.BotAPI/Stickers/uploadStickerFile.cs index a5ed5df9..292c9171 100644 --- a/src/Telegram.BotAPI/Stickers/uploadStickerFile.cs +++ b/src/library/Telegram.BotAPI/Stickers/uploadStickerFile.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -16,7 +16,7 @@ public static partial class StickersExtensions /// Parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static File UploadStickerFile(this BotClient? bot, UploadStickerFileArgs args) + public static File UploadStickerFile(this ITelegramBotClient bot, UploadStickerFileArgs args) { if (bot == default) { @@ -28,7 +28,7 @@ public static File UploadStickerFile(this BotClient? bot, UploadStickerFileArgs throw new ArgumentNullException(nameof(args)); } - return bot.RPCF(MethodNames.UploadStickerFile, args); + return bot.CallMethod(MethodNames.UploadStickerFile, args); } /// @@ -39,7 +39,7 @@ public static File UploadStickerFile(this BotClient? bot, UploadStickerFileArgs /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task UploadStickerFileAsync(this BotClient? bot, UploadStickerFileArgs args, [Optional] CancellationToken cancellationToken) + public static async Task UploadStickerFileAsync(this ITelegramBotClient bot, UploadStickerFileArgs args, CancellationToken cancellationToken = default) { if (bot == default) { @@ -51,7 +51,7 @@ public static async Task UploadStickerFileAsync(this BotClient? bot, Uploa throw new ArgumentNullException(nameof(args)); } - return await bot.RPCAF(MethodNames.UploadStickerFile, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.UploadStickerFile, args, cancellationToken: cancellationToken).ConfigureAwait(false); } /// @@ -59,18 +59,18 @@ public static async Task UploadStickerFileAsync(this BotClient? bot, Uploa /// /// BotClient /// User identifier of sticker file owner. - /// A file with the sticker in .WEBP, .PNG, .TGS, or .WEBM format. See https://core.telegram.org/stickers for technical requirements. More information on Sending Files - /// Format of the sticker, must be one of static, animated, video + /// A file with the sticker in .WEBP, .PNG, .TGS, or .WEBM format. See https://core.telegram.org/stickers for technical requirements. More information on Sending Files � + /// Format of the sticker, must be one of �static�, �animated�, �video� /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static File UploadStickerFile(this BotClient? bot, long userId, InputFile sticker, string stickerFormat) + public static File UploadStickerFile(this ITelegramBotClient bot, long userId, InputFile sticker, string stickerFormat) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } - return bot.RPCF(MethodNames.UploadStickerFile, new UploadStickerFileArgs(userId, sticker, stickerFormat)); + return bot.CallMethod(MethodNames.UploadStickerFile, new UploadStickerFileArgs(userId, sticker, stickerFormat)); } @@ -79,18 +79,18 @@ public static File UploadStickerFile(this BotClient? bot, long userId, InputFile /// /// BotClient /// User identifier of sticker file owner. - /// A file with the sticker in .WEBP, .PNG, .TGS, or .WEBM format. See https://core.telegram.org/stickers for technical requirements. More information on Sending Files - /// Format of the sticker, must be one of static, animated, video + /// A file with the sticker in .WEBP, .PNG, .TGS, or .WEBM format. See https://core.telegram.org/stickers for technical requirements. More information on Sending Files � + /// Format of the sticker, must be one of �static�, �animated�, �video� /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task UploadStickerFileAsync(this BotClient? bot, long userId, InputFile sticker, string stickerFormat, [Optional] CancellationToken cancellationToken) + public static async Task UploadStickerFileAsync(this ITelegramBotClient bot, long userId, InputFile sticker, string stickerFormat, CancellationToken cancellationToken = default) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } - return await bot.RPCAF(MethodNames.UploadStickerFile, new UploadStickerFileArgs(userId, sticker, stickerFormat), cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.UploadStickerFile, new UploadStickerFileArgs(userId, sticker, stickerFormat), cancellationToken: cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Sugar Library/AsyncTelegramBotBase.cs b/src/library/Telegram.BotAPI/Sugar Library/AsyncTelegramBotBase.cs similarity index 67% rename from src/Telegram.BotAPI/Sugar Library/AsyncTelegramBotBase.cs rename to src/library/Telegram.BotAPI/Sugar Library/AsyncTelegramBotBase.cs index ca7b53d0..730ce109 100644 --- a/src/Telegram.BotAPI/Sugar Library/AsyncTelegramBotBase.cs +++ b/src/library/Telegram.BotAPI/Sugar Library/AsyncTelegramBotBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -11,6 +11,7 @@ namespace Telegram.BotAPI; /// Base class for Telegram Bots. +[Obsolete("Use Telegram.BotAPI.Extensions.SimpleTelegramBotBase instead.")] public abstract class AsyncTelegramBotBase : AsyncTelegramBotBase where TBotProperties : IBotProperties { @@ -19,7 +20,7 @@ public abstract class AsyncTelegramBotBase : AsyncTelegramBotBas private readonly TBotProperties _properties; /// Bot client instance to interact with the Telegram Bot API. - protected BotClient Api => this._properties.Api; + protected ITelegramBotClient Api => this._properties.Api; /// The basic information about the bot. protected User Me => this._properties.User; @@ -35,7 +36,7 @@ public AsyncTelegramBotBase(TBotProperties botProperties) this._properties = botProperties; } /// - public override async Task OnUpdateAsync(Update update, [Optional] CancellationToken cancellationToken) + public override async Task OnUpdateAsync(Update update, CancellationToken cancellationToken = default) { this.Update = update; @@ -49,7 +50,7 @@ public override async Task OnUpdateAsync(Update update, [Optional] CancellationT /// Optional. The cancelation token. /// /// - protected override async Task OnMessageAsync(Message message, [Optional] CancellationToken cancellationToken) + protected override async Task OnMessageAsync(Message message, CancellationToken cancellationToken = default) { if (!string.IsNullOrEmpty(message.Text)) { @@ -69,17 +70,23 @@ protected override async Task OnMessageAsync(Message message, [Optional] Cancell /// Command parameters.
Example: /<command name> <command parameters> /// Optional. The cancelation token. /// - protected abstract Task OnCommandAsync(Message message, string commandName, string commandParameters, [Optional] CancellationToken cancellationToken); + protected abstract Task OnCommandAsync(Message message, string commandName, string commandParameters, CancellationToken cancellationToken = default); } /// Base class for Telegram Bots. +[Obsolete("Use Telegram.BotAPI.Extensions.SimpleTelegramBotBase instead.")] public abstract class AsyncTelegramBotBase : ITelegramBot { + void ITelegramBot.OnUpdate(Update update) + { + this.OnUpdateAsync(update).Wait(); + } + /// Call the corresponding method according to the type of update provided. /// Update /// Optional. The cancelation token. /// - public virtual async Task OnUpdateAsync(Update update, [Optional] CancellationToken cancellationToken) + public virtual async Task OnUpdateAsync(Update update, CancellationToken cancellationToken = default) { if (update == default) { @@ -87,53 +94,61 @@ public virtual async Task OnUpdateAsync(Update update, [Optional] CancellationTo } try { - switch (update.Type) + if (update.Message is not null) + { + await this.OnMessageAsync(update.Message, cancellationToken).ConfigureAwait(false); + } + else if (update.EditedMessage is not null) + { + await this.OnEditedMessageAsync(update.EditedMessage, cancellationToken).ConfigureAwait(false); + } + else if (update.ChannelPost is not null) + { + await this.OnChannelPostAsync(update.ChannelPost, cancellationToken).ConfigureAwait(false); + } + else if (update.EditedChannelPost is not null) + { + await this.OnEditedChannelPostAsync(update.EditedChannelPost, cancellationToken).ConfigureAwait(false); + } + else if (update.InlineQuery is not null) + { + await this.OnInlineQueryAsync(update.InlineQuery, cancellationToken).ConfigureAwait(false); + } + else if (update.ChosenInlineResult is not null) + { + await this.OnChosenInlineResultAsync(update.ChosenInlineResult, cancellationToken).ConfigureAwait(false); + } + else if (update.CallbackQuery is not null) + { + await this.OnCallbackQueryAsync(update.CallbackQuery, cancellationToken).ConfigureAwait(false); + } + else if (update.ShippingQuery is not null) + { + await this.OnShippingQueryAsync(update.ShippingQuery, cancellationToken).ConfigureAwait(false); + } + else if (update.PreCheckoutQuery is not null) + { + await this.OnPreCheckoutQueryAsync(update.PreCheckoutQuery, cancellationToken).ConfigureAwait(false); + } + else if (update.Poll is not null) + { + await this.OnPollAsync(update.Poll, cancellationToken).ConfigureAwait(false); + } + else if (update.PollAnswer is not null) + { + await this.OnPollAnswerAsync(update.PollAnswer, cancellationToken).ConfigureAwait(false); + } + else if (update.MyChatMember is not null) { - case UpdateType.Message: - await this.OnMessageAsync(update.Message!, cancellationToken).ConfigureAwait(false); - break; - case UpdateType.EditedMessage: - await this.OnEditedMessageAsync(update.EditedMessage!, cancellationToken).ConfigureAwait(false); - break; - case UpdateType.ChannelPost: - await this.OnChannelPostAsync(update.ChannelPost!, cancellationToken).ConfigureAwait(false); - break; - case UpdateType.EditedChannelPost: - await this.OnEditedChannelPostAsync(update.EditedChannelPost!, cancellationToken).ConfigureAwait(false); - break; - case UpdateType.InlineQuery: - await this.OnInlineQueryAsync(update.InlineQuery!, cancellationToken).ConfigureAwait(false); - break; - case UpdateType.ChosenInlineResult: - await this.OnChosenInlineResultAsync(update.ChosenInlineResult!, cancellationToken).ConfigureAwait(false); - break; - case UpdateType.CallbackQuery: - await this.OnCallbackQueryAsync(update.CallbackQuery!, cancellationToken).ConfigureAwait(false); - break; - case UpdateType.ShippingQuery: - await this.OnShippingQueryAsync(update.ShippingQuery!, cancellationToken).ConfigureAwait(false); - break; - case UpdateType.PreCheckoutQuery: - await this.OnPreCheckoutQueryAsync(update.PreCheckoutQuery!, cancellationToken).ConfigureAwait(false); - break; - case UpdateType.Poll: - await this.OnPollAsync(update.Poll!, cancellationToken).ConfigureAwait(false); - break; - case UpdateType.PollAnswer: - await this.OnPollAnswerAsync(update.PollAnswer!, cancellationToken).ConfigureAwait(false); - break; - case UpdateType.MyChatMember: - await this.OnMyChatMemberAsync(update.MyChatMember!, cancellationToken).ConfigureAwait(false); - break; - case UpdateType.ChatMember: - await this.OnChatMemberAsync(update.ChatMember!, cancellationToken).ConfigureAwait(false); - break; - case UpdateType.ChatJoinRequest: - await this.OnChatJoinRequestAsync(update.ChatJoinRequest!, cancellationToken).ConfigureAwait(false); - break; - case UpdateType.Unknown: - default: - throw new ArgumentException("The update parameter does not correspond to a valid update.", nameof(update)); + await this.OnMyChatMemberAsync(update.MyChatMember, cancellationToken).ConfigureAwait(false); + } + else if (update.ChatMember is not null) + { + await this.OnChatMemberAsync(update.ChatMember, cancellationToken).ConfigureAwait(false); + } + else if (update.ChatJoinRequest is not null) + { + await this.OnChatJoinRequestAsync(update.ChatJoinRequest, cancellationToken).ConfigureAwait(false); } } catch (BotRequestException exp) @@ -150,86 +165,81 @@ public virtual async Task OnUpdateAsync(Update update, [Optional] CancellationTo /// Message. /// Optional. The cancelation token. /// - protected abstract Task OnMessageAsync(Message message, [Optional] CancellationToken cancellationToken); + protected abstract Task OnMessageAsync(Message message, CancellationToken cancellationToken = default); /// Instructions for an edited message. /// Message /// Optional. The cancelation token. /// - protected virtual Task OnEditedMessageAsync(Message message, [Optional] CancellationToken cancellationToken) => Task.CompletedTask; + protected virtual Task OnEditedMessageAsync(Message message, CancellationToken cancellationToken = default) => Task.CompletedTask; /// Instructions for a channel post. /// Message /// Optional. The cancelation token. /// - protected virtual Task OnChannelPostAsync(Message message, [Optional] CancellationToken cancellationToken) => Task.CompletedTask; + protected virtual Task OnChannelPostAsync(Message message, CancellationToken cancellationToken = default) => Task.CompletedTask; /// Instructions for an edited channel post update. /// Message /// Optional. The cancelation token. /// - protected virtual Task OnEditedChannelPostAsync(Message message, [Optional] CancellationToken cancellationToken) => Task.CompletedTask; + protected virtual Task OnEditedChannelPostAsync(Message message, CancellationToken cancellationToken = default) => Task.CompletedTask; /// Instructions for an inline query update. /// Inline query. /// Optional. The cancelation token. /// - protected virtual Task OnInlineQueryAsync(InlineQuery inlineQuery, [Optional] CancellationToken cancellationToken) => Task.CompletedTask; + protected virtual Task OnInlineQueryAsync(InlineQuery inlineQuery, CancellationToken cancellationToken = default) => Task.CompletedTask; /// Instructions for a chosen inline result update. /// Chosen Inline Result. /// Optional. The cancelation token. /// - protected virtual Task OnChosenInlineResultAsync(ChosenInlineResult chosenInlineResult, [Optional] CancellationToken cancellationToken) => Task.CompletedTask; + protected virtual Task OnChosenInlineResultAsync(ChosenInlineResult chosenInlineResult, CancellationToken cancellationToken = default) => Task.CompletedTask; /// Instructions for a callback query update. /// Callback query /// Optional. The cancelation token. /// - protected virtual Task OnCallbackQueryAsync(CallbackQuery callbackQuery, [Optional] CancellationToken cancellationToken) => Task.CompletedTask; + protected virtual Task OnCallbackQueryAsync(CallbackQuery callbackQuery, CancellationToken cancellationToken = default) => Task.CompletedTask; /// Instructions for a shipping query update. /// Shipping query /// Optional. The cancelation token. /// - protected virtual Task OnShippingQueryAsync(ShippingQuery shippingQuery, [Optional] CancellationToken cancellationToken) => Task.CompletedTask; + protected virtual Task OnShippingQueryAsync(ShippingQuery shippingQuery, CancellationToken cancellationToken = default) => Task.CompletedTask; /// Instructions for a pre-checkout query update. /// Pre-checkout query. /// Optional. The cancelation token. /// - protected virtual Task OnPreCheckoutQueryAsync(PreCheckoutQuery preCheckoutQuery, [Optional] CancellationToken cancellationToken) => Task.CompletedTask; + protected virtual Task OnPreCheckoutQueryAsync(PreCheckoutQuery preCheckoutQuery, CancellationToken cancellationToken = default) => Task.CompletedTask; /// Instructions for a poll update. /// Poll. /// Optional. The cancelation token. /// - protected virtual Task OnPollAsync(Poll poll, [Optional] CancellationToken cancellationToken) => Task.CompletedTask; + protected virtual Task OnPollAsync(Poll poll, CancellationToken cancellationToken = default) => Task.CompletedTask; /// Instructions for a poll answer update. /// Poll answer. /// Optional. The cancelation token. /// - protected virtual Task OnPollAnswerAsync(PollAnswer pollAnswer, [Optional] CancellationToken cancellationToken) => Task.CompletedTask; + protected virtual Task OnPollAnswerAsync(PollAnswer pollAnswer, CancellationToken cancellationToken = default) => Task.CompletedTask; /// Instructions for my chat member update. /// My chat member updated. /// Optional. The cancelation token. /// - protected virtual Task OnMyChatMemberAsync(ChatMemberUpdated myChatMemberUpdated, [Optional] CancellationToken cancellationToken) => Task.CompletedTask; + protected virtual Task OnMyChatMemberAsync(ChatMemberUpdated myChatMemberUpdated, CancellationToken cancellationToken = default) => Task.CompletedTask; /// Instructions for chat member update. /// Chat member updated. /// Optional. The cancelation token. /// - protected virtual Task OnChatMemberAsync(ChatMemberUpdated chatMemberUpdated, [Optional] CancellationToken cancellationToken) => Task.CompletedTask; + protected virtual Task OnChatMemberAsync(ChatMemberUpdated chatMemberUpdated, CancellationToken cancellationToken = default) => Task.CompletedTask; /// Instructions for chat join request update. /// Chat join request. /// Optional. The cancelation token. /// - protected virtual Task OnChatJoinRequestAsync(ChatJoinRequest chatJoinRequest, [Optional] CancellationToken cancellationToken) => Task.CompletedTask; + protected virtual Task OnChatJoinRequestAsync(ChatJoinRequest chatJoinRequest, CancellationToken cancellationToken = default) => Task.CompletedTask; /// Instructions for a bot exception. /// Bot exception /// Optional. The cancelation token. /// - protected abstract Task OnBotExceptionAsync(BotRequestException exp, [Optional] CancellationToken cancellationToken); + protected abstract Task OnBotExceptionAsync(BotRequestException exp, CancellationToken cancellationToken = default); /// Instructions for a general exception. /// Exception /// Optional. The cancelation token. /// - protected abstract Task OnExceptionAsync(Exception exp, [Optional] CancellationToken cancellationToken); - - void ITelegramBot.OnUpdate(Update update) - { - this.OnUpdateAsync(update).Wait(); - } + protected abstract Task OnExceptionAsync(Exception exp, CancellationToken cancellationToken = default); } diff --git a/src/Telegram.BotAPI/Sugar Library/BotProperties.cs b/src/library/Telegram.BotAPI/Sugar Library/BotProperties.cs similarity index 84% rename from src/Telegram.BotAPI/Sugar Library/BotProperties.cs rename to src/library/Telegram.BotAPI/Sugar Library/BotProperties.cs index 72f88770..f0578080 100644 --- a/src/Telegram.BotAPI/Sugar Library/BotProperties.cs +++ b/src/library/Telegram.BotAPI/Sugar Library/BotProperties.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Net.Http; @@ -8,6 +8,7 @@ namespace Telegram.BotAPI; /// Represents a set of basic bot configuration properties. +[Obsolete("Use Telegram.BotAPI.Extensions.TelegramBot context instead.")] public class BotProperties : IBotProperties { /// Initialize a new instance of . @@ -21,7 +22,7 @@ public BotProperties(BotClient bot) /// Initialize a new instance of . /// Token granted by BotFather. Required to access the Telegram bot API. /// Provide a specific HttpClient for this instance of BotClient. - public BotProperties(string botToken, [Optional] HttpClient httpClient) : this(new BotClient(botToken, httpClient)) + public BotProperties(string botToken, HttpClient httpClient = null) : this(new BotClient(botToken, httpClient)) { } /// @@ -30,10 +31,8 @@ public BotProperties(string botToken, [Optional] HttpClient httpClient) : this(n public User User { get; } IBotCommandHelper IBotProperties.CommandHelper => this.CommandHelper; - - /// /// The bot command helper. /// public BotCommandHelper CommandHelper { get; } -} +} \ No newline at end of file diff --git a/src/Telegram.BotAPI/Sugar Library/ChatType.cs b/src/library/Telegram.BotAPI/Sugar Library/ChatType.cs similarity index 64% rename from src/Telegram.BotAPI/Sugar Library/ChatType.cs rename to src/library/Telegram.BotAPI/Sugar Library/ChatType.cs index c46c75b7..b6fc71d0 100644 --- a/src/Telegram.BotAPI/Sugar Library/ChatType.cs +++ b/src/library/Telegram.BotAPI/Sugar Library/ChatType.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI.AvailableTypes; @@ -8,14 +8,24 @@ namespace Telegram.BotAPI.AvailableTypes; ///
public static class ChatType { - /// Private chat with the inline query sender + /// + /// Private chat with the inline query sender + /// public const string Sender = "sender"; - /// Private chat + /// + /// Private chat + /// public const string Private = "private"; - /// Group chat + /// + /// Group chat + /// public const string Group = "group"; - /// Supergroup chat + /// + /// Supergroup chat + /// public const string Supergroup = "supergroup"; - /// Channel chat + /// + /// Channel chat + /// public const string Channel = "channel"; } diff --git a/src/Telegram.BotAPI/Sugar Library/Enums/InlineKeyboardButtonType.cs b/src/library/Telegram.BotAPI/Sugar Library/Enums/InlineKeyboardButtonType.cs similarity index 87% rename from src/Telegram.BotAPI/Sugar Library/Enums/InlineKeyboardButtonType.cs rename to src/library/Telegram.BotAPI/Sugar Library/Enums/InlineKeyboardButtonType.cs index e596066e..74ebb5ae 100644 --- a/src/Telegram.BotAPI/Sugar Library/Enums/InlineKeyboardButtonType.cs +++ b/src/library/Telegram.BotAPI/Sugar Library/Enums/InlineKeyboardButtonType.cs @@ -1,9 +1,12 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI; -/// inlinekeyboardbutton Type +/// +/// Inlinekeyboardbutton Type +/// +[Obsolete] public enum InlineKeyboardButtonType { /// Unknown button. diff --git a/src/Telegram.BotAPI/Sugar Library/Enums/MessageEntityType.cs b/src/library/Telegram.BotAPI/Sugar Library/Enums/MessageEntityType.cs similarity index 93% rename from src/Telegram.BotAPI/Sugar Library/Enums/MessageEntityType.cs rename to src/library/Telegram.BotAPI/Sugar Library/Enums/MessageEntityType.cs index 4cf4e224..1ea44cea 100644 --- a/src/Telegram.BotAPI/Sugar Library/Enums/MessageEntityType.cs +++ b/src/library/Telegram.BotAPI/Sugar Library/Enums/MessageEntityType.cs @@ -1,9 +1,12 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI; -/// Entity types. +/// +/// Entity types. +/// +[Obsolete] public enum MessageEntityType { /// diff --git a/src/Telegram.BotAPI/Sugar Library/Enums/UpdateType.cs b/src/library/Telegram.BotAPI/Sugar Library/Enums/UpdateType.cs similarity index 90% rename from src/Telegram.BotAPI/Sugar Library/Enums/UpdateType.cs rename to src/library/Telegram.BotAPI/Sugar Library/Enums/UpdateType.cs index bca1068c..4cc813ff 100644 --- a/src/Telegram.BotAPI/Sugar Library/Enums/UpdateType.cs +++ b/src/library/Telegram.BotAPI/Sugar Library/Enums/UpdateType.cs @@ -1,9 +1,12 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI; -/// Available update types. +/// +/// Available update types. +/// +[Obsolete] public enum UpdateType { /// Unknown update diff --git a/src/Telegram.BotAPI/Sugar Library/Extensions/InlineKeyboardButtonExtensions.cs b/src/library/Telegram.BotAPI/Sugar Library/Extensions/InlineKeyboardButtonExtensions.cs similarity index 96% rename from src/Telegram.BotAPI/Sugar Library/Extensions/InlineKeyboardButtonExtensions.cs rename to src/library/Telegram.BotAPI/Sugar Library/Extensions/InlineKeyboardButtonExtensions.cs index 4b865213..c65486f6 100644 --- a/src/Telegram.BotAPI/Sugar Library/Extensions/InlineKeyboardButtonExtensions.cs +++ b/src/library/Telegram.BotAPI/Sugar Library/Extensions/InlineKeyboardButtonExtensions.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Telegram.BotAPI.AvailableTypes; @@ -14,13 +14,14 @@ public static partial class InlineKeyboardButtonExtensions /// Get the button type. /// /// + [Obsolete] public static InlineKeyboardButtonType GetButtonType(this InlineKeyboardButton button) { if (button.Url != default) { return InlineKeyboardButtonType.Url; } - + if (button.CallbackData != default) { return InlineKeyboardButtonType.CallbackData; diff --git a/src/Telegram.BotAPI/Sugar Library/Extensions/MessageEntityExtensions.cs b/src/library/Telegram.BotAPI/Sugar Library/Extensions/MessageEntityExtensions.cs similarity index 82% rename from src/Telegram.BotAPI/Sugar Library/Extensions/MessageEntityExtensions.cs rename to src/library/Telegram.BotAPI/Sugar Library/Extensions/MessageEntityExtensions.cs index 56e805eb..31e76b5f 100644 --- a/src/Telegram.BotAPI/Sugar Library/Extensions/MessageEntityExtensions.cs +++ b/src/library/Telegram.BotAPI/Sugar Library/Extensions/MessageEntityExtensions.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Telegram.BotAPI.AvailableTypes; @@ -10,8 +10,11 @@ namespace Telegram.BotAPI; ///
public static partial class MessageEntityExtensions { - /// Get the entity type as enum. + /// + /// Get the entity type as enum. + /// /// + [Obsolete] public static MessageEntityType GetEntityType(this MessageEntity messageEntity) { string type = messageEntity.Type.Replace("_", string.Empty); diff --git a/src/Telegram.BotAPI/Sugar Library/Helpers/BotCommandHelper.cs b/src/library/Telegram.BotAPI/Sugar Library/Helpers/BotCommandHelper.cs similarity index 91% rename from src/Telegram.BotAPI/Sugar Library/Helpers/BotCommandHelper.cs rename to src/library/Telegram.BotAPI/Sugar Library/Helpers/BotCommandHelper.cs index be235bcc..ee1660bd 100644 --- a/src/Telegram.BotAPI/Sugar Library/Helpers/BotCommandHelper.cs +++ b/src/library/Telegram.BotAPI/Sugar Library/Helpers/BotCommandHelper.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Globalization; @@ -6,7 +6,10 @@ namespace Telegram.BotAPI; -/// Helper class for command detection. +/// +/// Helper class for command detection. +/// +[Obsolete] public sealed class BotCommandHelper : IBotCommandHelper { private const string COMMAND = "command"; @@ -20,7 +23,7 @@ public sealed class BotCommandHelper : IBotCommandHelper /// Initialize a new instance of . /// The bot username. - /// Set true, if tyou want to use regex compiled option. + /// Set true, if you want to use regex compiled option. /// public BotCommandHelper(IBotProperties configuration, [Optional] bool useRegexCompiled) { diff --git a/src/Telegram.BotAPI/Sugar Library/Helpers/BotCommandMatch.cs b/src/library/Telegram.BotAPI/Sugar Library/Helpers/BotCommandMatch.cs similarity index 95% rename from src/Telegram.BotAPI/Sugar Library/Helpers/BotCommandMatch.cs rename to src/library/Telegram.BotAPI/Sugar Library/Helpers/BotCommandMatch.cs index 627dbc77..f25b0544 100644 --- a/src/Telegram.BotAPI/Sugar Library/Helpers/BotCommandMatch.cs +++ b/src/library/Telegram.BotAPI/Sugar Library/Helpers/BotCommandMatch.cs @@ -1,9 +1,10 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI; /// This object represents the result of a bot command match. +[Obsolete] public class BotCommandMatch { /// Initialize a new instance of . diff --git a/src/Telegram.BotAPI/Sugar Library/Helpers/FormattingHelper.cs b/src/library/Telegram.BotAPI/Sugar Library/Helpers/FormattingHelper.cs similarity index 99% rename from src/Telegram.BotAPI/Sugar Library/Helpers/FormattingHelper.cs rename to src/library/Telegram.BotAPI/Sugar Library/Helpers/FormattingHelper.cs index b0a75347..b911390a 100644 --- a/src/Telegram.BotAPI/Sugar Library/Helpers/FormattingHelper.cs +++ b/src/library/Telegram.BotAPI/Sugar Library/Helpers/FormattingHelper.cs @@ -1,14 +1,14 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Linq; using System.Text; using Telegram.BotAPI.AvailableTypes; -using static System.Net.Mime.MediaTypeNames; namespace Telegram.BotAPI.AvailableMethods.FormattingOptions; /// This class contains a set of useful methods for formatting the text of messages. +[Obsolete] public class FormattingHelper : FormattingHelper { /// Initialize a new instance of StyleParser. @@ -19,6 +19,7 @@ public FormattingHelper([Optional] StyleParser styleParser) : base(styleParser ? } /// This class contains a set of useful methods for formatting the text of messages. +[Obsolete] public class FormattingHelper where TStyleParser : IStyleParser { diff --git a/src/Telegram.BotAPI/Sugar Library/Helpers/IBotCommandHelper.cs b/src/library/Telegram.BotAPI/Sugar Library/Helpers/IBotCommandHelper.cs similarity index 64% rename from src/Telegram.BotAPI/Sugar Library/Helpers/IBotCommandHelper.cs rename to src/library/Telegram.BotAPI/Sugar Library/Helpers/IBotCommandHelper.cs index f4b582a8..2992376a 100644 --- a/src/Telegram.BotAPI/Sugar Library/Helpers/IBotCommandHelper.cs +++ b/src/library/Telegram.BotAPI/Sugar Library/Helpers/IBotCommandHelper.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI; @@ -6,9 +6,12 @@ namespace Telegram.BotAPI; /// /// Defines a method to match the bot command of a text. /// +[Obsolete] public interface IBotCommandHelper { - /// Extracts the command name and parameters from the specified input string using the following format:
/commandName[@BotUsername] [Params].
+ /// + /// Extracts the command name and parameters from the specified input string using the following format:
/commandName[@BotUsername] [Params]. + ///
/// Input string. The message text. /// A object with the result information. BotCommandMatch Match(string text); diff --git a/src/Telegram.BotAPI/Sugar Library/Helpers/IStyleParser.cs b/src/library/Telegram.BotAPI/Sugar Library/Helpers/IStyleParser.cs similarity index 96% rename from src/Telegram.BotAPI/Sugar Library/Helpers/IStyleParser.cs rename to src/library/Telegram.BotAPI/Sugar Library/Helpers/IStyleParser.cs index 48dfbfaf..7d1afd83 100644 --- a/src/Telegram.BotAPI/Sugar Library/Helpers/IStyleParser.cs +++ b/src/library/Telegram.BotAPI/Sugar Library/Helpers/IStyleParser.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI.AvailableMethods.FormattingOptions; @@ -6,6 +6,7 @@ namespace Telegram.BotAPI.AvailableMethods.FormattingOptions; /// /// Define a set of useful methods for parsing text to be used with styles. /// +[Obsolete] public interface IStyleParser { /// Parse specified text with wrong style tags. diff --git a/src/Telegram.BotAPI/Sugar Library/Helpers/InlineButtonBuilder.cs b/src/library/Telegram.BotAPI/Sugar Library/Helpers/InlineButtonBuilder.cs similarity index 97% rename from src/Telegram.BotAPI/Sugar Library/Helpers/InlineButtonBuilder.cs rename to src/library/Telegram.BotAPI/Sugar Library/Helpers/InlineButtonBuilder.cs index 92c6d27b..206a3ae5 100644 --- a/src/Telegram.BotAPI/Sugar Library/Helpers/InlineButtonBuilder.cs +++ b/src/library/Telegram.BotAPI/Sugar Library/Helpers/InlineButtonBuilder.cs @@ -1,9 +1,6 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. -using System; -using System.Collections.Generic; -using System.Text; using Telegram.BotAPI.AvailableTypes; using Telegram.BotAPI.Games; @@ -12,6 +9,7 @@ namespace Telegram.BotAPI; /// /// This class define methods to build objects. /// +[Obsolete] public static class InlineButtonBuilder { /// diff --git a/src/Telegram.BotAPI/Sugar Library/IBotProperties.cs b/src/library/Telegram.BotAPI/Sugar Library/IBotProperties.cs similarity index 84% rename from src/Telegram.BotAPI/Sugar Library/IBotProperties.cs rename to src/library/Telegram.BotAPI/Sugar Library/IBotProperties.cs index ca1f640f..348e8500 100644 --- a/src/Telegram.BotAPI/Sugar Library/IBotProperties.cs +++ b/src/library/Telegram.BotAPI/Sugar Library/IBotProperties.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Telegram.BotAPI.AvailableTypes; @@ -8,6 +8,7 @@ namespace Telegram.BotAPI; /// /// Defines the properties used in the basic configuration of a Telegram bot. /// +[Obsolete("Use Telegram.BotAPI.Extensions.TelegramBot context instead.")] public interface IBotProperties { /// @@ -22,4 +23,4 @@ public interface IBotProperties /// The bot command helper. /// IBotCommandHelper CommandHelper { get; } -} +} \ No newline at end of file diff --git a/src/library/Telegram.BotAPI/Sugar Library/ITelegramBot.cs b/src/library/Telegram.BotAPI/Sugar Library/ITelegramBot.cs new file mode 100644 index 00000000..3bee84e4 --- /dev/null +++ b/src/library/Telegram.BotAPI/Sugar Library/ITelegramBot.cs @@ -0,0 +1,30 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System.Threading; +using System.Threading.Tasks; +using Telegram.BotAPI.GettingUpdates; + +namespace Telegram.BotAPI; + +/// +/// Represents a Telegram Bot. +/// Defines methods for receiving and processing incoming updates. +/// +public interface ITelegramBot +{ + /// + /// Receives and processes an incoming update. + /// + /// The incoming update. + void OnUpdate(Update update); + + /// + /// Receives and processes an incoming update. + /// + /// The incoming update. + /// A cancellation token. + /// A task that represents the asynchronous operation. + /// + Task OnUpdateAsync(Update update, CancellationToken cancellationToken = default); +} diff --git a/src/library/Telegram.BotAPI/Sugar Library/PollType.cs b/src/library/Telegram.BotAPI/Sugar Library/PollType.cs new file mode 100644 index 00000000..8a03568f --- /dev/null +++ b/src/library/Telegram.BotAPI/Sugar Library/PollType.cs @@ -0,0 +1,14 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +namespace Telegram.BotAPI.AvailableMethods; + +/// Poll type, “quiz” or “regular”, defaults to “regular” +[Obsolete] +public static class PollType +{ + /// Quiz poll + public const string Quiz = "quiz"; + /// Regular poll + public const string Regular = "regular"; +} \ No newline at end of file diff --git a/src/Telegram.BotAPI/Sugar Library/Stickers/StickerFormats.cs b/src/library/Telegram.BotAPI/Sugar Library/Stickers/StickerFormats.cs similarity index 92% rename from src/Telegram.BotAPI/Sugar Library/Stickers/StickerFormats.cs rename to src/library/Telegram.BotAPI/Sugar Library/Stickers/StickerFormats.cs index b18be2ff..fc1a4863 100644 --- a/src/Telegram.BotAPI/Sugar Library/Stickers/StickerFormats.cs +++ b/src/library/Telegram.BotAPI/Sugar Library/Stickers/StickerFormats.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI; diff --git a/src/Telegram.BotAPI/Sugar Library/Stickers/StickerTypes.cs b/src/library/Telegram.BotAPI/Sugar Library/Stickers/StickerTypes.cs similarity index 92% rename from src/Telegram.BotAPI/Sugar Library/Stickers/StickerTypes.cs rename to src/library/Telegram.BotAPI/Sugar Library/Stickers/StickerTypes.cs index 6236a480..c8837d51 100644 --- a/src/Telegram.BotAPI/Sugar Library/Stickers/StickerTypes.cs +++ b/src/library/Telegram.BotAPI/Sugar Library/Stickers/StickerTypes.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI; diff --git a/src/Telegram.BotAPI/Sugar Library/TelegramBotBase.cs b/src/library/Telegram.BotAPI/Sugar Library/TelegramBotBase.cs similarity index 75% rename from src/Telegram.BotAPI/Sugar Library/TelegramBotBase.cs rename to src/library/Telegram.BotAPI/Sugar Library/TelegramBotBase.cs index 667ca4dd..399c7767 100644 --- a/src/Telegram.BotAPI/Sugar Library/TelegramBotBase.cs +++ b/src/library/Telegram.BotAPI/Sugar Library/TelegramBotBase.cs @@ -1,6 +1,8 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. +using System.Threading; +using System.Threading.Tasks; using Telegram.BotAPI.AvailableTypes; using Telegram.BotAPI.GettingUpdates; using Telegram.BotAPI.InlineMode; @@ -8,7 +10,10 @@ namespace Telegram.BotAPI; -/// Base class for Telegram Bots. +/// +/// Base class for Telegram Bots. +/// +[Obsolete("Use Telegram.BotAPI.Extensions.SimpleTelegramBotBase instead.")] public abstract class TelegramBotBase : TelegramBotBase where TBotProperties : IBotProperties { @@ -64,6 +69,7 @@ protected override void OnMessage(Message message) } /// Base class for Telegram Bots. +[Obsolete("Use Telegram.BotAPI.Extensions.SimpleTelegramBotBase instead.")] public abstract class TelegramBotBase : ITelegramBot { /// Call the corresponding method according to the type of update provided. @@ -76,53 +82,61 @@ public virtual void OnUpdate(Update update) } try { - switch (update.Type) + if (update.Message is not null) + { + this.OnMessage(update.Message); + } + else if (update.EditedMessage is not null) + { + this.OnEditedMessage(update.EditedMessage); + } + else if (update.ChannelPost is not null) + { + this.OnChannelPost(update.ChannelPost); + } + else if (update.EditedChannelPost is not null) + { + this.OnEditedChannelPost(update.EditedChannelPost); + } + else if (update.InlineQuery is not null) + { + this.OnInlineQuery(update.InlineQuery); + } + else if (update.ChosenInlineResult is not null) + { + this.OnChosenInlineResult(update.ChosenInlineResult); + } + else if (update.CallbackQuery is not null) + { + this.OnCallbackQuery(update.CallbackQuery); + } + else if (update.ShippingQuery is not null) { - case UpdateType.Message: - this.OnMessage(update.Message!); - break; - case UpdateType.EditedMessage: - this.OnEditedMessage(update.EditedMessage!); - break; - case UpdateType.ChannelPost: - this.OnChannelPost(update.ChannelPost!); - break; - case UpdateType.EditedChannelPost: - this.OnEditedChannelPost(update.EditedChannelPost!); - break; - case UpdateType.InlineQuery: - this.OnInlineQuery(update.InlineQuery!); - break; - case UpdateType.ChosenInlineResult: - this.OnChosenInlineResult(update.ChosenInlineResult!); - break; - case UpdateType.CallbackQuery: - this.OnCallbackQuery(update.CallbackQuery!); - break; - case UpdateType.ShippingQuery: - this.OnShippingQuery(update.ShippingQuery!); - break; - case UpdateType.PreCheckoutQuery: - this.OnPreCheckoutQuery(update.PreCheckoutQuery!); - break; - case UpdateType.Poll: - this.OnPoll(update.Poll!); - break; - case UpdateType.PollAnswer: - this.OnPollAnswer(update.PollAnswer!); - break; - case UpdateType.MyChatMember: - this.OnMyChatMember(update.MyChatMember!); - break; - case UpdateType.ChatMember: - this.OnChatMember(update.ChatMember!); - break; - case UpdateType.ChatJoinRequest: - this.OnChatJoinRequest(update.ChatJoinRequest!); - break; - case UpdateType.Unknown: - default: - throw new ArgumentException("The update parameter does not correspond to a valid update.", nameof(update)); + this.OnShippingQuery(update.ShippingQuery); + } + else if (update.PreCheckoutQuery is not null) + { + this.OnPreCheckoutQuery(update.PreCheckoutQuery); + } + else if (update.Poll is not null) + { + this.OnPoll(update.Poll); + } + else if (update.PollAnswer is not null) + { + this.OnPollAnswer(update.PollAnswer); + } + else if (update.MyChatMember is not null) + { + this.OnMyChatMember(update.MyChatMember); + } + else if (update.ChatMember is not null) + { + this.OnChatMember(update.ChatMember); + } + else if (update.ChatJoinRequest is not null) + { + this.OnChatJoinRequest(update.ChatJoinRequest); } } catch (BotRequestException exp) @@ -135,6 +149,13 @@ public virtual void OnUpdate(Update update) } } + /// + Task ITelegramBot.OnUpdateAsync(Update update, CancellationToken cancellationToken) + { + this.OnUpdate(update); + return Task.CompletedTask; + } + /// Instructions for a message update. /// Message. protected abstract void OnMessage(Message message); @@ -183,4 +204,4 @@ protected virtual void OnChatJoinRequest(ChatJoinRequest chatJoinRequest) { } /// Instructions for a general exception. /// Exception protected abstract void OnException(Exception exp); -} +} \ No newline at end of file diff --git a/src/Telegram.BotAPI/Telegram Passport/Args/SetPassportDataErrorsArgs.cs b/src/library/Telegram.BotAPI/Telegram Passport/Args/SetPassportDataErrorsArgs.cs similarity index 97% rename from src/Telegram.BotAPI/Telegram Passport/Args/SetPassportDataErrorsArgs.cs rename to src/library/Telegram.BotAPI/Telegram Passport/Args/SetPassportDataErrorsArgs.cs index 589820e5..0b0132ed 100644 --- a/src/Telegram.BotAPI/Telegram Passport/Args/SetPassportDataErrorsArgs.cs +++ b/src/library/Telegram.BotAPI/Telegram Passport/Args/SetPassportDataErrorsArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Telegram Passport/EncryptedCredentials.cs b/src/library/Telegram.BotAPI/Telegram Passport/EncryptedCredentials.cs similarity index 98% rename from src/Telegram.BotAPI/Telegram Passport/EncryptedCredentials.cs rename to src/library/Telegram.BotAPI/Telegram Passport/EncryptedCredentials.cs index 43261509..8d1a270d 100644 --- a/src/Telegram.BotAPI/Telegram Passport/EncryptedCredentials.cs +++ b/src/library/Telegram.BotAPI/Telegram Passport/EncryptedCredentials.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Telegram Passport/EncryptedPassportElement.cs b/src/library/Telegram.BotAPI/Telegram Passport/EncryptedPassportElement.cs similarity index 99% rename from src/Telegram.BotAPI/Telegram Passport/EncryptedPassportElement.cs rename to src/library/Telegram.BotAPI/Telegram Passport/EncryptedPassportElement.cs index eb80fb6d..f8eb103c 100644 --- a/src/Telegram.BotAPI/Telegram Passport/EncryptedPassportElement.cs +++ b/src/library/Telegram.BotAPI/Telegram Passport/EncryptedPassportElement.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Telegram Passport/PassportData.cs b/src/library/Telegram.BotAPI/Telegram Passport/PassportData.cs similarity index 98% rename from src/Telegram.BotAPI/Telegram Passport/PassportData.cs rename to src/library/Telegram.BotAPI/Telegram Passport/PassportData.cs index 984dc09c..274f458e 100644 --- a/src/Telegram.BotAPI/Telegram Passport/PassportData.cs +++ b/src/library/Telegram.BotAPI/Telegram Passport/PassportData.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementError.cs b/src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementError.cs similarity index 97% rename from src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementError.cs rename to src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementError.cs index f21681e7..b7477419 100644 --- a/src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementError.cs +++ b/src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementError.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorDataField.cs b/src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorDataField.cs similarity index 98% rename from src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorDataField.cs rename to src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorDataField.cs index 252afe8a..5efb1366 100644 --- a/src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorDataField.cs +++ b/src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorDataField.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorFile.cs b/src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorFile.cs similarity index 98% rename from src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorFile.cs rename to src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorFile.cs index 6704969d..ec704573 100644 --- a/src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorFile.cs +++ b/src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorFile.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorFiles.cs b/src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorFiles.cs similarity index 98% rename from src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorFiles.cs rename to src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorFiles.cs index 5ce9b206..c9cae270 100644 --- a/src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorFiles.cs +++ b/src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorFiles.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorFrontSide.cs b/src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorFrontSide.cs similarity index 98% rename from src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorFrontSide.cs rename to src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorFrontSide.cs index 05d83146..e4087f21 100644 --- a/src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorFrontSide.cs +++ b/src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorFrontSide.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorReverseSide.cs b/src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorReverseSide.cs similarity index 98% rename from src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorReverseSide.cs rename to src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorReverseSide.cs index cfabc078..1303c321 100644 --- a/src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorReverseSide.cs +++ b/src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorReverseSide.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorSelfie.cs b/src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorSelfie.cs similarity index 98% rename from src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorSelfie.cs rename to src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorSelfie.cs index 8958ec3c..292ea3a0 100644 --- a/src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorSelfie.cs +++ b/src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorSelfie.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorSource.cs b/src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorSource.cs similarity index 98% rename from src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorSource.cs rename to src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorSource.cs index 05dd1549..4629b49d 100644 --- a/src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorSource.cs +++ b/src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorSource.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI.TelegramPassport; diff --git a/src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorTranslationFile.cs b/src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorTranslationFile.cs similarity index 98% rename from src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorTranslationFile.cs rename to src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorTranslationFile.cs index 9e064554..91eefef3 100644 --- a/src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorTranslationFile.cs +++ b/src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorTranslationFile.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorTranslationFiles.cs b/src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorTranslationFiles.cs similarity index 98% rename from src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorTranslationFiles.cs rename to src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorTranslationFiles.cs index a023cd0f..9157cd41 100644 --- a/src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorTranslationFiles.cs +++ b/src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorTranslationFiles.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorUnspecified.cs b/src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorUnspecified.cs similarity index 98% rename from src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorUnspecified.cs rename to src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorUnspecified.cs index d322fc37..721b13ad 100644 --- a/src/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorUnspecified.cs +++ b/src/library/Telegram.BotAPI/Telegram Passport/PassportElementError/PassportElementErrorUnspecified.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Telegram Passport/PassportFile.cs b/src/library/Telegram.BotAPI/Telegram Passport/PassportFile.cs similarity index 98% rename from src/Telegram.BotAPI/Telegram Passport/PassportFile.cs rename to src/library/Telegram.BotAPI/Telegram Passport/PassportFile.cs index ed420318..ec5f0416 100644 --- a/src/Telegram.BotAPI/Telegram Passport/PassportFile.cs +++ b/src/library/Telegram.BotAPI/Telegram Passport/PassportFile.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; diff --git a/src/Telegram.BotAPI/Telegram Passport/setPassportDataErrors.cs b/src/library/Telegram.BotAPI/Telegram Passport/setPassportDataErrors.cs similarity index 85% rename from src/Telegram.BotAPI/Telegram Passport/setPassportDataErrors.cs rename to src/library/Telegram.BotAPI/Telegram Passport/setPassportDataErrors.cs index 92e0d45f..4ca6f49b 100644 --- a/src/Telegram.BotAPI/Telegram Passport/setPassportDataErrors.cs +++ b/src/library/Telegram.BotAPI/Telegram Passport/setPassportDataErrors.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Threading; @@ -15,7 +15,7 @@ public static partial class TelegramPassportExtensions /// Parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool SetPassportDataErrors(this BotClient? bot, SetPassportDataErrorsArgs args) + public static bool SetPassportDataErrors(this ITelegramBotClient bot, SetPassportDataErrorsArgs args) { if (bot == default) { @@ -27,7 +27,7 @@ public static bool SetPassportDataErrors(this BotClient? bot, SetPassportDataErr throw new ArgumentNullException(nameof(args)); } - return bot.RPC(MethodNames.SetPassportDataErrors, args); + return bot.CallMethod(MethodNames.SetPassportDataErrors, args); } /// Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success. @@ -37,7 +37,7 @@ public static bool SetPassportDataErrors(this BotClient? bot, SetPassportDataErr /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SetPassportDataErrorsAsync(this BotClient? bot, SetPassportDataErrorsArgs args, [Optional] CancellationToken cancellationToken) + public static async Task SetPassportDataErrorsAsync(this ITelegramBotClient bot, SetPassportDataErrorsArgs args, CancellationToken cancellationToken = default) { if (bot == default) { @@ -49,7 +49,7 @@ public static async Task SetPassportDataErrorsAsync(this BotClient? bot, S throw new ArgumentNullException(nameof(args)); } - return await bot.RPCA(MethodNames.SetPassportDataErrors, args, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetPassportDataErrors, args, cancellationToken).ConfigureAwait(false); } /// Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success. @@ -59,7 +59,7 @@ public static async Task SetPassportDataErrorsAsync(this BotClient? bot, S /// An array of describing the errors /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool SetPassportDataErrors(this BotClient? bot, long userId, IEnumerable errors) + public static bool SetPassportDataErrors(this ITelegramBotClient bot, long userId, IEnumerable errors) { if (bot == default) { @@ -72,7 +72,7 @@ public static bool SetPassportDataErrors(this BotClient? bot, long userId, IEnum } var args = new SetPassportDataErrorsArgs(userId, errors); - return bot.RPC(MethodNames.SetPassportDataErrors, args); + return bot.CallMethod(MethodNames.SetPassportDataErrors, args); } /// Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success. @@ -83,7 +83,7 @@ public static bool SetPassportDataErrors(this BotClient? bot, long userId, IEnum /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task SetPassportDataErrorsAsync(this BotClient? bot, long userId, IEnumerable errors, [Optional] CancellationToken cancellationToken) + public static async Task SetPassportDataErrorsAsync(this ITelegramBotClient bot, long userId, IEnumerable errors, CancellationToken cancellationToken = default) { if (bot == default) { @@ -96,6 +96,6 @@ public static async Task SetPassportDataErrorsAsync(this BotClient? bot, l } var args = new SetPassportDataErrorsArgs(userId, errors); - return await bot.RPCA(MethodNames.SetPassportDataErrors, args, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.SetPassportDataErrors, args, cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Telegram.BotAPI.csproj b/src/library/Telegram.BotAPI/Telegram.BotAPI.csproj similarity index 68% rename from src/Telegram.BotAPI/Telegram.BotAPI.csproj rename to src/library/Telegram.BotAPI/Telegram.BotAPI.csproj index c1b1aa46..f6ca10b9 100644 --- a/src/Telegram.BotAPI/Telegram.BotAPI.csproj +++ b/src/library/Telegram.BotAPI/Telegram.BotAPI.csproj @@ -2,36 +2,32 @@ netstandard2.0 - 6.9.2 - Telegram.BotAPI + 7.0.0-alpha + $(AssemblyName) Quetzal Rivera true Telegram.BotAPI - Quetzal Rivera 2023 © + Quetzal Rivera 2024 © en true - - A very complete library to use Telegram Bot API in your NET project. Full support for Bot API v6.9 (September 22, 2023). - - Contains all classes and methods available from the Bot API. + A very complete library to use Telegram Bot API in your NET project. Full support for Bot API v7.0 (December 29, 2023). +- Contains all classes and methods available from the Bot API. - Telegram Bot API - Telegram Bot API - Library + Telegram;Bot;API + false Telegram.BotAPI.pfx - false latest - Telegram BotAPI + $(AssemblyName) LICENSE https://github.com/Eptagone/Telegram.BotAPI packicon.png - false https://github.com/Eptagone/Telegram.BotAPI - git + Telegram.BotAPI - - Added support for test environment + - Updated to Bot API 7.0 true - latest + latest-recommended README.md True enable @@ -43,7 +39,7 @@ - + True diff --git a/src/library/Telegram.BotAPI/TelegramBotClient.API.cs b/src/library/Telegram.BotAPI/TelegramBotClient.API.cs new file mode 100644 index 00000000..3242e7a4 --- /dev/null +++ b/src/library/Telegram.BotAPI/TelegramBotClient.API.cs @@ -0,0 +1,284 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System.Collections; +using System.IO; +using System.Net.Http; +using System.Reflection; +using System.Text; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI; + +public partial class TelegramBotClient : ITelegramBotClient +{ + internal static readonly JsonSerializerOptions SerializerOptions = new() + { + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull + }; + + private async Task CallApiMethodAndGetResultAsync(string method, object? args = null, CancellationToken cancellationToken = default) + { + BotResponse? response = null; + + do + { + if (response is not null) + { + var retryAfter = response.Parameters?.RetryAfter ?? 1; + await Task.Delay((int)retryAfter * 1000, cancellationToken).ConfigureAwait(false); + } + + response = await this.CallApiMethodAsync(method, args, cancellationToken).ConfigureAwait(false); + } + // Try again and again if the error code is 429 (Too Many Requests and AutoRetryOnRateLimit is true) + while (response.ErrorCode == 429 && this.options.AutoRetryOnRateLimit); + + if (response.Ok) + { + return response.Result; + } + + if (this.options.IgnoreBotExceptions) + { + return default; + } + + if (response.ErrorCode is null || response.Description is null) + { + throw new JsonException("Cannot deserialize the response error."); + } + + throw new BotRequestException((int)response.ErrorCode, response.Description, response.Parameters); + } + + private async Task> CallApiMethodAsync(string method, object? args = null, CancellationToken cancellationToken = default) + { + var requestUri = this.options.UseTestEnvironment + ? $"bot{this.options.BotToken}/test/{method}" + : $"bot{this.options.BotToken}/{method}"; + + if (this.httpClient.BaseAddress?.AbsoluteUri != this.options.ServerAddress) + { + requestUri = $"{this.options.ServerAddress}/{requestUri}"; + } + + HttpRequestMessage requestMessage; + + if (args is null) + { + requestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); + } + else if (args.GetType().IsPrimitive || args is string) + { + throw new ArgumentException("The method arguments must be an object."); + } + else if (args is Stream streamArgs) + { + var content = new StreamContent(streamArgs); + content.Headers.ContentType = new("application/json"); + requestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri) + { + Content = content + }; + } + else if (ArgsHasFiles(args)) + { + var content = CreateFormDataFromObject(args); + requestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri) + { + Content = content + }; + } + else + { + var stream = new MemoryStream(); + await JsonSerializer.SerializeAsync(stream, args, args.GetType(), SerializerOptions, cancellationToken).ConfigureAwait(false); + stream.Seek(0, SeekOrigin.Begin); + var content = new StreamContent(stream); + content.Headers.ContentType = new("application/json"); + requestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri) + { + Content = content + }; + } + + var response = await this.httpClient.SendAsync(requestMessage, cancellationToken).ConfigureAwait(false); + + try + { + response.EnsureSuccessStatusCode(); + } + catch (HttpRequestException) + { + if (response.Content.Headers.ContentType.MediaType != "application/json") + { + throw; + } + } + + var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + var botResponse = await JsonSerializer.DeserializeAsync>(responseStream, SerializerOptions, cancellationToken).ConfigureAwait(false); + + return botResponse ?? throw new JsonException("Cannot deserialize the response."); + } + + private static MultipartFormDataContent CreateFormDataFromObject(object args) + { + var content = new MultipartFormDataContent(Guid.NewGuid().ToString() + DateTime.UtcNow.Ticks); + + // If the value is an enumerable, add each item to the content. + if (args is IDictionary dictionary) + { + foreach (var item in dictionary) + { + if (item.Value is null) + { + continue; + } + if (item.Value.GetType().IsPrimitive || item.Value is string) + { + content.Add(new StringContent(item.Value.ToString()), item.Key); + } + else if (item.Value is InputFile inputFile) + { + content.Add(inputFile.Content, item.Key, inputFile.Filename); + } + else if (item.Value is AttachedFile atF) + { + content.Add(atF.File.Content, atF.Name, atF.File.Filename); + } + else if (item.Value is IEnumerable attachedFiles) + { + foreach (var aF in attachedFiles) + { + content.Add(aF.File.Content, aF.Name, aF.File.Filename); + } + } + else + { + var json = JsonSerializer.Serialize(item.Value, SerializerOptions); + content.Add(new StringContent(json, Encoding.UTF8), item.Key); + } + } + } + else + { + var properties = args.GetType().GetProperties(); + + foreach (var property in properties) + { + var value = property.GetValue(args); + if (value is null) + { + continue; + } + + var jsonAttribute = property.GetCustomAttribute(); + if (jsonAttribute is not null) + { + if (value.GetType().IsPrimitive || value is string) + { + content.Add(new StringContent(value.ToString()), jsonAttribute.Name); + } + else if (value is InputFile inputFile) + { + content.Add(inputFile.Content, jsonAttribute.Name, inputFile.Filename); + } + else if (value is AttachedFile atF) + { + content.Add(atF.File.Content, atF.Name, atF.File.Filename); + } + else if (value is IEnumerable attachedFiles) + { + foreach (var aF in attachedFiles) + { + content.Add(aF.File.Content, aF.Name, aF.File.Filename); + } + } + else + { + var json = JsonSerializer.Serialize(value, SerializerOptions); + content.Add(new StringContent(json, Encoding.UTF8), jsonAttribute.Name); + } + } + else + { + if (value is AttachedFile aF) + { + content.Add(aF.File.Content, property.Name, aF.File.Filename); + } + else if (value is IEnumerable attachedFiles) + { + foreach (var attachedFile in attachedFiles) + { + content.Add(attachedFile.File.Content, attachedFile.Name, attachedFile.File.Filename); + } + } + } + } + + } + + return content; + } + + private static bool ArgsHasFiles(object args) + { + if (typeof(IEnumerable).IsAssignableFrom(args.GetType())) + { + if (args is IDictionary items) + { + foreach (var item in items) + { + if (item.Value is IEnumerable attachedFiles && attachedFiles.Any()) + { + return true; + } + else if (item.Value is InputFile || item.Value is AttachedFile) + { + return true; + } + } + } + } + else + { + var properties = args.GetType().GetProperties(); + + foreach (var property in properties) + { + var value = property.GetValue(args); + if (value is null || value.GetType().IsPrimitive || value is string) + { + continue; + } + + if (value is InputFile || value is AttachedFile) + { + return true; + } + else if (typeof(IEnumerable).IsAssignableFrom(property.PropertyType)) + { + if (property.GetValue(args) is not IEnumerable items) + { + continue; + } + foreach (object item in items) + { + if (item is InputFile || item is AttachedFile) + { + return true; + } + } + } + } + } + + return false; + } +} diff --git a/src/library/Telegram.BotAPI/TelegramBotClient.ITelegramBotClient.cs b/src/library/Telegram.BotAPI/TelegramBotClient.ITelegramBotClient.cs new file mode 100644 index 00000000..0fac480c --- /dev/null +++ b/src/library/Telegram.BotAPI/TelegramBotClient.ITelegramBotClient.cs @@ -0,0 +1,25 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System.Threading; +using System.Threading.Tasks; + +namespace Telegram.BotAPI; + +public partial class TelegramBotClient : ITelegramBotClient +{ + /// + TelegramBotClientOptions ITelegramBotClient.Options => this.options; + + /// + public TResult CallMethod(string method, object? args = null) => this.CallApiMethodAndGetResultAsync(method, args).GetAwaiter().GetResult()!; + + /// + public Task CallMethodAsync(string method, object? args = null, CancellationToken cancellationToken = default) => this.CallApiMethodAndGetResultAsync(method, args, cancellationToken)!; + + /// + public BotResponse CallMethodDirect(string method, object? args = null) => this.CallApiMethodAsync(method, args).GetAwaiter().GetResult(); + + /// + public Task> CallMethodDirectAsync(string method, object? args = null, CancellationToken cancellationToken = default) => this.CallApiMethodAsync(method, args, cancellationToken); +} \ No newline at end of file diff --git a/src/library/Telegram.BotAPI/TelegramBotClient.cs b/src/library/Telegram.BotAPI/TelegramBotClient.cs new file mode 100644 index 00000000..3a42b51a --- /dev/null +++ b/src/library/Telegram.BotAPI/TelegramBotClient.cs @@ -0,0 +1,53 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +#region AUTHOR +/* + * ┌────────────────────────────────────────────────────────────────────────────┐ + * │ █████████████████████████████████████████████████████████████████████ │ + * │ ======================================================================= │ + * │ Author: Quetzal Rivera │ + * │ Email: QuetzalDeveloper@outlook.com │ + * │ Project: Telegram.BotAPI │ + * │ Creation Date: 13-12-2019 │ + * │ Description: Library to access and interact with the Telegram Bot API. │ + * │ ======================================================================= │ + * └────────────────────────────────────────────────────────────────────────────┘ + */ +#endregion + +using System.Net.Http; + +namespace Telegram.BotAPI; + +/// +/// Provides a class for sending requests to the Telegram Bot API. +/// +public partial class TelegramBotClient : ITelegramBotClient +{ + private readonly TelegramBotClientOptions options; + internal readonly HttpClient httpClient; + + /// + /// Initialize a new instance of the class. + /// + /// Token granted by BotFather. Required to access the Telegram bot API. + /// Optional. Provide a specific HttpClient for this instance of BotClient. + public TelegramBotClient(string botToken, HttpClient? httpClient = null) : this(new TelegramBotClientOptions(botToken), httpClient) + { + } + + /// + /// Initialize a new instance of the class. + /// + /// Options for the . + /// Optional. Provide a specific HttpClient for this instance of BotClient. + public TelegramBotClient(TelegramBotClientOptions options, HttpClient? httpClient = null) + { + this.options = options; + this.httpClient = httpClient ?? new HttpClient() + { + BaseAddress = new Uri(options.ServerAddress) + }; + } +} diff --git a/src/library/Telegram.BotAPI/TelegramBotClientOptions.cs b/src/library/Telegram.BotAPI/TelegramBotClientOptions.cs new file mode 100644 index 00000000..fa92f842 --- /dev/null +++ b/src/library/Telegram.BotAPI/TelegramBotClientOptions.cs @@ -0,0 +1,72 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +namespace Telegram.BotAPI; + +/// +/// Options for a . +/// +public record TelegramBotClientOptions +{ + /// + /// Default server address to send bot request. + /// + public const string BaseServerAddress = "https://api.telegram.org"; + + private string serverAddress = BaseServerAddress; + + /// + /// Initialize a Telegram Bot Client. + /// + /// Token granted by BotFather. Required to access the Telegram bot API. + public TelegramBotClientOptions(string botToken) => this.BotToken = botToken; + + /// + /// Set true if you want methods to automatically retry the request when the server returns a 429 (Too Many Requests) error. + /// Default value is false. + /// + public bool AutoRetryOnRateLimit { get; set; } + + /// + /// Token granted by BotFather. + /// Required to access the Telegram bot API. + /// + public string BotToken { get; } + + /// + /// Set true if you want methods to return a default value when bot requests are rejected instead of throwing a . + /// Default value is false. + /// + /// + /// This feature was added for specific testing purposes. For example, running the bot in fairly unstable environments. + /// It's not recommended to use this feature in production environments. All exceptions should be handled properly. + /// + public bool IgnoreBotExceptions { get; set; } + + /// + /// The server address to send bot request. + /// Default value is: https://api.telegram.org + /// + /// + /// Change this parameter if you're using your own Local Bot API Server. + /// + public string ServerAddress + { + get => this.serverAddress; + set + { + if (!Uri.TryCreate(value, UriKind.Absolute, out _)) + { + throw new ArgumentException("The value must be a valid Uri.", nameof(value)); + } + this.serverAddress = value; + } + } + + /// + /// True if the current client is using the Test Environment. + /// If true, all requests methods will be prefixed with "/test". + /// Default value is false. + /// + public bool UseTestEnvironment { get; set; } +} diff --git a/src/Telegram.BotAPI/Sugar Library/TelegramConstants.cs b/src/library/Telegram.BotAPI/TelegramConstants.cs similarity index 94% rename from src/Telegram.BotAPI/Sugar Library/TelegramConstants.cs rename to src/library/Telegram.BotAPI/TelegramConstants.cs index 895530c3..18014243 100644 --- a/src/Telegram.BotAPI/Sugar Library/TelegramConstants.cs +++ b/src/library/Telegram.BotAPI/TelegramConstants.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI; diff --git a/src/library/Telegram.BotAPI/Tools.cs b/src/library/Telegram.BotAPI/Tools.cs new file mode 100644 index 00000000..934cc023 --- /dev/null +++ b/src/library/Telegram.BotAPI/Tools.cs @@ -0,0 +1,25 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace Telegram.BotAPI; + +internal static class Tools +{ + internal static async Task SerializeAsStreamAsync(object args, [Optional] JsonSerializerOptions options, [Optional] CancellationToken cancellationToken) + { + if (options == default) + { + options = TelegramBotClient.SerializerOptions; + } + var stream = new MemoryStream(); + await JsonSerializer.SerializeAsync(stream, args, args.GetType(), options, cancellationToken).ConfigureAwait(false); + stream.Seek(0, SeekOrigin.Begin); + return stream; + } +} diff --git a/src/Telegram.BotAPI/Updating messages/Args/EditMessageCaptionArgs.cs b/src/library/Telegram.BotAPI/Updating messages/Args/EditMessageCaptionArgs.cs similarity index 53% rename from src/Telegram.BotAPI/Updating messages/Args/EditMessageCaptionArgs.cs rename to src/library/Telegram.BotAPI/Updating messages/Args/EditMessageCaptionArgs.cs index 5c807b78..ef4a5abd 100644 --- a/src/Telegram.BotAPI/Updating messages/Args/EditMessageCaptionArgs.cs +++ b/src/library/Telegram.BotAPI/Updating messages/Args/EditMessageCaptionArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; @@ -10,7 +10,7 @@ namespace Telegram.BotAPI.UpdatingMessages; /// EditMessageCaption method arguments. [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] -public class EditMessageCaptionArgs : ICaption, IFormattableMessage +public class EditMessageCaptionArgs { /// /// Initialize a new instance of . @@ -45,33 +45,46 @@ public EditMessageCaptionArgs(string inlineMessageId) this.InlineMessageId = inlineMessageId ?? throw new ArgumentNullException(nameof(inlineMessageId)); } - - /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). - [JsonPropertyName(PropertyNames.ChatId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + /// + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public object? ChatId { get; } - /// Required if inline_message_id is not specified. Identifier of the message to edit. - [JsonPropertyName(PropertyNames.MessageId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + /// + /// Required if inline_message_id is not specified. Identifier of the message to edit + /// + [JsonPropertyName(PropertyNames.MessageId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int? MessageId { get; } - /// Required if chat_id and message_id are not specified. Identifier of the inline message. - [JsonPropertyName(PropertyNames.InlineMessageId)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + /// + /// Required if chat_id and message_id are not specified. Identifier of the inline message + /// + [JsonPropertyName(PropertyNames.InlineMessageId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? InlineMessageId { get; } - /// New caption of the message. - [JsonPropertyName(PropertyNames.Caption)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + /// + /// New caption of the message, 0-1024 characters after entities parsing + /// + [JsonPropertyName(PropertyNames.Caption)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? Caption { get; set; } - /// Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. - [JsonPropertyName(PropertyNames.ParseMode)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + /// + /// Mode for parsing entities in the message caption. See formatting options for more details. + /// + [JsonPropertyName(PropertyNames.ParseMode)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string? ParseMode { get; set; } - /// List of special entities that appear in the caption, which can be specified instead of parse_mode. - [JsonPropertyName(PropertyNames.CaptionEntities)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + /// + /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode + /// + [JsonPropertyName(PropertyNames.CaptionEntities)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public IEnumerable? CaptionEntities { get; set; } - /// A object for an inline keyboard. - [JsonPropertyName(PropertyNames.ReplyMarkup)] - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + /// + /// A JSON-serialized object for an inline keyboard. + /// + [JsonPropertyName(PropertyNames.ReplyMarkup)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public InlineKeyboardMarkup? ReplyMarkup { get; set; } } diff --git a/src/library/Telegram.BotAPI/Updating messages/Args/EditMessageLiveLocationArgs.cs b/src/library/Telegram.BotAPI/Updating messages/Args/EditMessageLiveLocationArgs.cs new file mode 100644 index 00000000..b69d455d --- /dev/null +++ b/src/library/Telegram.BotAPI/Updating messages/Args/EditMessageLiveLocationArgs.cs @@ -0,0 +1,111 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.UpdatingMessages; + +/// EditMessageLiveLocation method arguments.} +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class EditMessageLiveLocationArgs +{ + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// Identifier of the sent message + /// Longitude as defined by sender + /// Latitude as defined by sender + public EditMessageLiveLocationArgs(long chatId, int messageId, float longitude, float latitude) + { + this.ChatId = chatId; + this.MessageId = messageId; + this.Longitude = longitude; + this.Latitude = latitude; + } + + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// Identifier of the sent message + /// Longitude as defined by sender + /// Latitude as defined by sender + public EditMessageLiveLocationArgs(string chatId, int messageId, float longitude, float latitude) + { + this.ChatId = chatId; + this.MessageId = messageId; + this.Longitude = longitude; + this.Latitude = latitude; + } + + /// + /// Initializes a new instance of the class. + /// + /// Identifier of the inline message + /// Longitude as defined by sender + /// Latitude as defined by sender + public EditMessageLiveLocationArgs(string inlineMessageId, float longitude, float latitude) + { + this.InlineMessageId = inlineMessageId; + this.Longitude = longitude; + this.Latitude = latitude; + } + + /// + /// Latitude of new location + /// + [JsonPropertyName(PropertyNames.Latitude)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public float Latitude { get; set; } + /// + /// Longitude of new location + /// + [JsonPropertyName(PropertyNames.Longitude)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public float Longitude { get; set; } + /// + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object? ChatId { get; } + /// + /// Required if inline_message_id is not specified. Identifier of the message to edit + /// + [JsonPropertyName(PropertyNames.MessageId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? MessageId { get; } + /// + /// Required if chat_id and message_id are not specified. Identifier of the inline message + /// + [JsonPropertyName(PropertyNames.InlineMessageId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? InlineMessageId { get; } + /// + /// The radius of uncertainty for the location, measured in meters; 0-1500 + /// + [JsonPropertyName(PropertyNames.HorizontalAccuracy)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public float? HorizontalAccuracy { get; set; } + /// + /// Direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. + /// + [JsonPropertyName(PropertyNames.Heading)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public ushort? Heading { get; set; } + /// + /// The maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. + /// + [JsonPropertyName(PropertyNames.ProximityAlertRadius)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public uint? ProximityAlertRadius { get; set; } + /// + /// A JSON-serialized object for a new inline keyboard. + /// + [JsonPropertyName(PropertyNames.ReplyMarkup)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public InlineKeyboardMarkup? ReplyMarkup { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Updating messages/Args/EditMessageMediaArgs.cs b/src/library/Telegram.BotAPI/Updating messages/Args/EditMessageMediaArgs.cs new file mode 100644 index 00000000..03f15156 --- /dev/null +++ b/src/library/Telegram.BotAPI/Updating messages/Args/EditMessageMediaArgs.cs @@ -0,0 +1,84 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using Telegram.BotAPI.AvailableMethods; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.UpdatingMessages; + +/// +/// EditMessageMedia method arguments. +/// +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class EditMessageMediaArgs : AttachedFilesArgsBase +{ + /// + /// Initializes a new instance of with required parameters. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// Identifier of the message to edit + /// A JSON-serialized object for a new media content of the message + public EditMessageMediaArgs(long chatId, int messageId, InputMedia media) + { + this.ChatId = chatId; + this.MessageId = messageId; + this.Media = media; + } + + /// + /// Initializes a new instance of with required parameters. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// Identifier of the message to edit + /// A JSON-serialized object for a new media content of the message + public EditMessageMediaArgs(string chatId, int messageId, InputMedia media) + { + this.ChatId = chatId; + this.MessageId = messageId; + this.Media = media; + } + + /// + /// Initializes a new instance of with required parameters. + /// + /// Identifier of the inline message + /// A JSON-serialized object for a new media content of the message + public EditMessageMediaArgs(string inlineMessageId, InputMedia media) + { + this.InlineMessageId = inlineMessageId; + this.Media = media; + } + + /// + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object? ChatId { get; } + /// + /// Required if inline_message_id is not specified. Identifier of the message to edit + /// + [JsonPropertyName(PropertyNames.MessageId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? MessageId { get; } + /// + /// Required if chat_id and message_id are not specified. Identifier of the inline message + /// + [JsonPropertyName(PropertyNames.InlineMessageId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? InlineMessageId { get; } + /// + /// A JSON-serialized object for a new media content of the message + /// + [JsonPropertyName(PropertyNames.Media)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public InputMedia Media { get; set; } + /// + /// A JSON-serialized object for a new inline keyboard. + /// + [JsonPropertyName(PropertyNames.ReplyMarkup)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public InlineKeyboardMarkup? ReplyMarkup { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Updating messages/Args/EditMessageReplyMarkup.cs b/src/library/Telegram.BotAPI/Updating messages/Args/EditMessageReplyMarkup.cs new file mode 100644 index 00000000..53c94396 --- /dev/null +++ b/src/library/Telegram.BotAPI/Updating messages/Args/EditMessageReplyMarkup.cs @@ -0,0 +1,69 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.UpdatingMessages; + +/// EditMessageReplyMarkup method arguments. +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class EditMessageReplyMarkupArgs +{ + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// Identifier of the message to edit + public EditMessageReplyMarkupArgs(long chatId, int messageId) + { + this.ChatId = chatId; + this.MessageId = messageId; + } + + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// Identifier of the message to edit + public EditMessageReplyMarkupArgs(string chatId, int messageId) + { + this.ChatId = chatId; + this.MessageId = messageId; + } + + /// + /// Initializes a new instance of the class. + /// + /// Identifier of the inline message + public EditMessageReplyMarkupArgs(string inlineMessageId) + { + this.InlineMessageId = inlineMessageId; + } + + /// + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object? ChatId { get; } + /// + /// Required if inline_message_id is not specified. Identifier of the message to edit + /// + [JsonPropertyName(PropertyNames.MessageId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? MessageId { get; } + /// + /// Required if chat_id and message_id are not specified. Identifier of the inline message + /// + [JsonPropertyName(PropertyNames.InlineMessageId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? InlineMessageId { get; } + /// + /// A JSON-serialized object for an inline keyboard. + /// + [JsonPropertyName(PropertyNames.ReplyMarkup)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public InlineKeyboardMarkup? ReplyMarkup { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Updating messages/Args/EditMessageTextArgs.cs b/src/library/Telegram.BotAPI/Updating messages/Args/EditMessageTextArgs.cs new file mode 100644 index 00000000..7301a4ee --- /dev/null +++ b/src/library/Telegram.BotAPI/Updating messages/Args/EditMessageTextArgs.cs @@ -0,0 +1,100 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.UpdatingMessages; + +/// EditMessage method arguments. +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class EditMessageTextArgs +{ + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// Identifier of the message to edit + /// New text of the message. + public EditMessageTextArgs(long chatId, int messageId, string text) + { + this.ChatId = chatId; + this.MessageId = messageId; + this.Text = text ?? throw new ArgumentNullException(nameof(text)); + } + + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// Identifier of the message to edit + /// New text of the message. + public EditMessageTextArgs(string chatId, int messageId, string text) + { + this.ChatId = chatId; + this.MessageId = messageId; + this.Text = text ?? throw new ArgumentNullException(nameof(text)); + } + + /// + /// Initializes a new instance of the class. + /// + /// Identifier of the inline message + /// New text of the message. + /// Thrown when a required parameter is null. + public EditMessageTextArgs(string inlineMessageId, string text) + { + this.InlineMessageId = inlineMessageId; + this.Text = text ?? throw new ArgumentNullException(nameof(text)); + } + + /// + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object? ChatId { get; } + /// + /// Required if inline_message_id is not specified. Identifier of the message to edit + /// + [JsonPropertyName(PropertyNames.MessageId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public long? MessageId { get; } + /// + /// Required if chat_id and message_id are not specified. Identifier of the inline message + /// + [JsonPropertyName(PropertyNames.InlineMessageId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? InlineMessageId { get; } + /// + /// New text of the message, 1-4096 characters after entities parsing + /// + [JsonPropertyName(PropertyNames.Text)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string Text { get; set; } + /// + /// Mode for parsing entities in the message text. See formatting options for more details. + /// + [JsonPropertyName(PropertyNames.ParseMode)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? ParseMode { get; set; } + /// + /// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode + /// + [JsonPropertyName(PropertyNames.Entities)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public IEnumerable? Entities { get; set; } + /// + /// Link preview generation options for the message + /// + [JsonPropertyName(PropertyNames.LinkPreviewOptions)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public LinkPreviewOptions? LinkPreviewOptions { get; set; } + /// + /// A JSON-serialized object for an inline keyboard. + /// + [JsonPropertyName(PropertyNames.ReplyMarkup)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public InlineKeyboardMarkup? ReplyMarkup { get; set; } +} diff --git a/src/library/Telegram.BotAPI/Updating messages/Args/StopMessageLiveLocationArgs.cs b/src/library/Telegram.BotAPI/Updating messages/Args/StopMessageLiveLocationArgs.cs new file mode 100644 index 00000000..af4a7f4a --- /dev/null +++ b/src/library/Telegram.BotAPI/Updating messages/Args/StopMessageLiveLocationArgs.cs @@ -0,0 +1,69 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.UpdatingMessages; + +/// StopMessageLiveLocation method arguments +[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] +public class StopMessageLiveLocationArgs +{ + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// Identifier of the message with live location to stop + public StopMessageLiveLocationArgs(long chatId, int messageId) + { + this.ChatId = chatId; + this.MessageId = messageId; + } + + /// + /// Initializes a new instance of the class. + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// Identifier of the message with live location to stop + public StopMessageLiveLocationArgs(string chatId, int messageId) + { + this.ChatId = chatId; + this.MessageId = messageId; + } + + /// + /// Initializes a new instance of the class. + /// + /// Identifier of the inline message + public StopMessageLiveLocationArgs(string inlineMessageId) + { + this.InlineMessageId = inlineMessageId; + } + + /// + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername) + /// + [JsonPropertyName(PropertyNames.ChatId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public object? ChatId { get; } + /// + /// Required if inline_message_id is not specified. Identifier of the message with live location to stop + /// + [JsonPropertyName(PropertyNames.MessageId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public int? MessageId { get; } + /// + /// Required if chat_id and message_id are not specified. Identifier of the inline message + /// + [JsonPropertyName(PropertyNames.InlineMessageId)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public string? InlineMessageId { get; } + /// + /// A JSON-serialized object for a new inline keyboard. + /// + [JsonPropertyName(PropertyNames.ReplyMarkup)] + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public InlineKeyboardMarkup? ReplyMarkup { get; set; } +} diff --git a/src/Telegram.BotAPI/Updating messages/Args/StopPollArgs.cs b/src/library/Telegram.BotAPI/Updating messages/Args/StopPollArgs.cs similarity index 65% rename from src/Telegram.BotAPI/Updating messages/Args/StopPollArgs.cs rename to src/library/Telegram.BotAPI/Updating messages/Args/StopPollArgs.cs index efcfb5ef..d2e10d9c 100644 --- a/src/Telegram.BotAPI/Updating messages/Args/StopPollArgs.cs +++ b/src/library/Telegram.BotAPI/Updating messages/Args/StopPollArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using Newtonsoft.Json; @@ -11,16 +11,22 @@ namespace Telegram.BotAPI.UpdatingMessages; [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] public class StopPollArgs { - /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// [JsonPropertyName(PropertyNames.ChatId)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public object ChatId { get; set; } - /// Identifier of the original message with the poll. + /// + /// Identifier of the original message with the poll. + /// [JsonPropertyName(PropertyNames.MessageId)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int MessageId { get; set; } - /// Optional. A object for a new message inline keyboard. + /// + /// Optional. A object for a new message inline keyboard. + /// [JsonPropertyName(PropertyNames.ReplyMarkup)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public InlineKeyboardMarkup ReplyMarkup { get; set; } + public InlineKeyboardMarkup? ReplyMarkup { get; set; } } diff --git a/src/Telegram.BotAPI/Updating messages/deleteMessage.cs b/src/library/Telegram.BotAPI/Updating messages/deleteMessage.cs similarity index 88% rename from src/Telegram.BotAPI/Updating messages/deleteMessage.cs rename to src/library/Telegram.BotAPI/Updating messages/deleteMessage.cs index 3b64e882..f82776af 100644 --- a/src/Telegram.BotAPI/Updating messages/deleteMessage.cs +++ b/src/library/Telegram.BotAPI/Updating messages/deleteMessage.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -23,7 +23,7 @@ public static partial class UpdatingMessagesExtensions /// Identifier of the message to delete. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool DeleteMessage(this BotClient? bot, long chatId, int messageId) + public static bool DeleteMessage(this ITelegramBotClient bot, long chatId, int messageId) { if (bot == default) { @@ -38,7 +38,7 @@ public static bool DeleteMessage(this BotClient? bot, long chatId, int messageId json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.DeleteMessage, stream); + return bot.CallMethod(MethodNames.DeleteMessage, stream); } /// Use this method to delete a message, including service messages, with the following limitations:
/// - A message can only be deleted if it was sent less than 48 hours ago.
@@ -53,7 +53,7 @@ public static bool DeleteMessage(this BotClient? bot, long chatId, int messageId /// Identifier of the message to delete. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static bool DeleteMessage(this BotClient? bot, string chatId, int messageId) + public static bool DeleteMessage(this ITelegramBotClient bot, string chatId, int messageId) { if (bot == default) { @@ -68,7 +68,7 @@ public static bool DeleteMessage(this BotClient? bot, string chatId, int message json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.DeleteMessage, stream); + return bot.CallMethod(MethodNames.DeleteMessage, stream); } /// Use this method to delete a message, including service messages, with the following limitations:
/// - A message can only be deleted if it was sent less than 48 hours ago.
@@ -84,7 +84,7 @@ public static bool DeleteMessage(this BotClient? bot, string chatId, int message /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task DeleteMessageAsync(this BotClient? bot, long chatId, int messageId, [Optional] CancellationToken cancellationToken) + public static async Task DeleteMessageAsync(this ITelegramBotClient bot, long chatId, int messageId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -100,7 +100,7 @@ public static async Task DeleteMessageAsync(this BotClient? bot, long chat await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.DeleteMessage, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.DeleteMessage, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to delete a message, including service messages, with the following limitations:
/// - A message can only be deleted if it was sent less than 48 hours ago.
@@ -116,7 +116,7 @@ public static async Task DeleteMessageAsync(this BotClient? bot, long chat /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task DeleteMessageAsync(this BotClient? bot, string chatId, int messageId, [Optional] CancellationToken cancellationToken) + public static async Task DeleteMessageAsync(this ITelegramBotClient bot, string chatId, int messageId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -132,6 +132,6 @@ public static async Task DeleteMessageAsync(this BotClient? bot, string ch await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.DeleteMessage, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.DeleteMessage, stream, cancellationToken).ConfigureAwait(false); } } diff --git a/src/library/Telegram.BotAPI/Updating messages/deleteMessages.cs b/src/library/Telegram.BotAPI/Updating messages/deleteMessages.cs new file mode 100644 index 00000000..a9db2b49 --- /dev/null +++ b/src/library/Telegram.BotAPI/Updating messages/deleteMessages.cs @@ -0,0 +1,93 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System.Threading; +using System.Threading.Tasks; + +namespace Telegram.BotAPI.UpdatingMessages; + +/// Available Methods +public static partial class AvailableMethodsExtensions +{ + /// + /// Use this method to delete multiple messages simultaneously. If some of the specified messages can't be found, they are skipped. Returns True on success. + /// + /// The bot client. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Identifiers of 1-100 messages to delete. See deleteMessage for limitations on which messages can be deleted. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static bool DeleteMessages(this ITelegramBotClient client, long chatId, IEnumerable messageIds) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new Dictionary() + { + {PropertyNames.ChatId, chatId}, + {PropertyNames.MessageIds, messageIds} + }; + return client.CallMethod(MethodNames.DeleteMessages, args); + } + + /// + /// Use this method to delete multiple messages simultaneously. If some of the specified messages can't be found, they are skipped. Returns True on success. + /// + /// The bot client. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Identifiers of 1-100 messages to delete. See deleteMessage for limitations on which messages can be deleted. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static bool DeleteMessages(this ITelegramBotClient client, string chatId, IEnumerable messageIds) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new Dictionary() + { + {PropertyNames.ChatId, chatId}, + {PropertyNames.MessageIds, messageIds} + }; + return client.CallMethod(MethodNames.DeleteMessages, args); + } + + /// + /// Use this method to delete multiple messages simultaneously. If some of the specified messages can't be found, they are skipped. Returns True on success. + /// + /// The bot client. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Identifiers of 1-100 messages to delete. See deleteMessage for limitations on which messages can be deleted. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static async Task DeleteMessagesAsync(this ITelegramBotClient client, long chatId, IEnumerable messageIds, CancellationToken cancellationToken = default) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new Dictionary() + { + {PropertyNames.ChatId, chatId}, + {PropertyNames.MessageIds, messageIds} + }; + return await client.CallMethodAsync(MethodNames.DeleteMessages, args, cancellationToken).ConfigureAwait(false); + } + + /// + /// Use this method to delete multiple messages simultaneously. If some of the specified messages can't be found, they are skipped. Returns True on success. + /// + /// The bot client. + /// Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Identifiers of 1-100 messages to delete. See deleteMessage for limitations on which messages can be deleted. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static async Task DeleteMessagesAsync(this ITelegramBotClient client, string chatId, IEnumerable messageIds, CancellationToken cancellationToken = default) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new Dictionary() + { + {PropertyNames.ChatId, chatId}, + {PropertyNames.MessageIds, messageIds} + }; + return await client.CallMethodAsync(MethodNames.DeleteMessages, args, cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/library/Telegram.BotAPI/Updating messages/editMessageCaption.cs b/src/library/Telegram.BotAPI/Updating messages/editMessageCaption.cs new file mode 100644 index 00000000..bb9d5995 --- /dev/null +++ b/src/library/Telegram.BotAPI/Updating messages/editMessageCaption.cs @@ -0,0 +1,215 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System.Threading; +using System.Threading.Tasks; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.UpdatingMessages; + +public static partial class UpdatingMessagesExtensions +{ + /// + /// Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// BotClient + /// Parameters. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + /// Thrown when is not or . + /// or . On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. + public static TReturn EditMessageCaption(this ITelegramBotClient client, EditMessageCaptionArgs args) + { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + if (args == default) + { + throw new ArgumentNullException(nameof(args)); + } + if (typeof(TReturn) != typeof(Message) && typeof(TReturn) != typeof(bool)) + { + throw new ArgumentException($"{nameof(TReturn)} must be a Telegram.BotAPI.AvailableTypes.Message or bool."); + } + return client.CallMethod(MethodNames.EditMessageCaption, args); + } + + /// + /// Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// BotClient + /// Parameters. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + /// Thrown when is not or . + /// or . On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. + public static Task EditMessageCaptionAsync(this ITelegramBotClient client, EditMessageCaptionArgs args, CancellationToken cancellationToken = default) + { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + if (args == default) + { + throw new ArgumentNullException(nameof(args)); + } + if (typeof(TReturn) != typeof(Message) && typeof(TReturn) != typeof(bool)) + { + throw new ArgumentException($"{nameof(TReturn)} must be a Telegram.BotAPI.AvailableTypes.Message or bool."); + } + return client.CallMethodAsync(MethodNames.EditMessageCaption, args, cancellationToken); + } + + /// + /// Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Required if inline_message_id is not specified. Identifier of the message to edit. + /// New caption of the message, 0-1024 characters after entities parsing. + /// Mode for parsing entities in the message caption. See formatting options for more details. + /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. + /// A JSON-serialized object for an inline keyboard. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Message EditMessageCaption(this ITelegramBotClient client, long chatId, int messageId, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, InlineKeyboardMarkup? replyMarkup = null) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new EditMessageCaptionArgs(chatId, messageId) + { + Caption = caption, + ParseMode = parseMode, + CaptionEntities = captionEntities, + ReplyMarkup = replyMarkup + }; + return client.CallMethod(MethodNames.EditMessageCaption, args); + } + + /// + /// Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Required if inline_message_id is not specified. Identifier of the message to edit. + /// New caption of the message, 0-1024 characters after entities parsing. + /// Mode for parsing entities in the message caption. See formatting options for more details. + /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. + /// A JSON-serialized object for an inline keyboard. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Message EditMessageCaption(this ITelegramBotClient client, string chatId, int messageId, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, InlineKeyboardMarkup? replyMarkup = null) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new EditMessageCaptionArgs(chatId, messageId) + { + Caption = caption, + ParseMode = parseMode, + CaptionEntities = captionEntities, + ReplyMarkup = replyMarkup + }; + return client.CallMethod(MethodNames.EditMessageCaption, args); + } + + /// + /// Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Required if inline_message_id is not specified. Identifier of the message to edit. + /// New caption of the message, 0-1024 characters after entities parsing. + /// Mode for parsing entities in the message caption. See formatting options for more details. + /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. + /// A JSON-serialized object for an inline keyboard. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Task EditMessageCaptionAsync(this ITelegramBotClient client, long chatId, int messageId, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, InlineKeyboardMarkup? replyMarkup = null, CancellationToken cancellationToken = default) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new EditMessageCaptionArgs(chatId, messageId) + { + Caption = caption, + ParseMode = parseMode, + CaptionEntities = captionEntities, + ReplyMarkup = replyMarkup + }; + return client.CallMethodAsync(MethodNames.EditMessageCaption, args, cancellationToken); + } + + /// + /// Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Required if inline_message_id is not specified. Identifier of the message to edit. + /// New caption of the message, 0-1024 characters after entities parsing. + /// Mode for parsing entities in the message caption. See formatting options for more details. + /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. + /// A JSON-serialized object for an inline keyboard. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Task EditMessageCaptionAsync(this ITelegramBotClient client, string chatId, int messageId, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, InlineKeyboardMarkup? replyMarkup = null, CancellationToken cancellationToken = default) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new EditMessageCaptionArgs(chatId, messageId) + { + Caption = caption, + ParseMode = parseMode, + CaptionEntities = captionEntities, + ReplyMarkup = replyMarkup + }; + return client.CallMethodAsync(MethodNames.EditMessageCaption, args, cancellationToken); + } + + /// + /// Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Required if chat_id and message_id are not specified. Identifier of the inline message. + /// New caption of the message, 0-1024 characters after entities parsing. + /// Mode for parsing entities in the message caption. See formatting options for more details. + /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. + /// A JSON-serialized object for an inline keyboard. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static bool EditMessageCaption(this ITelegramBotClient client, string inlineMessageId, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, InlineKeyboardMarkup? replyMarkup = null) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new EditMessageCaptionArgs(inlineMessageId) + { + Caption = caption, + ParseMode = parseMode, + CaptionEntities = captionEntities, + ReplyMarkup = replyMarkup + }; + return client.CallMethod(MethodNames.EditMessageCaption, args); + } + + /// + /// Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Required if chat_id and message_id are not specified. Identifier of the inline message. + /// New caption of the message, 0-1024 characters after entities parsing. + /// Mode for parsing entities in the message caption. See formatting options for more details. + /// A JSON-serialized list of special entities that appear in the caption, which can be specified instead of parse_mode. + /// A JSON-serialized object for an inline keyboard. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Task EditMessageCaptionAsync(this ITelegramBotClient client, string inlineMessageId, string? caption = null, string? parseMode = null, IEnumerable? captionEntities = null, InlineKeyboardMarkup? replyMarkup = null, CancellationToken cancellationToken = default) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new EditMessageCaptionArgs(inlineMessageId) + { + Caption = caption, + ParseMode = parseMode, + CaptionEntities = captionEntities, + ReplyMarkup = replyMarkup + }; + return client.CallMethodAsync(MethodNames.EditMessageCaption, args, cancellationToken); + } +} \ No newline at end of file diff --git a/src/library/Telegram.BotAPI/Updating messages/editMessageLiveLocation.cs b/src/library/Telegram.BotAPI/Updating messages/editMessageLiveLocation.cs new file mode 100644 index 00000000..93e7d52a --- /dev/null +++ b/src/library/Telegram.BotAPI/Updating messages/editMessageLiveLocation.cs @@ -0,0 +1,223 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System.Threading; +using System.Threading.Tasks; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.UpdatingMessages; + +public static partial class AvailableMethodsExtensions +{ + /// Use this method to edit live location messages sent by the bot or via the bot (for inline bots). A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. + /// BotClient + /// Parameters. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + /// Thrown when T is not Telegram.BotAPI.AvailableTypes.Message or bool. + /// or . On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned. + public static TReturn EditMessageLiveLocation(this ITelegramBotClient bot, EditMessageLiveLocationArgs args) + { + if (bot == default) + { + throw new ArgumentNullException(nameof(bot)); + } + if (args == default) + { + throw new ArgumentNullException(nameof(args)); + } + if (typeof(TReturn) != typeof(Message) && typeof(TReturn) != typeof(bool)) + { + throw new ArgumentException($"{nameof(TReturn)} must be a Telegram.BotAPI.AvailableTypes.Message or bool."); + } + return bot.CallMethod(MethodNames.EditMessageLiveLocation, args); + } + + /// Use this method to edit live location messages sent by the bot or via the bot (for inline bots). A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. + /// BotClient + /// Parameters. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + /// Thrown when T is not Telegram.BotAPI.AvailableTypes.Message or bool. + /// or . On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned. + public static Task EditMessageLiveLocationAsync(this ITelegramBotClient bot, EditMessageLiveLocationArgs args, CancellationToken cancellationToken = default) + { + if (bot == default) + { + throw new ArgumentNullException(nameof(bot)); + } + if (args == default) + { + throw new ArgumentNullException(nameof(args)); + } + if (typeof(TReturn) != typeof(Message) && typeof(TReturn) != typeof(bool)) + { + throw new ArgumentException($"{nameof(TReturn)} must be a Telegram.BotAPI.AvailableTypes.Message or bool."); + } + return bot.CallMethodAsync(MethodNames.EditMessageLiveLocation, args, cancellationToken: cancellationToken); + } + + /// + /// Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Required if inline_message_id is not specified. Identifier of the message to edit.] + /// Latitude of new location. + /// Longitude of new location. + /// The radius of uncertainty for the location, measured in meters; 0-1500. + /// Direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. + /// The maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. + /// A JSON-serialized object for a new inline keyboard. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Message EditMessageLiveLocation(this ITelegramBotClient client, long chatId, int messageId, float latitude, float longitude, float? horizontalAccuracy = null, ushort? heading = null, uint? proximityAlertRadius = null, InlineKeyboardMarkup? replyMarkup = null) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new EditMessageLiveLocationArgs(chatId, messageId, latitude, longitude) + { + HorizontalAccuracy = horizontalAccuracy, + Heading = heading, + ProximityAlertRadius = proximityAlertRadius, + ReplyMarkup = replyMarkup + }; + return client.CallMethod(MethodNames.EditMessageLiveLocation, args); + } + + /// + /// Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Required if inline_message_id is not specified. Identifier of the message to edit.] + /// Latitude of new location. + /// Longitude of new location. + /// The radius of uncertainty for the location, measured in meters; 0-1500. + /// Direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. + /// The maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. + /// A JSON-serialized object for a new inline keyboard. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Message EditMessageLiveLocation(this ITelegramBotClient client, string chatId, int messageId, float latitude, float longitude, float? horizontalAccuracy = null, ushort? heading = null, uint? proximityAlertRadius = null, InlineKeyboardMarkup? replyMarkup = null) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new EditMessageLiveLocationArgs(chatId, messageId, latitude, longitude) + { + HorizontalAccuracy = horizontalAccuracy, + Heading = heading, + ProximityAlertRadius = proximityAlertRadius, + ReplyMarkup = replyMarkup + }; + return client.CallMethod(MethodNames.EditMessageLiveLocation, args); + } + + /// + /// Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Latitude of new location. + /// Longitude of new location. + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Required if inline_message_id is not specified. Identifier of the message to edit. + /// The radius of uncertainty for the location, measured in meters; 0-1500. + /// Direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. + /// The maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. + /// A JSON-serialized object for a new inline keyboard. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Task EditMessageLiveLocationAsync(this ITelegramBotClient client, long chatId, int messageId, float latitude, float longitude, float? horizontalAccuracy = null, ushort? heading = null, uint? proximityAlertRadius = null, InlineKeyboardMarkup? replyMarkup = null, CancellationToken cancellationToken = default) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new EditMessageLiveLocationArgs(chatId, messageId, latitude, longitude) + { + HorizontalAccuracy = horizontalAccuracy, + Heading = heading, + ProximityAlertRadius = proximityAlertRadius, + ReplyMarkup = replyMarkup + }; + return client.CallMethodAsync(MethodNames.EditMessageLiveLocation, args, cancellationToken); + } + + /// + /// Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Latitude of new location. + /// Longitude of new location. + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Required if inline_message_id is not specified. Identifier of the message to edit. + /// The radius of uncertainty for the location, measured in meters; 0-1500. + /// Direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. + /// The maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. + /// A JSON-serialized object for a new inline keyboard. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Task EditMessageLiveLocationAsync(this ITelegramBotClient client, string chatId, int messageId, float latitude, float longitude, float? horizontalAccuracy = null, ushort? heading = null, uint? proximityAlertRadius = null, InlineKeyboardMarkup? replyMarkup = null, CancellationToken cancellationToken = default) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new EditMessageLiveLocationArgs(chatId, messageId, latitude, longitude) + { + HorizontalAccuracy = horizontalAccuracy, + Heading = heading, + ProximityAlertRadius = proximityAlertRadius, + ReplyMarkup = replyMarkup + }; + return client.CallMethodAsync(MethodNames.EditMessageLiveLocation, args, cancellationToken); + } + + /// + /// Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Latitude of new location. + /// Longitude of new location. + /// Required if chat_id and message_id are not specified. Identifier of the inline message. + /// The radius of uncertainty for the location, measured in meters; 0-1500. + /// Direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. + /// The maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. + /// A JSON-serialized object for a new inline keyboard. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static bool EditMessageLiveLocation(this ITelegramBotClient client, string inlineMessageId, float latitude, float longitude, float? horizontalAccuracy = null, ushort? heading = null, uint? proximityAlertRadius = null, InlineKeyboardMarkup? replyMarkup = null) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new EditMessageLiveLocationArgs(inlineMessageId, latitude, longitude) + { + HorizontalAccuracy = horizontalAccuracy, + Heading = heading, + ProximityAlertRadius = proximityAlertRadius, + ReplyMarkup = replyMarkup + }; + return client.CallMethod(MethodNames.EditMessageLiveLocation, args); + } + + /// + /// Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Latitude of new location. + /// Longitude of new location. + /// Required if chat_id and message_id are not specified. Identifier of the inline message. + /// The radius of uncertainty for the location, measured in meters; 0-1500. + /// Direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. + /// The maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. + /// A JSON-serialized object for a new inline keyboard. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Task EditMessageLiveLocationAsync(this ITelegramBotClient client, string inlineMessageId, float latitude, float longitude, float? horizontalAccuracy = null, ushort? heading = null, uint? proximityAlertRadius = null, InlineKeyboardMarkup? replyMarkup = null, CancellationToken cancellationToken = default) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new EditMessageLiveLocationArgs(inlineMessageId, latitude, longitude) + { + HorizontalAccuracy = horizontalAccuracy, + Heading = heading, + ProximityAlertRadius = proximityAlertRadius, + ReplyMarkup = replyMarkup + }; + return client.CallMethodAsync(MethodNames.EditMessageLiveLocation, args, cancellationToken); + } +} \ No newline at end of file diff --git a/src/library/Telegram.BotAPI/Updating messages/editMessageMedia.cs b/src/library/Telegram.BotAPI/Updating messages/editMessageMedia.cs new file mode 100644 index 00000000..61dfd894 --- /dev/null +++ b/src/library/Telegram.BotAPI/Updating messages/editMessageMedia.cs @@ -0,0 +1,181 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System.Threading; +using System.Threading.Tasks; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.UpdatingMessages; + +public static partial class UpdatingMessagesExtensions +{ + /// Use this method to edit animation, audio, document, photo, or video messages. If a message is a part of a message album, then it can be edited only to a photo or a video. Otherwise, message type can be changed arbitrarily. When inline message is edited, new file can't be uploaded. Use previously uploaded file via its file_id or specify a URL. + /// BotClient + /// Parameters. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + /// Thrown when T is not Telegram.BotAPI.AvailableTypes.Message or bool. + /// or . On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned. + public static TReturn EditMessageMedia(this ITelegramBotClient client, EditMessageMediaArgs args) + { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + if (args is null) + { + throw new ArgumentNullException(nameof(args)); + } + if (typeof(TReturn) != typeof(Message) && typeof(TReturn) != typeof(bool)) + { + throw new ArgumentException($"{nameof(TReturn)} must be a Telegram.BotAPI.AvailableTypes.Message or bool."); + } + return client.CallMethod(MethodNames.EditMessageMedia, args); + } + + /// Use this method to edit animation, audio, document, photo, or video messages. If a message is a part of a message album, then it can be edited only to a photo or a video. Otherwise, message type can be changed arbitrarily. When inline message is edited, new file can't be uploaded. Use previously uploaded file via its file_id or specify a URL. + /// BotClient + /// Parameters. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + /// Thrown when T is not Telegram.BotAPI.AvailableTypes.Message or bool. + /// or . On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned. + public static Task EditMessageMediaAsync(this ITelegramBotClient client, EditMessageMediaArgs args, CancellationToken cancellationToken = default) + { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + if (args is null) + { + throw new ArgumentNullException(nameof(args)); + } + if (typeof(TReturn) != typeof(Message) && typeof(TReturn) != typeof(bool)) + { + throw new ArgumentException($"{nameof(TReturn)} must be a Telegram.BotAPI.AvailableTypes.Message or bool."); + } + return client.CallMethodAsync(MethodNames.EditMessageMedia, args, cancellationToken: cancellationToken); + } + + /// + /// Use this method to edit animation, audio, document, photo, or video messages. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo or a video otherwise. When an inline message is edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify a URL. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// A JSON-serialized object for a new media content of the message. + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Required if inline_message_id is not specified. Identifier of the message to edit. + /// A JSON-serialized object for a new inline keyboard. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Message EditMessageMedia(this ITelegramBotClient client, long chatId, int messageId, InputMedia media, InlineKeyboardMarkup? replyMarkup = null) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new EditMessageMediaArgs(chatId, messageId, media) + { + ReplyMarkup = replyMarkup + }; + return client.CallMethod(MethodNames.EditMessageMedia, args); + } + + /// + /// Use this method to edit animation, audio, document, photo, or video messages. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo or a video otherwise. When an inline message is edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify a URL. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// A JSON-serialized object for a new media content of the message. + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Required if inline_message_id is not specified. Identifier of the message to edit. + /// A JSON-serialized object for a new inline keyboard. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Message EditMessageMedia(this ITelegramBotClient client, string chatId, int messageId, InputMedia media, InlineKeyboardMarkup? replyMarkup = null) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new EditMessageMediaArgs(chatId, messageId, media) + { + ReplyMarkup = replyMarkup + }; + return client.CallMethod(MethodNames.EditMessageMedia, args); + } + + /// + /// Use this method to edit animation, audio, document, photo, or video messages. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo or a video otherwise. When an inline message is edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify a URL. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// A JSON-serialized object for a new media content of the message. + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Required if inline_message_id is not specified. Identifier of the message to edit. + /// A JSON-serialized object for a new inline keyboard. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static async Task EditMessageMediaAsync(this ITelegramBotClient client, long chatId, int messageId, InputMedia media, InlineKeyboardMarkup? replyMarkup = null, CancellationToken cancellationToken = default) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new EditMessageMediaArgs(chatId, messageId, media) + { + ReplyMarkup = replyMarkup + }; + return await client.CallMethodAsync(MethodNames.EditMessageMedia, args, cancellationToken).ConfigureAwait(false); + } + + /// + /// Use this method to edit animation, audio, document, photo, or video messages. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo or a video otherwise. When an inline message is edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify a URL. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// A JSON-serialized object for a new media content of the message. + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Required if inline_message_id is not specified. Identifier of the message to edit. + /// A JSON-serialized object for a new inline keyboard. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static async Task EditMessageMediaAsync(this ITelegramBotClient client, string chatId, int messageId, InputMedia media, InlineKeyboardMarkup? replyMarkup = null, CancellationToken cancellationToken = default) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new EditMessageMediaArgs(chatId, messageId, media) + { + ReplyMarkup = replyMarkup + }; + return await client.CallMethodAsync(MethodNames.EditMessageMedia, args, cancellationToken).ConfigureAwait(false); + } + + /// + /// Use this method to edit animation, audio, document, photo, or video messages. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo or a video otherwise. When an inline message is edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify a URL. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// A JSON-serialized object for a new media content of the message. + /// Required if chat_id and message_id are not specified. Identifier of the inline message. + /// A JSON-serialized object for a new inline keyboard. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static bool EditMessageMedia(this ITelegramBotClient client, string inlineMessageId, InputMedia media, InlineKeyboardMarkup? replyMarkup = null) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new EditMessageMediaArgs(inlineMessageId, media) + { + ReplyMarkup = replyMarkup + }; + return client.CallMethod(MethodNames.EditMessageMedia, args); + } + + /// + /// Use this method to edit animation, audio, document, photo, or video messages. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo or a video otherwise. When an inline message is edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify a URL. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// A JSON-serialized object for a new media content of the message. + /// Required if chat_id and message_id are not specified. Identifier of the inline message. + /// A JSON-serialized object for a new inline keyboard. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Task EditMessageMediaAsync(this ITelegramBotClient client, string inlineMessageId, InputMedia media, InlineKeyboardMarkup? replyMarkup = null, CancellationToken cancellationToken = default) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new EditMessageMediaArgs(inlineMessageId, media) + { + ReplyMarkup = replyMarkup + }; + return client.CallMethodAsync(MethodNames.EditMessageMedia, args, cancellationToken); + } +} \ No newline at end of file diff --git a/src/library/Telegram.BotAPI/Updating messages/editMessageReplyMarkup.cs b/src/library/Telegram.BotAPI/Updating messages/editMessageReplyMarkup.cs new file mode 100644 index 00000000..e8e34481 --- /dev/null +++ b/src/library/Telegram.BotAPI/Updating messages/editMessageReplyMarkup.cs @@ -0,0 +1,175 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System.Threading; +using System.Threading.Tasks; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.UpdatingMessages; + +public static partial class UpdatingMessagesExtensions +{ + /// Use this method to edit only the reply markup of messages. + /// BotClient + /// Parameters. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + /// Thrown when T is not Telegram.BotAPI.AvailableTypes.Message or bool. + /// or . On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. + public static TReturn EditMessageReplyMarkup(this ITelegramBotClient client, EditMessageReplyMarkupArgs args) + { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + if (args == default) + { + throw new ArgumentNullException(nameof(args)); + } + if (typeof(TReturn) != typeof(Message) && typeof(TReturn) != typeof(bool)) + { + throw new ArgumentException($"{nameof(TReturn)} must be a Telegram.BotAPI.AvailableTypes.Message or bool."); + } + return client.CallMethod(MethodNames.EditMessageReplyMarkup, args); + } + + /// Use this method to edit only the reply markup of messages. + /// BotClient + /// Parameters. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + /// Thrown when T is not Telegram.BotAPI.AvailableTypes.Message or bool. + /// or . On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. + public static async Task EditMessageReplyMarkupAsync(this ITelegramBotClient client, EditMessageReplyMarkupArgs args, CancellationToken cancellationToken = default) + { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + if (args == default) + { + throw new ArgumentNullException(nameof(args)); + } + if (typeof(TReturn) != typeof(Message) && typeof(TReturn) != typeof(bool)) + { + throw new ArgumentException($"{nameof(TReturn)} must be a Telegram.BotAPI.AvailableTypes.Message or bool."); + } + return await client.CallMethodAsync(MethodNames.EditMessageReplyMarkup, args, cancellationToken: cancellationToken).ConfigureAwait(false); + } + + /// + /// Use this method to edit only the reply markup of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Required if inline_message_id is not specified. Identifier of the message to edit. + /// A JSON-serialized object for an inline keyboard. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Message EditMessageReplyMarkup(this ITelegramBotClient client, long chatId, int messageId, InlineKeyboardMarkup? replyMarkup = null) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new EditMessageReplyMarkupArgs(chatId, messageId) + { + ReplyMarkup = replyMarkup + }; + return client.CallMethod(MethodNames.EditMessageReplyMarkup, args); + } + + /// + /// Use this method to edit only the reply markup of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Required if inline_message_id is not specified. Identifier of the message to edit. + /// A JSON-serialized object for an inline keyboard. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Message EditMessageReplyMarkup(this ITelegramBotClient client, string chatId, int messageId, InlineKeyboardMarkup? replyMarkup = null) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new EditMessageReplyMarkupArgs(chatId, messageId) + { + ReplyMarkup = replyMarkup + }; + return client.CallMethod(MethodNames.EditMessageReplyMarkup, args); + } + + /// + /// Use this method to edit only the reply markup of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Required if inline_message_id is not specified. Identifier of the message to edit. + /// A JSON-serialized object for an inline keyboard. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Task EditMessageReplyMarkupAsync(this ITelegramBotClient client, long chatId, int messageId, InlineKeyboardMarkup? replyMarkup = null, CancellationToken cancellationToken = default) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new EditMessageReplyMarkupArgs(chatId, messageId) + { + ReplyMarkup = replyMarkup + }; + return client.CallMethodAsync(MethodNames.EditMessageReplyMarkup, args, cancellationToken); + } + + /// + /// Use this method to edit only the reply markup of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Required if inline_message_id is not specified. Identifier of the message to edit. + /// A JSON-serialized object for an inline keyboard. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static async Task EditMessageReplyMarkupAsync(this ITelegramBotClient client, string chatId, int messageId, InlineKeyboardMarkup? replyMarkup = null, CancellationToken cancellationToken = default) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new EditMessageReplyMarkupArgs(chatId, messageId) + { + ReplyMarkup = replyMarkup + }; + return await client.CallMethodAsync(MethodNames.EditMessageReplyMarkup, args, cancellationToken).ConfigureAwait(false); + } + + /// + /// Use this method to edit only the reply markup of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Required if chat_id and message_id are not specified. Identifier of the inline message. + /// A JSON-serialized object for an inline keyboard. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static bool EditMessageReplyMarkup(this ITelegramBotClient client, string inlineMessageId, InlineKeyboardMarkup? replyMarkup = null) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new EditMessageReplyMarkupArgs(inlineMessageId) + { + ReplyMarkup = replyMarkup + }; + return client.CallMethod(MethodNames.EditMessageReplyMarkup, args); + } + + /// + /// Use this method to edit only the reply markup of messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Required if chat_id and message_id are not specified. Identifier of the inline message. + /// A JSON-serialized object for an inline keyboard. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Task EditMessageReplyMarkupAsync(this ITelegramBotClient client, string inlineMessageId, InlineKeyboardMarkup? replyMarkup = null, CancellationToken cancellationToken = default) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new EditMessageReplyMarkupArgs(inlineMessageId) + { + ReplyMarkup = replyMarkup + }; + return client.CallMethodAsync(MethodNames.EditMessageReplyMarkup, args, cancellationToken); + } +} diff --git a/src/library/Telegram.BotAPI/Updating messages/editMessageText.cs b/src/library/Telegram.BotAPI/Updating messages/editMessageText.cs new file mode 100644 index 00000000..8e53f878 --- /dev/null +++ b/src/library/Telegram.BotAPI/Updating messages/editMessageText.cs @@ -0,0 +1,225 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using System.Threading; +using System.Threading.Tasks; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.UpdatingMessages; + +public static partial class UpdatingMessagesExtensions +{ + /// Use this method to edit text and game messages. + /// Return type. or bool + /// The bot client + /// Parameters. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + /// Thrown when T is not Telegram.BotAPI.AvailableTypes.Message or bool. + /// or . On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. + public static TReturn EditMessageText(this ITelegramBotClient client, EditMessageTextArgs args) + { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + if (args is null) + { + throw new ArgumentNullException(nameof(args)); + } + if (typeof(TReturn) != typeof(Message) && typeof(TReturn) != typeof(bool)) + { + throw new ArgumentException($"{nameof(TReturn)} must be a Telegram.BotAPI.AvailableTypes.Message or bool."); + } + return client.CallMethod(MethodNames.EditMessageText, args); + } + + /// Use this method to edit text and game messages. + /// Return type. or bool + /// The bot client + /// Parameters. + /// + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + /// Thrown when T is not Telegram.BotAPI.AvailableTypes.Message or bool. + /// or . On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned. + public static Task EditMessageTextAsync(this ITelegramBotClient client, EditMessageTextArgs args, CancellationToken cancellationToken = default) + { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + if (args is null) + { + throw new ArgumentNullException(nameof(args)); + } + if (typeof(TReturn) != typeof(Message) && typeof(TReturn) != typeof(bool)) + { + throw new ArgumentException($"{nameof(TReturn)} must be a Telegram.BotAPI.AvailableTypes.Message or bool."); + } + return client.CallMethodAsync(MethodNames.EditMessageText, args, cancellationToken); + } + + /// + /// Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// New text of the message, 1-4096 characters after entities parsing. + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Required if inline_message_id is not specified. Identifier of the message to edit. + /// Mode for parsing entities in the message text. See formatting options for more details. + /// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode. + /// Link preview generation options for the message. + /// A JSON-serialized object for an inline keyboard. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Message EditMessageText(this ITelegramBotClient client, long chatId, int messageId, string text, string? parseMode = null, IEnumerable? entities = null, LinkPreviewOptions? linkPreviewOptions = null, InlineKeyboardMarkup? replyMarkup = null) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new EditMessageTextArgs(chatId, messageId, text) + { + ParseMode = parseMode, + Entities = entities, + LinkPreviewOptions = linkPreviewOptions, + ReplyMarkup = replyMarkup + }; + return client.CallMethod(MethodNames.EditMessageText, args); + } + + /// + /// Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// New text of the message, 1-4096 characters after entities parsing. + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Required if inline_message_id is not specified. Identifier of the message to edit. + /// Mode for parsing entities in the message text. See formatting options for more details. + /// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode. + /// Link preview generation options for the message. + /// A JSON-serialized object for an inline keyboard. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Message EditMessageText(this ITelegramBotClient client, string chatId, int messageId, string text, string? parseMode = null, IEnumerable? entities = null, LinkPreviewOptions? linkPreviewOptions = null, InlineKeyboardMarkup? replyMarkup = null) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new EditMessageTextArgs(chatId, messageId, text) + { + ParseMode = parseMode, + Entities = entities, + LinkPreviewOptions = linkPreviewOptions, + ReplyMarkup = replyMarkup + }; + return client.CallMethod(MethodNames.EditMessageText, args); + } + + /// + /// Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// New text of the message, 1-4096 characters after entities parsing. + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Required if inline_message_id is not specified. Identifier of the message to edit. + /// Mode for parsing entities in the message text. See formatting options for more details. + /// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode. + /// Link preview generation options for the message. + /// A JSON-serialized object for an inline keyboard. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Task EditMessageTextAsync(this ITelegramBotClient client, long chatId, int messageId, string text, string? parseMode = null, IEnumerable? entities = null, LinkPreviewOptions? linkPreviewOptions = null, InlineKeyboardMarkup? replyMarkup = null, CancellationToken cancellationToken = default) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new EditMessageTextArgs(chatId, messageId, text) + { + ParseMode = parseMode, + Entities = entities, + LinkPreviewOptions = linkPreviewOptions, + ReplyMarkup = replyMarkup + }; + return client.CallMethodAsync(MethodNames.EditMessageText, args, cancellationToken); + } + + /// + /// Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// New text of the message, 1-4096 characters after entities parsing. + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Required if inline_message_id is not specified. Identifier of the message to edit. + /// Mode for parsing entities in the message text. See formatting options for more details. + /// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode. + /// Link preview generation options for the message. + /// A JSON-serialized object for an inline keyboard. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Task EditMessageTextAsync(this ITelegramBotClient client, string chatId, int messageId, string text, string? parseMode = null, IEnumerable? entities = null, LinkPreviewOptions? linkPreviewOptions = null, InlineKeyboardMarkup? replyMarkup = null, CancellationToken cancellationToken = default) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new EditMessageTextArgs(chatId, messageId, text) + { + ParseMode = parseMode, + Entities = entities, + LinkPreviewOptions = linkPreviewOptions, + ReplyMarkup = replyMarkup + }; + return client.CallMethodAsync(MethodNames.EditMessageText, args, cancellationToken); + } + + /// + /// Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Required if chat_id and message_id are not specified. Identifier of the inline message. + /// New text of the message, 1-4096 characters after entities parsing. + /// Mode for parsing entities in the message text. See formatting options for more details. + /// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode. + /// Link preview generation options for the message. + /// A JSON-serialized object for an inline keyboard. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static bool EditMessageText(this ITelegramBotClient client, string inlineMessageId, string text, string? parseMode = null, IEnumerable? entities = null, LinkPreviewOptions? linkPreviewOptions = null, InlineKeyboardMarkup? replyMarkup = null) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new EditMessageTextArgs(inlineMessageId, text) + { + ParseMode = parseMode, + Entities = entities, + LinkPreviewOptions = linkPreviewOptions, + ReplyMarkup = replyMarkup + }; + return client.CallMethod(MethodNames.EditMessageText, args); + } + + /// + /// Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// New text of the message, 1-4096 characters after entities parsing. + /// Required if chat_id and message_id are not specified. Identifier of the inline message. + /// Mode for parsing entities in the message text. See formatting options for more details. + /// A JSON-serialized list of special entities that appear in message text, which can be specified instead of parse_mode. + /// Link preview generation options for the message. + /// A JSON-serialized object for an inline keyboard. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Task EditMessageTextAsync(this ITelegramBotClient client, string inlineMessageId, string text, string? parseMode = null, IEnumerable? entities = null, LinkPreviewOptions? linkPreviewOptions = null, InlineKeyboardMarkup? replyMarkup = null, CancellationToken cancellationToken = default) + { + if (client is null) + throw new ArgumentNullException(nameof(client)); + var args = new EditMessageTextArgs(inlineMessageId, text) + { + ParseMode = parseMode, + Entities = entities, + LinkPreviewOptions = linkPreviewOptions, + ReplyMarkup = replyMarkup + }; + return client.CallMethodAsync(MethodNames.EditMessageText, args, cancellationToken); + } +} diff --git a/src/library/Telegram.BotAPI/Updating messages/stopMessageLiveLocation.cs b/src/library/Telegram.BotAPI/Updating messages/stopMessageLiveLocation.cs new file mode 100644 index 00000000..0320e1c0 --- /dev/null +++ b/src/library/Telegram.BotAPI/Updating messages/stopMessageLiveLocation.cs @@ -0,0 +1,181 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +using Newtonsoft.Json.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Telegram.BotAPI.AvailableTypes; + +namespace Telegram.BotAPI.UpdatingMessages; + +public static partial class AvailableMethodsExtensions +{ + /// + /// Use this method to stop updating a live location message sent by the bot or via the bot (for inline bots) before live_period expires. + /// + /// BotClient + /// Parameters. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + /// Thrown when T is not Telegram.BotAPI.AvailableTypes.Message or bool. + /// or . On success, if the message was sent by the bot, the sent Message is returned, otherwise True is returned. + public static TReturn StopMessageLiveLocation(this ITelegramBotClient client, StopMessageLiveLocationArgs args) + { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + if (args == default) + { + throw new ArgumentNullException(nameof(args)); + } + if (typeof(TReturn) != typeof(Message) && typeof(TReturn) != typeof(bool)) + { + throw new ArgumentException($"{nameof(TReturn)} must be a Telegram.BotAPI.AvailableTypes.Message or bool."); + } + return client.CallMethod(MethodNames.StopMessageLiveLocation, args); + } + + /// + /// Use this method to stop updating a live location message sent by the bot or via the bot (for inline bots) before live_period expires. + /// + /// BotClient + /// Parameters. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + /// Thrown when T is not Telegram.BotAPI.AvailableTypes.Message or bool. + /// or . On success, if the message was sent by the bot, the sent Message is returned, otherwise True is returned. + public static async Task StopMessageLiveLocationAsync(this ITelegramBotClient client, StopMessageLiveLocationArgs args, CancellationToken cancellationToken = default) + { + if (client is null) + { + throw new ArgumentNullException(nameof(client)); + } + if (args == default) + { + throw new ArgumentNullException(nameof(args)); + } + if (typeof(TReturn) != typeof(Message) && typeof(TReturn) != typeof(bool)) + { + throw new ArgumentException($"{nameof(TReturn)} must be a Telegram.BotAPI.AvailableTypes.Message or bool."); + } + return await client.CallMethodAsync(MethodNames.StopMessageLiveLocation, args, cancellationToken: cancellationToken).ConfigureAwait(false); + } + + /// + /// Use this method to stop updating a live location message before live_period expires. On success, if the message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Required if inline_message_id is not specified. Identifier of the message with live location to stop. + /// A JSON-serialized object for an inline keyboard. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Message StopMessageLiveLocation(this ITelegramBotClient client, long chatId, int messageId, InlineKeyboardMarkup? replyMarkup = null) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new StopMessageLiveLocationArgs(chatId, messageId) + { + ReplyMarkup = replyMarkup + }; + return client.CallMethod(MethodNames.StopMessageLiveLocation, args); + } + + /// + /// Use this method to stop updating a live location message before live_period expires. On success, if the message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Required if inline_message_id is not specified. Identifier of the message with live location to stop. + /// A JSON-serialized object for an inline keyboard. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Message StopMessageLiveLocation(this ITelegramBotClient client, string chatId, int messageId, InlineKeyboardMarkup? replyMarkup = null) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new StopMessageLiveLocationArgs(chatId, messageId) + { + ReplyMarkup = replyMarkup + }; + return client.CallMethod(MethodNames.StopMessageLiveLocation, args); + } + + /// + /// Use this method to stop updating a live location message before live_period expires. On success, if the message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Required if inline_message_id is not specified. Identifier of the message with live location to stop. + /// A JSON-serialized object for an inline keyboard. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Task StopMessageLiveLocationAsync(this ITelegramBotClient client, long chatId, int messageId, InlineKeyboardMarkup? replyMarkup = null, CancellationToken cancellationToken = default) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new StopMessageLiveLocationArgs(chatId, messageId) + { + ReplyMarkup = replyMarkup + }; + return client.CallMethodAsync(MethodNames.StopMessageLiveLocation, args, cancellationToken); + } + + /// + /// Use this method to stop updating a live location message before live_period expires. On success, if the message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername). + /// Required if inline_message_id is not specified. Identifier of the message with live location to stop. + /// A JSON-serialized object for an inline keyboard. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static async Task StopMessageLiveLocationAsync(this ITelegramBotClient client, string chatId, int messageId, InlineKeyboardMarkup? replyMarkup = null, CancellationToken cancellationToken = default) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new StopMessageLiveLocationArgs(chatId, messageId) + { + ReplyMarkup = replyMarkup + }; + return await client.CallMethodAsync(MethodNames.StopMessageLiveLocation, args, cancellationToken).ConfigureAwait(false); + } + + /// + /// Use this method to stop updating a live location message before live_period expires. On success, if the message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Required if chat_id and message_id are not specified. Identifier of the inline message. + /// A JSON-serialized object for an inline keyboard. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static bool StopMessageLiveLocation(this ITelegramBotClient client, string inlineMessageId, InlineKeyboardMarkup? replyMarkup = null) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new StopMessageLiveLocationArgs(inlineMessageId) + { + ReplyMarkup = replyMarkup + }; + return client.CallMethod(MethodNames.StopMessageLiveLocation, args); + } + + /// + /// Use this method to stop updating a live location message before live_period expires. On success, if the message is not an inline message, the edited Message is returned, otherwise True is returned. + /// + /// The bot client. + /// Required if chat_id and message_id are not specified. Identifier of the inline message. + /// A JSON-serialized object for an inline keyboard. + /// The cancellation token to cancel operation. + /// Thrown when a request to Telegram Bot API got an error response. + /// Thrown when a required parameter is null. + public static Task StopMessageLiveLocationAsync(this ITelegramBotClient client, string inlineMessageId, InlineKeyboardMarkup? replyMarkup = null, CancellationToken cancellationToken = default) + { + if (client is null) { throw new ArgumentNullException(nameof(client)); } + var args = new StopMessageLiveLocationArgs(inlineMessageId) + { + ReplyMarkup = replyMarkup + }; + return client.CallMethodAsync(MethodNames.StopMessageLiveLocation, args, cancellationToken); + } +} diff --git a/src/Telegram.BotAPI/Updating messages/stopPoll.cs b/src/library/Telegram.BotAPI/Updating messages/stopPoll.cs similarity index 82% rename from src/Telegram.BotAPI/Updating messages/stopPoll.cs rename to src/library/Telegram.BotAPI/Updating messages/stopPoll.cs index f3080f7f..17d3a6f2 100644 --- a/src/Telegram.BotAPI/Updating messages/stopPoll.cs +++ b/src/library/Telegram.BotAPI/Updating messages/stopPoll.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.IO; @@ -18,7 +18,7 @@ public static partial class UpdatingMessagesExtensions /// Identifier of the original message with the poll /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Poll StopPoll(this BotClient? bot, long chatId, int messageId) + public static Poll StopPoll(this ITelegramBotClient bot, long chatId, int messageId) { if (bot == default) { @@ -33,7 +33,7 @@ public static Poll StopPoll(this BotClient? bot, long chatId, int messageId) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.StopPoll, stream); + return bot.CallMethod(MethodNames.StopPoll, stream); } /// Use this method to stop a poll which was sent by the bot. On success, the stopped Poll with the final results is returned. @@ -42,7 +42,7 @@ public static Poll StopPoll(this BotClient? bot, long chatId, int messageId) /// Identifier of the original message with the poll /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Poll StopPoll(this BotClient? bot, string chatId, int messageId) + public static Poll StopPoll(this ITelegramBotClient bot, string chatId, int messageId) { if (bot == default) { @@ -57,7 +57,7 @@ public static Poll StopPoll(this BotClient? bot, string chatId, int messageId) json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); - return bot.RPC(MethodNames.StopPoll, stream); + return bot.CallMethod(MethodNames.StopPoll, stream); } /// Use this method to stop a poll which was sent by the bot. On success, the stopped Poll with the final results is returned. /// BotClient @@ -66,7 +66,7 @@ public static Poll StopPoll(this BotClient? bot, string chatId, int messageId) /// A object for a new message inline keyboard. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Poll StopPoll(this BotClient? bot, long chatId, int messageId, InlineKeyboardMarkup replyMarkup) + public static Poll StopPoll(this ITelegramBotClient bot, long chatId, int messageId, InlineKeyboardMarkup replyMarkup) { if (bot == default) { @@ -84,7 +84,7 @@ public static Poll StopPoll(this BotClient? bot, long chatId, int messageId, Inl MessageId = messageId, ReplyMarkup = replyMarkup }; - return bot.RPC(MethodNames.StopPoll, args); + return bot.CallMethod(MethodNames.StopPoll, args); } /// Use this method to stop a poll which was sent by the bot. On success, the stopped Poll with the final results is returned. /// BotClient @@ -93,7 +93,7 @@ public static Poll StopPoll(this BotClient? bot, long chatId, int messageId, Inl /// A object for a new message inline keyboard. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Poll StopPoll(this BotClient? bot, string chatId, int messageId, InlineKeyboardMarkup replyMarkup) + public static Poll StopPoll(this ITelegramBotClient bot, string chatId, int messageId, InlineKeyboardMarkup replyMarkup) { if (bot == default) { @@ -111,7 +111,7 @@ public static Poll StopPoll(this BotClient? bot, string chatId, int messageId, I MessageId = messageId, ReplyMarkup = replyMarkup }; - return bot.RPC(MethodNames.StopPoll, args); + return bot.CallMethod(MethodNames.StopPoll, args); } /// Use this method to stop a poll which was sent by the bot. On success, the stopped Poll with the final results is returned. @@ -121,7 +121,7 @@ public static Poll StopPoll(this BotClient? bot, string chatId, int messageId, I /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task StopPollAsync(this BotClient? bot, long chatId, int messageId, [Optional] CancellationToken cancellationToken) + public static async Task StopPollAsync(this ITelegramBotClient bot, long chatId, int messageId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -137,7 +137,7 @@ public static async Task StopPollAsync(this BotClient? bot, long chatId, i await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.StopPoll, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.StopPoll, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to stop a poll which was sent by the bot. On success, the stopped Poll with the final results is returned. @@ -147,7 +147,7 @@ public static async Task StopPollAsync(this BotClient? bot, long chatId, i /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task StopPollAsync(this BotClient? bot, string chatId, int messageId, [Optional] CancellationToken cancellationToken) + public static async Task StopPollAsync(this ITelegramBotClient bot, string chatId, int messageId, CancellationToken cancellationToken = default) { if (bot == default) { @@ -163,7 +163,7 @@ public static async Task StopPollAsync(this BotClient? bot, string chatId, await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); - return await bot.RPCA(MethodNames.StopPoll, stream, cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.StopPoll, stream, cancellationToken).ConfigureAwait(false); } /// Use this method to stop a poll which was sent by the bot. On success, the stopped Poll with the final results is returned. @@ -174,7 +174,7 @@ public static async Task StopPollAsync(this BotClient? bot, string chatId, /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task StopPollAsync(this BotClient? bot, long chatId, int messageId, [Optional] InlineKeyboardMarkup replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task StopPollAsync(this ITelegramBotClient bot, long chatId, int messageId, [Optional] InlineKeyboardMarkup replyMarkup, CancellationToken cancellationToken = default) { if (bot == default) { @@ -192,7 +192,7 @@ public static async Task StopPollAsync(this BotClient? bot, long chatId, i MessageId = messageId, ReplyMarkup = replyMarkup }; - return await bot.RPCA(MethodNames.StopPoll, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.StopPoll, args, cancellationToken: cancellationToken).ConfigureAwait(false); } /// Use this method to stop a poll which was sent by the bot. On success, the stopped Poll with the final results is returned. /// BotClient @@ -202,7 +202,7 @@ public static async Task StopPollAsync(this BotClient? bot, long chatId, i /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task StopPollAsync(this BotClient? bot, string chatId, int messageId, InlineKeyboardMarkup replyMarkup, [Optional] CancellationToken cancellationToken) + public static async Task StopPollAsync(this ITelegramBotClient bot, string chatId, int messageId, InlineKeyboardMarkup replyMarkup, CancellationToken cancellationToken = default) { if (bot == default) { @@ -220,14 +220,14 @@ public static async Task StopPollAsync(this BotClient? bot, string chatId, MessageId = messageId, ReplyMarkup = replyMarkup }; - return await bot.RPCA(MethodNames.StopPoll, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.StopPoll, args, cancellationToken: cancellationToken).ConfigureAwait(false); } /// Use this method to stop a poll which was sent by the bot. On success, the stopped Poll with the final results is returned. /// BotClient /// Parameters. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static Poll StopPoll(this BotClient? bot, StopPollArgs args) + public static Poll StopPoll(this ITelegramBotClient bot, StopPollArgs args) { if (bot == default) { @@ -239,7 +239,7 @@ public static Poll StopPoll(this BotClient? bot, StopPollArgs args) throw new ArgumentNullException(nameof(args)); } - return bot.RPC(MethodNames.StopPoll, args); + return bot.CallMethod(MethodNames.StopPoll, args); } /// Use this method to stop a poll which was sent by the bot. On success, the stopped Poll with the final results is returned. /// BotClient @@ -247,7 +247,7 @@ public static Poll StopPoll(this BotClient? bot, StopPollArgs args) /// The cancellation token to cancel operation. /// Thrown when a request to Telegram Bot API got an error response. /// Thrown when a required parameter is null. - public static async Task StopPollAsync(this BotClient? bot, StopPollArgs args, [Optional] CancellationToken cancellationToken) + public static async Task StopPollAsync(this ITelegramBotClient bot, StopPollArgs args, CancellationToken cancellationToken = default) { if (bot == default) { @@ -259,6 +259,6 @@ public static async Task StopPollAsync(this BotClient? bot, StopPollArgs a throw new ArgumentNullException(nameof(args)); } - return await bot.RPCA(MethodNames.StopPoll, args, cancellationToken: cancellationToken).ConfigureAwait(false); + return await bot.CallMethodAsync(MethodNames.StopPoll, args, cancellationToken: cancellationToken).ConfigureAwait(false); } } diff --git a/src/Telegram.BotAPI/Usings.cs b/src/library/Telegram.BotAPI/Usings.cs similarity index 85% rename from src/Telegram.BotAPI/Usings.cs rename to src/library/Telegram.BotAPI/Usings.cs index ea216d4e..5b0fb7c6 100644 --- a/src/Telegram.BotAPI/Usings.cs +++ b/src/library/Telegram.BotAPI/Usings.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. global using System; diff --git a/src/Telegram.BotAPI/packicon.png b/src/library/Telegram.BotAPI/packicon.png similarity index 100% rename from src/Telegram.BotAPI/packicon.png rename to src/library/Telegram.BotAPI/packicon.png diff --git a/src/Telegram.BotAPI.Tests/Args.cs b/src/tests/Telegram.BotAPI.Tests/Args.cs similarity index 95% rename from src/Telegram.BotAPI.Tests/Args.cs rename to src/tests/Telegram.BotAPI.Tests/Args.cs index 6ea0744b..dae2ecb4 100644 --- a/src/Telegram.BotAPI.Tests/Args.cs +++ b/src/tests/Telegram.BotAPI.Tests/Args.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. namespace Telegram.BotAPI.Tests; diff --git a/src/Telegram.BotAPI.Tests/ConverterTests.cs b/src/tests/Telegram.BotAPI.Tests/ConverterTests.cs similarity index 93% rename from src/Telegram.BotAPI.Tests/ConverterTests.cs rename to src/tests/Telegram.BotAPI.Tests/ConverterTests.cs index 5df8325b..401b1814 100644 --- a/src/Telegram.BotAPI.Tests/ConverterTests.cs +++ b/src/tests/Telegram.BotAPI.Tests/ConverterTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Text.Json; @@ -8,6 +8,7 @@ using KB = Telegram.BotAPI.AvailableTypes.KeyboardButton; using RKM = Telegram.BotAPI.AvailableTypes.ReplyKeyboardMarkup; using RKR = Telegram.BotAPI.AvailableTypes.ReplyKeyboardRemove; +using IBB = Telegram.BotAPI.InlineButtonBuilder; namespace Telegram.BotAPI.Tests; @@ -158,12 +159,12 @@ public void SerializeSendMessageArgsWithReplyMarkup(long chatId, string text) { new IKB[] { - IKB.SetCallbackData("Your text", text), - IKB.SetCallbackData("Your chatId", chatId.ToString()) + IBB.SetCallbackData("Your text", text), + IBB.SetCallbackData("Your chatId", chatId.ToString()) }, new IKB[] { - IKB.SetCallbackData("Your text", text) + IBB.SetCallbackData("Your text", text) } } } @@ -236,12 +237,12 @@ public void SerializeSendPhotoArgsWithReplyMarkup(long chatId, string photo) { new IKB[] { - IKB.SetCallbackData("Your text", photo), - IKB.SetCallbackData("Your chatId", chatId.ToString()) + IBB.SetCallbackData("Your text", photo), + IBB.SetCallbackData("Your chatId", chatId.ToString()) }, new IKB[] { - IKB.SetCallbackData("Your text", photo) + IBB.SetCallbackData("Your text", photo) } } } @@ -310,12 +311,12 @@ public void SerializeAndDeserializeInlineKeyboardMarkup() { new IKB[] { - IKB.SetCallbackData("Your text", "example"), - IKB.SetCallbackData("Your chatId", "example") + IBB.SetCallbackData("Your text", "example"), + IBB.SetCallbackData("Your chatId", "example") }, new IKB[] { -IKB.SetCallbackData("Your text", "example") +IBB.SetCallbackData("Your text", "example") } } }; diff --git a/src/tests/Telegram.BotAPI.Tests/MethodTests.cs b/src/tests/Telegram.BotAPI.Tests/MethodTests.cs new file mode 100644 index 00000000..cf7ed3d2 --- /dev/null +++ b/src/tests/Telegram.BotAPI.Tests/MethodTests.cs @@ -0,0 +1,16 @@ +// Copyright (c) 2024 Quetzal Rivera. +// Licensed under the MIT License, See LICENCE in the project root for license information. + +namespace Telegram.BotAPI.Tests; + +public sealed class MethodTests +{ + [Fact] + public void SendMessageWithNullClient() + { + Assert.Throws(() => + { + AvailableMethodsExtensions.SendMessage(null, 0, "Hello World"); + }); + } +} diff --git a/src/Telegram.BotAPI.Tests/Serialization.cs b/src/tests/Telegram.BotAPI.Tests/Serialization.cs similarity index 76% rename from src/Telegram.BotAPI.Tests/Serialization.cs rename to src/tests/Telegram.BotAPI.Tests/Serialization.cs index 15ad6c00..35852c6c 100644 --- a/src/Telegram.BotAPI.Tests/Serialization.cs +++ b/src/tests/Telegram.BotAPI.Tests/Serialization.cs @@ -1,14 +1,15 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. using System.Text.Json; using System.Text.Json.Serialization; +using Telegram.BotAPI.UpdatingMessages; namespace Telegram.BotAPI.Tests; public sealed class Serialization { - private static JsonSerializerOptions options = new() + private static readonly JsonSerializerOptions options = new() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }; @@ -20,10 +21,7 @@ public sealed class Serialization [Fact] public void SerializeAnyObject() { - var obj = new EditMessageLiveLocationArgs(0, 0) - { - ChatId = 1 - }; + var obj = new EditMessageLiveLocationArgs(1, 0, 0, 0); var rawText = JsonSerializer.Serialize(obj, options); this._outputHelper.WriteLine(rawText); @@ -32,7 +30,7 @@ public void SerializeAnyObject() [Fact] public void SerializeInlineButton() { - var button = InlineKeyboardButton.SetCallbackData("Callback Button", "callback query"); + var button = InlineButtonBuilder.SetCallbackData("Callback Button", "callback query"); var rawText = JsonSerializer.Serialize(button, options); this._outputHelper.WriteLine(rawText); diff --git a/src/Telegram.BotAPI.Tests/Telegram.BotAPI.Tests.csproj b/src/tests/Telegram.BotAPI.Tests/Telegram.BotAPI.Tests.csproj similarity index 80% rename from src/Telegram.BotAPI.Tests/Telegram.BotAPI.Tests.csproj rename to src/tests/Telegram.BotAPI.Tests/Telegram.BotAPI.Tests.csproj index 1fc0cb08..adc61a96 100644 --- a/src/Telegram.BotAPI.Tests/Telegram.BotAPI.Tests.csproj +++ b/src/tests/Telegram.BotAPI.Tests/Telegram.BotAPI.Tests.csproj @@ -20,8 +20,8 @@ - - + + diff --git a/src/Telegram.BotAPI.Tests/Usings.cs b/src/tests/Telegram.BotAPI.Tests/Usings.cs similarity index 89% rename from src/Telegram.BotAPI.Tests/Usings.cs rename to src/tests/Telegram.BotAPI.Tests/Usings.cs index 7eb6f1e3..66b7f980 100644 --- a/src/Telegram.BotAPI.Tests/Usings.cs +++ b/src/tests/Telegram.BotAPI.Tests/Usings.cs @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Quetzal Rivera. +// Copyright (c) 2024 Quetzal Rivera. // Licensed under the MIT License, See LICENCE in the project root for license information. global using System;