private async void EncodeEvents(DirectoryPath recordingDirectoryPath) { var fileStream = GetFileStream(recordingDirectoryPath); // using statement with IDisposable will close writer at end of scope var writer = new Utf8JsonWriter(fileStream); writer.WriteStartArray(); EncodeFinished.Reset(); await foreach (var sample in IntermediateFormatSampleQueue.GetEvents()) { writer.WriteStartObject(); writer.WriteString(nameof(JsonIntermediateFormatSample.Type), sample.JsonEncodedType); // As there is no WriteRaw method on Utf8JsonWriter, we have to use a workaround to write the data writer.WritePropertyName(nameof(JsonIntermediateFormatSample.Data)); sample.JsonEncodedData.WriteTo(writer); writer.WriteEndObject(); } writer.WriteEndArray(); writer.Dispose(); fileStream.Close(); fileStream.Dispose(); EncodeFinished.Set(); }
public void SaveToFile(String path) { if (!path.EndsWith(".tm.json")) { throw new FormatException("Given file '" + path + "' is not a tm(Tilemap)File.\n" + "Provide a file that ends with '.tm.json'."); } FileStream fileStream = new FileStream(path, FileMode.Create); JsonWriterOptions writerOptions = new JsonWriterOptions(); writerOptions.Indented = true; Utf8JsonWriter writer = new Utf8JsonWriter(fileStream, writerOptions); writer.WriteStartObject(); writer.WritePropertyName("TILESET"); writer.WriteStringValue("tilesets/HOW_TO_GET_TILESET_NAME_?"); writer.WritePropertyName("TILES"); writer.WriteStartObject(); for (int i = 0; i < tiles.Count; ++i) { Tile tile = tiles[i]; writer.WritePropertyName("TILE_" + (i + 1)); writer.WriteStartObject(); // Name writer.WritePropertyName("NAME"); writer.WriteStringValue(tile.name); // TextureBounds writer.WritePropertyName("TEXTURE_BOUNDS"); writer.WriteStartArray(); writer.WriteNumberValue(tile.textureBounds.X); writer.WriteNumberValue(tile.textureBounds.Y); writer.WriteNumberValue(tile.textureBounds.Width); writer.WriteNumberValue(tile.textureBounds.Height); writer.WriteEndArray(); // ScreenBounds writer.WritePropertyName("SCREEN_BOUNDS"); writer.WriteStartArray(); writer.WriteNumberValue(tile.screenBounds.X); writer.WriteNumberValue(tile.screenBounds.Y); writer.WriteNumberValue(tile.screenBounds.Width); writer.WriteNumberValue(tile.screenBounds.Height); writer.WriteEndArray(); writer.WriteEndObject(); } writer.WriteEndObject(); writer.WriteEndObject(); writer.Dispose(); fileStream.Dispose(); }
/// <summary>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.</summary> /// <param name="bot">BotClient</param> /// <param name="commands">A list of bot commands to be set as the list of the bot's commands. At most 100 commands can be specified.</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 bool SetMyCommands(this BotClient bot, params BotCommand[] commands) { if (bot == null) { throw new ArgumentNullException(nameof(bot)); } if (commands == null) { throw new ArgumentNullException(nameof(commands)); } var stream = new MemoryStream(); using var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }); json.WriteStartObject(); json.WriteStartArray(PropertyNames.Commands); foreach (var cmd in commands) { if (string.IsNullOrEmpty(cmd.Command) || string.IsNullOrEmpty(cmd.Description)) { throw new ArgumentNullException($"{nameof(commands)} properties can't be null"); } json.WriteStartObject(); json.WriteString(PropertyNames.Command, cmd.Command); json.WriteString(PropertyNames.Description, cmd.Description); json.WriteEndObject(); } json.WriteEndArray(); json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); return(bot.RPC <bool>(MethodNames.SetMyCommands, stream)); }
/// <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">Optional. Sequential number of the first photo to be returned. By default, all photos are returned.</param> /// <param name="limit">Optional. Limits the number of photos to be retrieved. Values between 1—100 are accepted. Defaults to 100.</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 UserProfilePhotos GetUserProfilePhotos( this BotClient bot, long userId, [Optional] int?offset, [Optional] ushort?limit) { 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(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); return(bot.RPC <UserProfilePhotos>(MethodNames.GetUserProfilePhotos, stream)); }
/// <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="thumb">A PNG image with the thumbnail, must be up to 128 kilobytes in size and have width and height exactly 100px, or a TGS animation with the thumbnail up to 32 kilobytes in size; see https://core.telegram.org/animated_stickers#technical-requirements for animated 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. <a href="https://core.telegram.org/bots/api#sending-files">More info on Sending Files »</a>. Animated sticker set thumbnail can't be uploaded via HTTP URL.</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 bool SetStickerSetThumb(this BotClient bot, string name, long userId, string thumb) { 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)); } if (string.IsNullOrEmpty(thumb)) { throw new ArgumentNullException(nameof(thumb)); } 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.WriteString(PropertyNames.Thumb, thumb); json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); return(bot.RPC <bool>(MethodNames.SetStickerSetThumb, stream)); }
/// <summary>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.</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 @channelusername).</param> /// <param name="userId">Unique identifier of the target user.</param> /// <param name="untilDate">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.</param> /// <param name="revokeMessages">Pass True to delete all messages from the chat for the user that is being removed. If False, the user will be able to see messages in the group that were sent before the user was removed. Always True for supergroups and channels.</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 bool BanChatMember(this BotClient bot, string chatId, long userId, [Optional] uint?untilDate, [Optional] bool?revokeMessages) { 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.WriteNumber(PropertyNames.UserId, userId); if (untilDate != null) { json.WriteNumber(PropertyNames.UntilDate, (uint)untilDate); } if (revokeMessages == true) { json.WriteBoolean(PropertyNames.RevokeMessages, true); } json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); return(bot.RPC <bool>(MethodNames.BanChatMember, stream)); }
/// <summary> /// Gets a JSON string for properties from the log message's state and any active scopes. /// </summary> /// <param name="state">The state from the log message.</param> /// <param name="provider">The <see cref="LoupeLoggerProvider"/>.</param> /// <typeparam name="T">The type of the state object</typeparam> /// <returns>A JSON string.</returns> public static string GetJson <T>(T state, LoupeLoggerProvider provider) { var propertySet = HashSetPool.Get(); ByteBufferWriter buffer = null; Utf8JsonWriter jsonWriter = null; try { // Write state first WriteState(state, propertySet, ref buffer, ref jsonWriter); // Write any values from active scopes WriteScope(provider, propertySet, ref jsonWriter, ref buffer); if (!(jsonWriter is null)) { jsonWriter.WriteEndObject(); jsonWriter.Flush(); return(buffer.OutputAsString); } } finally { HashSetPool.Return(propertySet); if (!(jsonWriter is null)) { jsonWriter.Dispose(); buffer.Dispose(); } } return(null); }
/// <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> /// <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 Message ForwardMessage(this BotClient api, string chatId, long fromChatId, int messageId, [Optional] bool?disableNotification, [Optional] bool?protectContent) { 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.WriteNumber(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(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); return(api.RPC <Message>(MethodNames.ForwardMessage, stream)); }
public void WriteToSimpleJsonStream(ReadOnlySpan <JsonEncodedText> propertyNames, Stream outputStream) { using var jw = new Utf8JsonWriter(outputStream); jw.WriteStartArray(); foreach (var line in Utf8ReadLinesToJsonMemory()) { jw.WriteStartObject(); for (int i = 0; i < propertyNames.Length; i++) { if (i >= line.Length) { break; } var m_Value = line.Span[i]; if (!string.IsNullOrWhiteSpace(m_Value.ToString())) { jw.WriteString(propertyNames[i], line.Span[i]); } } jw.WriteEndObject(); } jw.WriteEndArray(); jw.Dispose(); // Clean Up while (jw.BytesPending > 0) { System.Threading.Thread.Sleep(5); } }
private static Utf8JsonWriter WriteJsonToStream(ReadOnlySpan <JsonEncodedText> propertyNames, Stream inputStream, Stream outputStream) { var tsr = new TabStreamReader(inputStream); var jw = new Utf8JsonWriter(outputStream); jw.WriteStartArray(); foreach (var line in tsr.Utf8ReadLinesToJsonMemory()) { jw.WriteStartObject(); for (int i = 0; i < propertyNames.Length; i++) { jw.WriteString(propertyNames[i], line.Span[i]); } jw.WriteEndObject(); } jw.WriteEndArray(); jw.Dispose(); // Clean Up while (jw.BytesPending > 0) { System.Threading.Thread.Sleep(5); } return(jw); }
public void GetTabJsonStrings() { /* Arrange */ var tr = new TabReader(); var jsonFile = TestConstants.GetSUT_OUTPUT_FileInfo(JSON_FILE_NAME); /* Act */ var got = tr.ReadLineTabJsonStrings(TAB_LINE_SIMPLE); var gotHeader = tr.ReadLineTabJsonStrings(TAB_HEADER_SIMPLE); using var writefs = jsonFile.OpenWrite(); using var writer = new Utf8JsonWriter(writefs); writer.WriteStartArray(); writer.WriteStartObject(); for (int i = 0; i < gotHeader.Length; i++) { writer.WriteString(gotHeader[i], got[i]); } writer.WriteEndObject(); writer.WriteEndArray(); // await writer.FlushAsync(); writer.Dispose(); while (writer.BytesPending > 0) { System.Threading.Thread.Sleep(5); } jsonFile.Refresh(); /* Assert */ Assert.False(got.IsEmpty); }
/// <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> /// <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>On success, True is returned.</returns> public static bool AnswerPreCheckoutQuery(this BotClient bot, string preCheckoutQueryId, bool ok, [Optional] string errorMessage) { 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(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); return(bot.RPC <bool>(MethodNames.AnswerPreCheckoutQuery, stream)); }
/// <summary>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 <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="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> /// <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 ChatInviteLink CreateChatInviteLink(this BotClient bot, string chatId, [Optional] string name, [Optional] uint?expireDate, [Optional] uint?memberLimit, [Optional] bool?createsJoinRequest) { 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); 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(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); return(bot.RPC <ChatInviteLink>(MethodNames.CreateChatInviteLink, stream)); }
protected virtual void Dispose(bool disposing) { if (disposing) { _jsonWriter?.Dispose(); } _jsonWriter = null; }
public void Dispose() { if (disposed) { return; } disposed = true; if (ownsWriter) { writer.Dispose(); } }
protected virtual void Dispose(bool disposing) { if (_disposed) { return; } _disposed = true; if (disposing) { _jsonWriter?.Dispose(); } _jsonWriter = null; }
/// <summary>Use this method to get basic info about a file and prepare it for downloading.. On success, a File object is returned.</summary> /// <param name="bot">BotClient</param> /// <param name="fileId">File identifier to get info about.</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="File"/></returns> public static async Task <File> GetFileAsync(this BotClient bot, string fileId, [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.FileId, fileId); json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); return(await bot.RPCA <File>(MethodNames.GetFile, stream, cancellationToken).ConfigureAwait(false)); }
/// <summary>Use this method for your bot to leave a group, supergroup or 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> /// <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 bool LeaveChat(this BotClient bot, string chatId) { 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(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); return(bot.RPC <bool>(MethodNames.LeaveChat, stream)); }
/// <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> /// <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 ChatMember[] GetChatAdministrators(this BotClient bot, long chatId) { 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.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); return(bot.RPC <ChatMember[]>(MethodNames.GetChatAdministrators, stream)); }
public static bool AnswerCallbackQuery( this BotClient bot, string callbackQueryId, [Optional] string?text, [Optional] bool?showAlert, [Optional] string?url, [Optional] uint?cacheTime) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } var stream = new MemoryStream(); 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(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); return(bot.RPC <bool>(MethodNames.AnswerCallbackQuery, stream)); }
protected virtual void Dispose(bool disposing) { if (_disposed) { return; } if (disposing) { _jsonWriter?.Dispose(); // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. _disposed = true; }
/// <summary>Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success.</summary> /// <param name="bot">BotClient</param> /// <param name="sticker">File identifier of the sticker.</param> /// <param name="position">New sticker position in the set, zero-based.</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 bool SetStickerPositionInSet(this BotClient bot, string sticker, int position) { 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.Sticker, sticker); json.WriteNumber(PropertyNames.Position, position); json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); return(bot.RPC <bool>(MethodNames.SetStickerPositionInSet, stream)); }
/// <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> /// <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 MenuButton GetChatMenuButton(this BotClient api, [Optional] long?chatId) { 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(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); return(api.RPC <MenuButton>(MethodNames.GetChatMenuButton, stream)); }
public static ChatAdministratorRights GetMyDefaultAdministratorRights(this BotClient api, [Optional] bool?forChannels) { 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(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); return(api.RPC <ChatAdministratorRights>(MethodNames.GetMyDefaultAdministratorRights, stream)); }
public static bool AnswerInlineQuery(this BotClient bot, AnswerInlineQueryArgs args) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } if (args == default) { throw new ArgumentNullException(nameof(args)); } var stream = new MemoryStream(); using var json = new Utf8JsonWriter(stream); JsonSerializer.Serialize(json, args, typeof(AnswerInlineQueryArgs), BotClient.DefaultSerializerOptions); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); return(bot.RPC <bool>(MethodNames.AnswerInlineQuery, stream)); }
/// <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> /// <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 T GetUpdates <T>(this BotClient bot, [Optional] int?offset, [Optional] ushort?limit, [Optional] uint?timeout, [Optional] IEnumerable <string> allowedUpdates) where T : IEnumerable <Update> { 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(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); return(bot.RPC <T>(MethodNames.GetUpdates, stream)); }
public override void Save <T>(T obj, Stream stream) { JsonWriterOptions option = new JsonWriterOptions { Indented = true, }; jsonWriter = new Utf8JsonWriter(stream, option); if (obj.GetType() != typeof(T)) { object o = obj; Serialize(ref o, 1); } else { Serialize(ref obj, 1); } jsonWriter.Dispose(); }
/// <summary>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..</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="userId">Unique identifier of the target user.</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 bool DeclineChatJoinRequest(this BotClient bot, string chatId, long userId) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } if (string.IsNullOrEmpty(chatId)) { throw new ArgumentNullException(nameof(chatId)); } 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(bot.RPC <bool>(MethodNames.DeclineChatJoinRequest, stream)); }
/// <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> /// <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 ChatInviteLink RevokeChatInviteLink(this BotClient bot, string chatId, string inviteLink) { 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); json.WriteEndObject(); json.Flush(); json.Dispose(); stream.Seek(0, SeekOrigin.Begin); return(bot.RPC <ChatInviteLink>(MethodNames.RevokeChatInviteLink, stream)); }
protected virtual void Dispose(bool disposing) { if (!_isDisposed) { if (disposing) { if (_memoryStream != null) { _memoryStream.Dispose(); } if (_writer != null) { _writer.Dispose(); } } _memoryStream = null; _writer = null; _key = null; _isDisposed = true; } }