Example #1
0
        /// <summary>Use this method to forward messages of any kind. Service messages can't be forwarded. On success, the sent Message is returned.</summary>
        /// <param name="api">The bot client.</param>
        /// <param name="chatId">Unique identifier for the target chat or username of the target channel (in the format @channelusername).</param>
        /// <param name="fromChatId">Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername).</param>
        /// <param name="messageId">Message identifier in the chat specified in from_chat_id.</param>
        /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param>
        /// <param name="protectContent">Protects the contents of the forwarded message from forwarding and saving.</param>
        /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
        /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception>
        /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception>
        public static async Task <Message> ForwardMessageAsync(this BotClient api, string chatId, string fromChatId, int messageId, [Optional] bool?disableNotification, [Optional] bool?protectContent, [Optional] CancellationToken cancellationToken)
        {
            if (api == null)
            {
                throw new ArgumentNullException(nameof(api));
            }
            var stream = new MemoryStream();

            using var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true });
            json.WriteStartObject();
            json.WriteString(PropertyNames.ChatId, chatId);
            json.WriteString(PropertyNames.FromChatId, fromChatId);
            json.WriteNumber(PropertyNames.MessageId, messageId);
            if (disableNotification is not null)
            {
                json.WriteBoolean(PropertyNames.DisableNotification, (bool)disableNotification);
            }
            if (protectContent is not null)
            {
                json.WriteBoolean(PropertyNames.ProtectContent, (bool)protectContent);
            }
            json.WriteEndObject();
            await json.FlushAsync(cancellationToken).ConfigureAwait(false);

            await json.DisposeAsync().ConfigureAwait(false);

            stream.Seek(0, SeekOrigin.Begin);
            return(await api.RPCA <Message>(MethodNames.ForwardMessage, stream, cancellationToken).ConfigureAwait(false));
        }
Example #2
0
        /// <summary>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.</summary>
        /// <param name="bot">BotClient</param>
        /// <param name="chatId">Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername).</param>
        /// <param name="messageId">Identifier of a message to pin.</param>
        /// <param name="disableNotification">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.</param>
        /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
        /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception>
        /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception>
        public static async Task <bool> PinChatMessageAsync(this BotClient bot, long chatId, int messageId, [Optional] bool?disableNotification, [Optional] CancellationToken cancellationToken)
        {
            if (bot == default)
            {
                throw new ArgumentNullException(nameof(bot));
            }

            var stream = new MemoryStream();

            using var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true });
            json.WriteStartObject();
            json.WriteNumber(PropertyNames.ChatId, chatId);
            json.WriteNumber(PropertyNames.MessageId, messageId);
            if (disableNotification != null)
            {
                json.WriteBoolean(PropertyNames.DisableNotification, (bool)disableNotification);
            }

            json.WriteEndObject();
            await json.FlushAsync(cancellationToken).ConfigureAwait(false);

            await json.DisposeAsync().ConfigureAwait(false);

            stream.Seek(0, SeekOrigin.Begin);
            return(await bot.RPCA <bool>(MethodNames.PinChatMessage, stream, cancellationToken).ConfigureAwait(false));
        }
Example #3
0
        /// <summary>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.</summary>
        /// <param name="bot">BotClient</param>
        /// <param name="chatId">Unique identifier for the target group or username of the target supergroup or channel (in the format @username).</param>
        /// <param name="userId">Unique identifier of the target user.</param>
        /// <param name="onlyIfBanned">Do nothing if the user is not banned</param>
        /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
        /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception>
        /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception>
        public static async Task <bool> UnbanChatMemberAsync(this BotClient bot, long chatId, long userId, [Optional] bool?onlyIfBanned, [Optional] CancellationToken cancellationToken)
        {
            if (bot == default)
            {
                throw new ArgumentNullException(nameof(bot));
            }

            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);
            if (onlyIfBanned != null)
            {
                json.WriteBoolean(PropertyNames.OnlyIfBanned, (bool)onlyIfBanned);
            }

            json.WriteEndObject();
            await json.FlushAsync(cancellationToken).ConfigureAwait(false);

            await json.DisposeAsync().ConfigureAwait(false);

            stream.Seek(0, SeekOrigin.Begin);
            return(await bot.RPCA <bool>(MethodNames.UnbanChatMember, stream, cancellationToken).ConfigureAwait(false));
        }
Example #4
0
        /// <summary>Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success. Requires no parameters.</summary>
        /// <param name="bot">Bot Client</param>
        /// <param name="dropPendingUpdates">Pass True to drop all pending updates.</param>
        /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
        /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception>
        /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception>
        public static async Task <bool> DeleteWebhookAsync(this BotClient bot, [Optional] bool?dropPendingUpdates, [Optional] CancellationToken cancellationToken)
        {
            if (bot == default)
            {
                throw new ArgumentNullException(nameof(bot));
            }

            if (dropPendingUpdates != null)
            {
                var stream = new MemoryStream();
                using var json = new Utf8JsonWriter(stream);
                json.WriteStartObject();
                json.WriteBoolean(PropertyNames.DropPendingUpdates, (bool)dropPendingUpdates);
                json.WriteEndObject();
                await json.FlushAsync(cancellationToken).ConfigureAwait(false);

                await json.DisposeAsync().ConfigureAwait(false);

                stream.Seek(0, SeekOrigin.Begin);
                return(await bot.RPCA <bool>(MethodNames.DeleteWebhook, stream, cancellationToken).ConfigureAwait(false));
            }
            else
            {
                return(await bot.RPCA <bool>(MethodNames.DeleteWebhook, cancellationToken).ConfigureAwait(false));
            }
        }
Example #5
0
        /// <summary>Use this method to get a list of profile pictures for a user.</summary>
        /// <param name="bot">BotClient</param>
        /// <param name="userId">Unique identifier of the target user.</param>
        /// <param name="offset">Sequential number of the first photo to be returned. By default, all photos are returned.</param>
        /// <param name="limit">Limits the number of photos to be retrieved. Values between 1—100 are accepted. Defaults to 100.</param>
        /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
        /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception>
        /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception>
        /// <returns>UserProfilePhotos Object.</returns>
        public static async Task <UserProfilePhotos> GetUserProfilePhotosAsync(
            this BotClient bot,
            long userId,
            [Optional] int?offset,
            [Optional] ushort?limit,
            [Optional] CancellationToken cancellationToken)
        {
            if (bot == default)
            {
                throw new ArgumentNullException(nameof(bot));
            }

            var stream = new MemoryStream();

            using var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true });
            json.WriteStartObject();
            json.WriteNumber(PropertyNames.UserId, userId);
            if (offset != null)
            {
                json.WriteNumber(PropertyNames.Offset, (int)offset);
            }

            if (limit != null)
            {
                json.WriteNumber(PropertyNames.Limit, (ushort)limit);
            }

            json.WriteEndObject();
            await json.FlushAsync(cancellationToken).ConfigureAwait(false);

            await json.DisposeAsync().ConfigureAwait(false);

            stream.Seek(0, SeekOrigin.Begin);
            return(await bot.RPCA <UserProfilePhotos>(MethodNames.GetUserProfilePhotos, stream, cancellationToken).ConfigureAwait(false));
        }
        /// <summary>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.</summary>
        /// <param name="bot">Bot Client</param>
        /// <param name="preCheckoutQueryId">Unique identifier for the query to be answered.</param>
        /// <param name="ok">Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems.</param>
        /// <param name="errorMessage">Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user.</param>
        /// <returns>On success, True is returned.</returns>
        /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
        /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception>
        /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception>
        public static async Task <bool> AnswerPreCheckoutQueryAsync(this BotClient bot, string preCheckoutQueryId, bool ok, [Optional] string errorMessage, [Optional] CancellationToken cancellationToken)
        {
            if (bot == default)
            {
                throw new ArgumentNullException(nameof(bot));
            }

            var stream = new MemoryStream();

            using var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true });
            json.WriteStartObject();
            json.WriteString("pre_checkout_query_id", preCheckoutQueryId);
            json.WriteBoolean("ok", ok);
            if (!ok)
            {
                if (errorMessage == default)
                {
                    throw new ArgumentNullException(nameof(errorMessage));
                }

                json.WriteString("error_message", errorMessage);
            }
            json.WriteEndObject();
            await json.FlushAsync(cancellationToken).ConfigureAwait(false);

            await json.DisposeAsync().ConfigureAwait(false);

            stream.Seek(0, SeekOrigin.Begin);
            return(await bot.RPCA <bool>(MethodNames.AnswerPreCheckoutQuery, stream, cancellationToken).ConfigureAwait(false));
        }
        /// <summary>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.</summary>
        /// <param name="bot">BotClient</param>
        /// <param name="name">Sticker set name</param>
        /// <param name="userId">User identifier of the sticker set owner</param>
        /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
        /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception>
        /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception>
        /// <returns>True</returns>
        public static async Task <bool> SetStickerSetThumbAsync(this BotClient bot, string name, long userId, [Optional] CancellationToken cancellationToken)
        {
            if (bot == default)
            {
                throw new ArgumentNullException(nameof(bot));
            }

            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (userId == default)
            {
                throw new ArgumentNullException(nameof(userId));
            }

            var stream = new MemoryStream();

            using var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true });
            json.WriteStartObject();
            json.WriteString(PropertyNames.Name, name);
            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 bot.RPCA <bool>(MethodNames.SetStickerSetThumb, stream, cancellationToken).ConfigureAwait(false));
        }
Example #8
0
        public async Task GetSafe2InfinityAsync(long count)
        {
            Response.Headers.Add("Content-Type", "application/json");
            Response.Headers.Add("Charset", "utf-8");
            var writer = new Utf8JsonWriter(Response.Body);

            try
            {
                var i = 1;
                writer.WriteStartArray();
                //await writer.FlushAsync();
                await foreach (var model in GenerateModelsAsync(count))
                {
                    writer.WriteStartObject();
                    writer.WriteString("index", model.Index.ToString());
                    writer.WriteString("a", model.A.ToString());
                    writer.WriteString("b", model.B.ToString());
                    writer.WriteString("c", model.C);
                    writer.WriteEndObject();
                    i++;
                    if (i % 10000 == 0)
                    {
                        await writer.FlushAsync();
                    }
                }
                writer.WriteEndArray();
                //await writer.FlushAsync();
            }
            finally
            {
                await writer.DisposeAsync();
            }
        }
        /// <summary>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.</summary>
        /// <param name="bot">BotClient</param>
        /// <param name="chatId">Unique identifier for the target chat or username of the target channel (in the format @channelusername)</param>
        /// <param name="senderChatId">Unique identifier of the target sender chat</param>
        /// <param name="untilDate">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.</param>
        /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
        /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception>
        /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception>
        /// <returns>True on success.</returns>
        public static async Task <bool> BanChatSenderChatAsync(this BotClient bot, long chatId, long senderChatId, [Optional] uint?untilDate, [Optional] CancellationToken cancellationToken)
        {
            if (bot == default)
            {
                throw new ArgumentNullException(nameof(bot));
            }

            var stream = new MemoryStream();

            using var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true });
            json.WriteStartObject();
            json.WriteNumber(PropertyNames.ChatId, chatId);
            json.WriteNumber(PropertyNames.SenderChatId, senderChatId);
            if (untilDate != null)
            {
                json.WriteNumber(PropertyNames.UntilDate, (uint)untilDate);
            }
            json.WriteEndObject();
            await json.FlushAsync(cancellationToken).ConfigureAwait(false);

            await json.DisposeAsync().ConfigureAwait(false);

            stream.Seek(0, SeekOrigin.Begin);
            return(await bot.RPCA <bool>(MethodNames.BanChatSenderChat, stream, cancellationToken).ConfigureAwait(false));
        }
Example #10
0
        /// <summary>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.</summary>
        /// <param name="bot">BotClient</param>
        /// <param name="chatId">Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername).</param>
        /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
        /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception>
        /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception>
        public static async Task <bool> DeleteChatStickerSetAsync(
            this BotClient bot,
            string chatId,
            [Optional] CancellationToken cancellationToken)
        {
            if (bot == default)
            {
                throw new ArgumentNullException(nameof(bot));
            }

            var stream = new MemoryStream();

            using var json = new Utf8JsonWriter(
                      stream,
                      new JsonWriterOptions { Indented = true });
            json.WriteStartObject();
            json.WriteString(PropertyNames.ChatId, chatId);
            json.WriteEndObject();
            await json.FlushAsync(cancellationToken).ConfigureAwait(false);

            await json.DisposeAsync().ConfigureAwait(false);

            stream.Seek(0, SeekOrigin.Begin);
            return(await bot.RPCA <bool>(
                       "deleteChatStickerSet",
                       stream,
                       cancellationToken).ConfigureAwait(false));
        }
Example #11
0
        private async Task SerializeInternalAsync(IEnumerable <RpcResponse> responses, bool isBulkRequest, Stream stream)
        {
            var jsonWriter = new Utf8JsonWriter(stream);

            try
            {
                if (isBulkRequest)
                {
                    jsonWriter.WriteStartArray();
                    foreach (RpcResponse response in responses)
                    {
                        this.SerializeResponse(response, jsonWriter);
                    }
                    jsonWriter.WriteEndArray();
                }
                else
                {
                    this.SerializeResponse(responses.Single(), jsonWriter);
                }
            }
            finally
            {
                await jsonWriter.FlushAsync();

                await jsonWriter.DisposeAsync();
            }
        }
Example #12
0
    protected virtual async ValueTask DisposeAsyncCore()
    {
        if (_jsonWriter is not null)
        {
            await _jsonWriter.DisposeAsync().ConfigureAwait(false);
        }

        _jsonWriter = null;
    }
        public async Task <Stream> ExecuteJsonQueryAsync(SqlCommand sqlCommand)
        {
            EnsureConnection(sqlCommand);

            m_SqlDataReader = await sqlCommand.ExecuteReaderAsync();

            SetColumnsFromReader();

            var ms = new MemoryStream();

            await WriteJsonAsync(ms);

            await m_JsonWriter.DisposeAsync();

            await m_SqlDataReader.DisposeAsync();

            return(ms);
        }
Example #14
0
    protected virtual async ValueTask DisposeAsyncCore()
    {
        // Cascade async dispose calls
        if (_jsonWriter != null)
        {
            await _jsonWriter.DisposeAsync();

            _jsonWriter = null;
        }
    }
Example #15
0
        public async ValueTask DisposeAsync()
        {
            if (disposed)
            {
                return;
            }

            disposed = true;
            if (ownsWriter)
            {
                await writer.DisposeAsync();
            }
        }
Example #16
0
    protected virtual async ValueTask DisposeAsyncCore()
    {
        if (!_disposed)
        {
            _disposed = true;

            if (_jsonWriter is not null)
            {
                await _jsonWriter.DisposeAsync();
            }

            _jsonWriter = null;
        }
    }
Example #17
0
        public static async Task <bool> AnswerCallbackQueryAsync(
            this BotClient bot,
            string callbackQueryId,
            [Optional] string?text,
            [Optional] bool?showAlert,
            [Optional] string?url,
            [Optional] uint?cacheTime,
            [Optional] CancellationToken cancellationToken)
        {
            if (bot == default)
            {
                throw new ArgumentNullException(nameof(bot));
            }

            var stream = new MemoryStream();

            using var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true });
            json.WriteStartObject();
            json.WriteString(PropertyNames.CallbackQueryId, callbackQueryId);
            if (!string.IsNullOrEmpty(text))
            {
                json.WriteString(PropertyNames.Text, text);
            }

            if (showAlert != null)
            {
                json.WriteBoolean(PropertyNames.ShowAlert, (bool)showAlert);
            }

            if (!string.IsNullOrEmpty(url))
            {
                json.WriteString(PropertyNames.Url, url);
            }

            if (cacheTime != null)
            {
                json.WriteNumber(PropertyNames.CacheTime, (uint)cacheTime);
            }

            json.WriteEndObject();
            await json.FlushAsync(cancellationToken).ConfigureAwait(false);

            await json.DisposeAsync().ConfigureAwait(false);

            stream.Seek(0, SeekOrigin.Begin);
            return(await bot.RPCA <bool>(MethodNames.AnswerCallbackQuery, stream, cancellationToken).ConfigureAwait(false));
        }
Example #18
0
        /// <summary>Use this method to receive incoming updates using long polling. An Array of <see cref="Update"/> objects is returned.</summary>
        /// <param name="bot">BotClient</param>
        /// <param name="offset">Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned.</param>
        /// <param name="limit">Limits the number of updates to be retrieved. Values between 1—100 are accepted. Defaults to 100.</param>
        /// <param name="timeout">Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only.</param>
        /// <param name="allowedUpdates">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.<para>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.</para></param>
        /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
        /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception>
        /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception>
        public static async Task <Update[]> GetUpdatesAsync(this BotClient bot, [Optional] int?offset, [Optional] ushort?limit, [Optional] uint?timeout, [Optional] IEnumerable <string> allowedUpdates, [Optional] CancellationToken cancellationToken)
        {
            if (bot == default)
            {
                throw new ArgumentNullException(nameof(bot));
            }

            var stream = new MemoryStream();

            using var json = new Utf8JsonWriter(stream);
            json.WriteStartObject();
            if (offset != null)
            {
                json.WriteNumber(PropertyNames.Offset, (int)offset);
            }

            if (limit != null)
            {
                json.WriteNumber(PropertyNames.Limit, (ushort)limit);
            }

            if (timeout != null)
            {
                json.WriteNumber(PropertyNames.Timeout, (uint)timeout);
            }

            if (allowedUpdates != default)
            {
                json.WriteStartArray(PropertyNames.AllowedUpdates);
                foreach (var value in allowedUpdates)
                {
                    json.WriteStringValue(value);
                }
                json.WriteEndArray();
            }
            json.WriteEndObject();
            await json.FlushAsync(cancellationToken).ConfigureAwait(false);

            await json.DisposeAsync().ConfigureAwait(false);

            stream.Seek(0, SeekOrigin.Begin);
            return(await bot.RPCA <Update[]>(MethodNames.GetUpdates, stream, cancellationToken).ConfigureAwait(false));
        }
Example #19
0
        /// <summary>
        /// Attempts to write the provided <see cref="IGraphOperationResult" /> to the stream. Generally this stream
        /// will be the response stream for an HTTP request.
        /// </summary>
        /// <param name="streamToWriteTo">The stream to write to.</param>
        /// <param name="resultToWrite">The result to write.</param>
        /// <param name="options">A set options to customize how the response is serialized to the stream.</param>
        /// <returns>Task.</returns>
        public async Task WriteAsync(Stream streamToWriteTo, IGraphOperationResult resultToWrite, GraphQLResponseOptions options = null)
        {
            options = options ?? GraphQLResponseOptions.Default;

            Utf8JsonWriter writer = null;

            try
            {
                writer = new Utf8JsonWriter(streamToWriteTo, _writerOptions);
                this.WriteResult(writer, resultToWrite, options);
            }
            finally
            {
                if (writer != null)
                {
                    await writer.DisposeAsync();
                }
            }
        }
        /// <summary>Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns True on success.</summary>
        /// <param name="bot">Bot Client</param>
        /// <param name="chatId">Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername).</param>
        /// <param name="userId">Unique identifier of the target user.</param>
        /// <param name="customTitle">New custom title for the administrator; 0-16 characters, emoji are not allowed.</param>
        /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
        /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception>
        /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception>
        /// <returns>True</returns>
        public static async Task<bool> SetChatAdministratorCustomTitleAsync(this BotClient bot, long chatId, long userId, string customTitle, [Optional] CancellationToken cancellationToken)
        {
            if (bot == default)
            {
                throw new ArgumentNullException(nameof(bot));
            }

            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.WriteString(PropertyNames.CustomTitle, customTitle);
            json.WriteEndObject();
            await json.FlushAsync(cancellationToken).ConfigureAwait(false);
            await json.DisposeAsync().ConfigureAwait(false);
            stream.Seek(0, SeekOrigin.Begin);
            return await bot.RPCA<bool>(MethodNames.SendVideoNote, stream, cancellationToken).ConfigureAwait(false);
        }
        private static async ValueTask SerialiseErrorResponseAsync(HttpResponse response, JavaScriptEncoder javaScriptEncoder, Dictionary <string, List <string> > errors)
        {
            var writerOptions = new JsonWriterOptions {
                Encoder = javaScriptEncoder ?? JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            };

            await using var writer = new Utf8JsonWriter(response.Body, writerOptions);

            writer.WriteStartObject();
            writer.WriteString("errorSummary", "One or more validation errors occurred.");
            writer.WriteStartObject("errors");
            WriteErrorsArray(writer, errors);
            writer.WriteEndObject();
            writer.WriteEndObject();

            await writer.FlushAsync();

            await writer.DisposeAsync();
        }
Example #22
0
        /// <summary>Use this method to stop a poll which was sent by the bot. On success, the stopped Poll with the final results is returned.</summary>
        /// <param name="bot">BotClient</param>
        /// <param name="chatId">Unique identifier for the target chat or username of the target channel (in the format @channelusername).</param>
        /// <param name="messageId">Identifier of the original message with the poll</param>
        /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
        /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception>
        /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception>
        public static async Task <Poll> StopPollAsync(this BotClient bot, string chatId, int messageId, [Optional] CancellationToken cancellationToken)
        {
            if (bot == default)
            {
                throw new ArgumentNullException(nameof(bot));
            }

            var stream = new MemoryStream();

            using var json = new Utf8JsonWriter(stream);
            json.WriteStartObject();
            json.WriteString(PropertyNames.ChatId, chatId);
            json.WriteNumber(PropertyNames.MessageId, messageId);
            json.WriteEndObject();
            await json.FlushAsync(cancellationToken).ConfigureAwait(false);

            await json.DisposeAsync().ConfigureAwait(false);

            stream.Seek(0, SeekOrigin.Begin);
            return(await bot.RPCA <Poll>(MethodNames.StopPoll, stream, cancellationToken).ConfigureAwait(false));
        }
Example #23
0
        /// <summary>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.</summary>
        /// <param name="bot">BotClient</param>
        /// <param name="chatId">Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername).</param>
        /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
        /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception>
        /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception>
        /// <returns>Array de ChatMember Object.</returns>
        public static async Task <T> GetChatAdministratorsAsync <T>(this BotClient bot, string chatId, [Optional] CancellationToken cancellationToken)
            where T : IEnumerable <ChatMember>
        {
            if (bot == default)
            {
                throw new ArgumentNullException(nameof(bot));
            }

            var stream = new MemoryStream();

            using var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true });
            json.WriteStartObject();
            json.WriteString(PropertyNames.ChatId, chatId);
            json.WriteEndObject();
            await json.FlushAsync(cancellationToken).ConfigureAwait(false);

            await json.DisposeAsync().ConfigureAwait(false);

            stream.Seek(0, SeekOrigin.Begin);
            return(await bot.RPCA <T>(MethodNames.GetChatAdministrators, stream, cancellationToken).ConfigureAwait(false));
        }
Example #24
0
        public async ValueTask ConvertAsync(Stream input, Stream output, string correlationId)
        {
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }

            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }

            using (var reader = XmlReader.Create(input, new XmlReaderSettings {
                Async = true
            }))
            {
                var header = new RsmHeader();
                var writer = new Utf8JsonWriter(output);

                try
                {
                    reader.ReadToFollowing("MessageContainer", B2BNamespace);

                    await ParseMessageContainerAsync(reader, header).ConfigureAwait(false);

                    reader.ReadToFollowing("Payload", B2BNamespace);

                    await ParseRsmHeaderAsync(reader, header).ConfigureAwait(false);

                    await ConvertPayloadAsync(reader, header, writer, correlationId).ConfigureAwait(false);

                    await writer.FlushAsync().ConfigureAwait(false);
                }
                finally
                {
                    output.Position = 0;
                    await writer.DisposeAsync().ConfigureAwait(false);
                }
            }
        }
        /// <summary>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 <see cref="ChatInviteLink"/> object.</summary>
        /// <param name="bot">BotClient</param>
        /// <param name="chatId">Unique identifier for the target chat or username of the target channel (in the format @channelusername).</param>
        /// <param name="inviteLink">The invite link to edit.</param>
        /// <param name="name">Invite link name; 0-32 characters</param>
        /// <param name="expireDate">Point in time (Unix timestamp) when the link will expire.</param>
        /// <param name="memberLimit">Maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999.</param>
        /// <param name="createsJoinRequest">True, if users joining the chat via the link need to be approved by chat administrators. If True, member_limit can't be specified</param>
        /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
        /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception>
        /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception>
        /// <returns><see cref="ChatInviteLink"/></returns>
        public static async Task <ChatInviteLink> EditChatInviteLink(this BotClient bot, string chatId, string inviteLink, [Optional] string name, [Optional] uint?expireDate, [Optional] uint?memberLimit, [Optional] bool?createsJoinRequest, [Optional] CancellationToken cancellationToken)
        {
            if (bot == default)
            {
                throw new ArgumentNullException(nameof(bot));
            }
            if (string.IsNullOrEmpty(inviteLink))
            {
                throw new ArgumentNullException(nameof(inviteLink));
            }
            var stream = new MemoryStream();

            using var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true });
            json.WriteStartObject();
            json.WriteString(PropertyNames.ChatId, chatId);
            json.WriteString(PropertyNames.InviteLink, inviteLink);
            if (!string.IsNullOrEmpty(name))
            {
                json.WriteString(PropertyNames.Name, name);
            }
            if (expireDate != null)
            {
                json.WriteNumber(PropertyNames.ExpireDate, (uint)expireDate);
            }
            if (memberLimit != null)
            {
                json.WriteNumber(PropertyNames.MemberLimit, (uint)memberLimit);
            }
            if (createsJoinRequest != null)
            {
                json.WriteBoolean(PropertyNames.CreatesJoinRequest, (bool)createsJoinRequest);
            }
            json.WriteEndObject();
            await json.FlushAsync(cancellationToken).ConfigureAwait(false);

            await json.DisposeAsync().ConfigureAwait(false);

            stream.Seek(0, SeekOrigin.Begin);
            return(await bot.RPCA <ChatInviteLink>(MethodNames.EditChatInviteLink, stream, cancellationToken).ConfigureAwait(false));
        }
Example #26
0
        public async ValueTask DisposeAsync()
        {
            await DisposeAsyncCore();

            async ValueTask DisposeAsyncCore()
            {
                if (!_disposed)
                {
                    _disposed = true;

                    if (_jsonWriter != null)
                    {
                        await _jsonWriter.DisposeAsync();
                    }

                    _jsonWriter = null;
                }
            }

            Dispose(disposing: false);
            GC.SuppressFinalize(this);
        }
Example #27
0
        public static async Task <ChatAdministratorRights> GetMyDefaultAdministratorRightsAsync(this BotClient api, [Optional] bool?forChannels, [Optional] CancellationToken cancellationToken)
        {
            if (api == null)
            {
                throw new ArgumentNullException(nameof(api));
            }
            var stream = new MemoryStream();

            using var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true });
            json.WriteStartObject();
            if (forChannels is not null)
            {
                json.WriteBoolean(PropertyNames.ForChannels, (bool)forChannels);
            }
            json.WriteEndObject();
            await json.FlushAsync(cancellationToken).ConfigureAwait(false);

            await json.DisposeAsync().ConfigureAwait(false);

            stream.Seek(0, SeekOrigin.Begin);
            return(await api.RPCA <ChatAdministratorRights>(MethodNames.GetMyDefaultAdministratorRights, stream, cancellationToken).ConfigureAwait(false));
        }
        /// <summary>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.</summary>
        /// <param name="api">The bot client.</param>
        /// <param name="chatId">Unique identifier for the target private chat. If not specified, default bot's menu button will be returned.</param>
        /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
        /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception>
        /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception>
        public static async Task <MenuButton> GetChatMenuButtonAsync(this BotClient api, [Optional] long?chatId, [Optional] CancellationToken cancellationToken)
        {
            if (api == null)
            {
                throw new ArgumentNullException(nameof(api));
            }
            var stream = new MemoryStream();

            using var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true });
            json.WriteStartObject();
            if (chatId is not null)
            {
                json.WriteNumber(PropertyNames.ChatId, (int)chatId);
            }
            json.WriteEndObject();
            await json.FlushAsync(cancellationToken).ConfigureAwait(false);

            await json.DisposeAsync().ConfigureAwait(false);

            stream.Seek(0, SeekOrigin.Begin);
            return(await api.RPCA <MenuButton>(MethodNames.GetChatMenuButton, stream, cancellationToken).ConfigureAwait(false));
        }
        public async ValueTask DisposeAsync()
        {
            var priorState = _state.BeginDispose();

            if (priorState < Disposing)
            {
                if (priorState > Initialized)
                {
                    // if we started running, ensure we are stopped before
                    // continuing
                    _stopCancelTokenSource !.Cancel();
                    _stopCancelTokenSource !.Dispose();
                }

                _heartbeatMutex.Dispose();
                _sessionEncryptionKey.Dispose();
                _websocket.Dispose();
                await _writer.DisposeAsync();

                _userInfo.Dispose();

                _state.EndDispose();
            }
        }
Example #30
0
        /// <summary>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 <see cref="ChatInviteLink"/> object.</summary>
        /// <param name="bot">BotClient</param>
        /// <param name="chatId">Unique identifier for the target chat or username of the target channel (in the format @channelusername).</param>
        /// <param name="inviteLink">The invite link to revoke.</param>
        /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
        /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception>
        /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception>
        /// <returns><see cref="ChatInviteLink"/></returns>
        public static async Task <ChatInviteLink> RevokeChatInviteLink(this BotClient bot, long chatId, string inviteLink, [Optional] CancellationToken cancellationToken)
        {
            if (bot == default)
            {
                throw new ArgumentNullException(nameof(bot));
            }
            if (string.IsNullOrEmpty(inviteLink))
            {
                throw new ArgumentNullException(nameof(inviteLink));
            }
            var stream = new MemoryStream();

            using var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true });
            json.WriteStartObject();
            json.WriteNumber(PropertyNames.ChatId, chatId);
            json.WriteString(PropertyNames.InviteLink, inviteLink);
            json.WriteEndObject();
            await json.FlushAsync(cancellationToken).ConfigureAwait(false);

            await json.DisposeAsync().ConfigureAwait(false);

            stream.Seek(0, SeekOrigin.Begin);
            return(await bot.RPCA <ChatInviteLink>(MethodNames.RevokeChatInviteLink, stream, cancellationToken).ConfigureAwait(false));
        }