### Basic TDLib Authentication Example in Ruby Source: https://github.com/southbridgeio/tdlib-ruby/blob/master/README.md Demonstrates how to set up and authenticate a TDLib client in Ruby. It covers configuring API credentials, handling authorization states (WaitPhoneNumber, WaitCode, WaitPassword, Ready), and fetching user information. This example utilizes TD::Client for asynchronous operations and Concurrent::Promises::Future for managing them. ```ruby require 'tdlib-ruby' TD.configure do |config| config.lib_path = 'path_to_dir_containing_tdlibjson' config.client.api_id = your_api_id config.client.api_hash = 'your_api_hash' end TD::Api.set_log_verbosity_level(1) client = TD::Client.new begin state = nil client.on(TD::Types::Update::AuthorizationState) do |update| state = case update.authorization_state when TD::Types::AuthorizationState::WaitPhoneNumber :wait_phone_number when TD::Types::AuthorizationState::WaitCode :wait_code when TD::Types::AuthorizationState::WaitPassword :wait_password when TD::Types::AuthorizationState::Ready :ready else nil end end client.connect loop do case state when :wait_phone_number puts 'Please, enter your phone number:' phone = STDIN.gets.strip client.set_authentication_phone_number(phone_number: phone, settings: nil).wait when :wait_code puts 'Please, enter code from SMS:' code = STDIN.gets.strip client.check_authentication_code(code: code).wait when :wait_password puts 'Please, enter 2FA password:' password = STDIN.gets.strip client.check_authentication_password(password: password).wait when :ready client.get_me.then { |user| @me = user }.rescue { |err| puts "error: #{err}" }.wait break end sleep 0.1 end ensure client.dispose end p @me ``` -------------------------------- ### Create and Manage Supergroups with tdlib-ruby Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Provides examples for creating new supergroups or channels, setting their photos, and obtaining invite links. This covers both synchronous and asynchronous operations for group management. ```ruby client = TD::Client.new client.connect # Create a new supergroup client.create_new_supergroup_chat( title: 'My Ruby Bot Group', is_channel: false, description: 'A group created by tdlib-ruby', location: nil, for_import: false ).then { |chat| puts "Created supergroup: #{chat.title}" puts "Chat ID: #{chat.id}" supergroup_id = chat.type.supergroup_id # Set chat photo client.set_chat_photo( chat_id: chat.id, photo: TD::Types::InputChatPhoto::InputChatPhotoStatic.new( photo: TD::Types::InputFile::InputFileLocal.new( path: '/path/to/group_photo.jpg' ) ) ).wait # Get invite link client.get_chat_invite_link(chat_id: chat.id).then { |link| puts "Invite link: #{link.invite_link}" }.wait }.wait # Create a channel (broadcast group) client.create_new_supergroup_chat( title: 'My Ruby Channel', is_channel: true, description: 'A channel for Ruby developers' ).then { |channel| puts "Created channel: #{channel.title}" }.wait ``` -------------------------------- ### Get Full User Info with tdlib-ruby Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Retrieves comprehensive user details, including their bio and group count, using asynchronous promises. This example showcases the `.then` and `.wait` methods for handling asynchronous responses. ```ruby client.get_user_full_info(user_id: user_id) .then { |full_info| puts "\nFull User Info:" puts "Bio: #{full_info.bio.text}" if full_info.bio puts "Group in common count: #{full_info.group_in_common_count}" } .wait ``` -------------------------------- ### Download Photo File Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Provides an example of how to handle new messages containing photos and download them. It extracts the largest photo size and uses `download_file` to initiate the download, checking its progress. ```ruby client.on(TD::Types::Update::NewMessage) do |update| message = update.message if message.content.is_a?(TD::Types::MessageContent::MessagePhoto) photo = message.content.photo # Get largest photo size largest_photo = photo.sizes.max_by { |size| size.width * size.height } file = largest_photo.photo puts "Downloading photo file ID: #{file.id}" # Download file client.download_file( file_id: file.id, priority: 32, offset: 0, limit: 0, synchronous: false ).then { |downloaded_file| if downloaded_file.local.is_downloaded puts "Photo downloaded to: #{downloaded_file.local.path}" else puts "Download in progress: #{downloaded_file.local.downloaded_size}/#{downloaded_file.size} bytes" end }.wait end end client.connect ``` -------------------------------- ### Get User Information with tdlib-ruby Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Fetches and displays basic information about a specific user, including name, username, and contact status. It also demonstrates handling potential TD::Error exceptions during the API call. ```ruby user_id = 987654321 begin user = client.get_user(user_id: user_id).value! puts "\nUser Information:" puts "Name: #{user.first_name} #{user.last_name}" puts "Username: @#{user.username}" if user.username puts "Bio: #{user.type.class.name}" puts "Is Contact: #{user.is_contact}" puts "Is Mutual Contact: #{user.is_mutual_contact}" rescue TD::Error => e puts "Failed to get user: #{e.message}" end ``` -------------------------------- ### Sending Text Messages with Formatting in Ruby Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Provides an example of sending a formatted text message to a specific chat using TD::Client.send_message. It demonstrates constructing the TD::Types::InputMessageContent::InputMessageText object and handling the response or potential errors using promises. ```ruby client = TD::Client.new client.connect # Send simple text message client.send_message( chat_id: 123456789, input_message_content: TD::Types::InputMessageContent::InputMessageText.new( text: TD::Types::FormattedText.new( text: 'Hello from tdlib-ruby!', entities: [] ) ) ).then { |message| puts "Message sent with ID: #{message.id}" }.rescue { |error| puts "Failed to send message: #{error.message}" }.wait ``` -------------------------------- ### Get Chat List Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Demonstrates how to retrieve a list of chats and then fetch details for each chat ID. It uses `get_chats` to get chat IDs and then `get_chat` to retrieve individual chat information. ```ruby client.get_chats( limit: 50 ).then { |chat_list| puts "Retrieved #{chat_list.chat_ids.size} chats" # Get details for each chat chat_list.chat_ids.each do |chat_id| client.get_chat(chat_id: chat_id).then { |chat| puts "- #{chat.title} (#{chat.id})" } end }.wait ``` -------------------------------- ### Get Current User Information Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Demonstrates how to retrieve details about the currently logged-in user using the `get_me` method. It prints various user attributes like name, username, phone number, ID, and premium status. ```ruby current_user = client.get_me.value! puts "Logged in as: #{current_user.first_name} #{current_user.last_name}" puts "Username: @#{current_user.username}" puts "Phone: #{current_user.phone_number}" puts "User ID: #{current_user.id}" puts "Is Premium: #{current_user.is_premium}" ``` -------------------------------- ### Registering Update Handlers with Class Constants in Ruby Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Demonstrates how to register callback handlers for specific TDLib update types using TD::Types::Update constants. Examples include handling new messages, message edits, user status changes, and connection state changes. ```ruby client = TD::Client.new # Handle new messages client.on(TD::Types::Update::NewMessage) do |update| message = update.message chat_id = message.chat_id if message.content.is_a?(TD::Types::MessageContent::MessageText) text = message.content.text.text puts "[Chat #{chat_id}] New message: #{text}" # Reply to message if it contains "ping" if text.downcase.include?('ping') client.send_message( chat_id: chat_id, input_message_content: TD::Types::InputMessageContent::InputMessageText.new( text: TD::Types::FormattedText.new(text: 'pong!', entities: []) ) ) end end end # Handle message edits client.on(TD::Types::Update::MessageContent) do |update| puts "Message #{update.message_id} in chat #{update.chat_id} was edited" end # Handle user status changes client.on(TD::Types::Update::UserStatus) do |update| status = case update.status when TD::Types::UserStatus::Online then "online" when TD::Types::UserStatus::Offline then "offline" when TD::Types::UserStatus::Recently then "recently" else "unknown" end puts "User #{update.user_id} is now #{status}" end # Handle connection state changes client.on(TD::Types::Update::ConnectionState) do |update| state = update.state puts "Connection state: #{state.class.name}" end client.connect # Client will now process updates and trigger registered handlers sleep # Keep running client.dispose ``` -------------------------------- ### Adding tdlib-schema Dependency in Gemfile (Ruby) Source: https://github.com/southbridgeio/tdlib-ruby/blob/master/README.md Shows how to specify the tdlib-schema gem version in a Ruby Gemfile. This is necessary for versions of tdlib-ruby starting from 3.0, where the types schema is extracted to a separate gem. It ensures compatibility with a specific TDLib version. ```ruby gem 'tdlib-schema', '~> 1.7.0' ``` -------------------------------- ### Client Lifecycle Management with tdlib-ruby Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Illustrates different methods for managing the TDLib client's lifecycle, including manual connection/disposal, checking client status (alive, ready, dead), and using a shortcut for automatic ready state. ```ruby # Method 1: Manual lifecycle management client = TD::Client.new client.connect begin # Use client user = client.get_me.value! puts "Connected as: #{user.first_name}" # Do work... ensure # Always dispose client to cleanup resources client.dispose end # Method 2: Check client state client = TD::Client.new client.connect if client.alive? puts "Client is active" # Perform operations end if client.ready? puts "Client is ready for queries" end # Wait for client to be ready client.ready.then { puts "Client initialization complete" # Perform operations after ready }.wait client.dispose # Check if client is dead if client.dead? puts "Client has been disposed" end # Method 3: Ready client shortcut client = TD::Client.ready # Creates, connects, and waits for ready state user = client.get_me.value! client.dispose ``` -------------------------------- ### Configure TDLib Client with Ruby Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Sets up global configuration for the TDLib client, including library path, API credentials, data center usage, storage locations, and client identification details. It prepares the environment for interacting with Telegram. ```ruby require 'tdlib-ruby' TD.configure do |config| # Path to directory containing libtdjson library config.lib_path = '/usr/local/lib/tdlib' # Optional database encryption key config.encryption_key = 'my_secure_encryption_key_32bytes' # Telegram API credentials config.client.api_id = 123456 config.client.api_hash = 'abcdef123456789abcdef123456789ab' # Use test data center (for testing only) config.client.use_test_dc = false # Database and file storage locations config.client.database_directory = "#{Dir.home}/.my_telegram_app/db" config.client.files_directory = "#{Dir.home}/.my_telegram_app/files" # Database features config.client.use_file_database = true config.client.use_chat_info_database = true config.client.use_secret_chats = true config.client.use_message_database = true # Client identification config.client.system_language_code = 'en' config.client.device_model = 'Desktop' config.client.system_version = 'Linux 5.15' config.client.application_version = '1.0.0' # Storage optimization config.client.enable_storage_optimizer = true config.client.ignore_file_names = false end ``` -------------------------------- ### Client Initialization and Connection Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Initialize a TDLib client, connect to Telegram, and handle the authentication flow. ```APIDOC ## Client Initialization and Connection ### Description Create and connect a TDLib client instance with an authentication flow. ### Method `TD::Client.new` `client.connect` `client.on(TD::Types::Update::AuthorizationState)` `client.set_authentication_phone_number(phone_number:, settings:)` `client.check_authentication_code(code:)` `client.check_authentication_password(password:)` `client.get_me` `client.dispose` ### Endpoint N/A ### Parameters #### `TD::Client.new` - **database_directory** (String) - Optional - Path for database storage (overrides global config). - **files_directory** (String) - Optional - Path for file storage (overrides global config). - **timeout** (Integer) - Optional - Client timeout in seconds (default: 30). #### `client.set_authentication_phone_number` - **phone_number** (String) - Required - The phone number to authenticate. - **settings** (Object) - Optional - Authentication settings. #### `client.check_authentication_code` - **code** (String) - Required - The authentication code received. #### `client.check_authentication_password` - **password** (String) - Required - The two-factor authentication password. #### `client.on` - **event** (Class) - Required - The event to listen for, e.g., `TD::Types::Update::AuthorizationState`. - **block** (Proc) - Required - Callback function to handle the event. ### Request Example ```ruby require 'tdlib-ruby' TD.configure do |config| config.lib_path = '/usr/local/lib/tdlib' config.client.api_id = 123456 config.client.api_hash = 'your_api_hash_here' end TD::Api.set_log_verbosity_level(1) client = TD::Client.new auth_state = nil client.on(TD::Types::Update::AuthorizationState) do |update| auth_state = case update.authorization_state when TD::Types::AuthorizationState::WaitPhoneNumber :wait_phone_number when TD::Types::AuthorizationState::WaitCode :wait_code when TD::Types::AuthorizationState::WaitPassword :wait_password when TD::Types::AuthorizationState::Ready :ready when TD::Types::AuthorizationState::Closed :closed else nil end end client.connect begin loop do case auth_state when :wait_phone_number puts 'Enter phone number (with country code):' phone = STDIN.gets.strip client.set_authentication_phone_number( phone_number: phone, settings: nil ).wait when :wait_code puts 'Enter authentication code from SMS/Telegram:' code = STDIN.gets.strip client.check_authentication_code(code: code).wait when :wait_password puts 'Enter 2FA password:' password = STDIN.gets.strip client.check_authentication_password(password: password).wait when :ready me = client.get_me.value! puts "Authenticated as: #{me.first_name} #{me.last_name} (@#{me.username})" break when :closed puts "Client closed" break end sleep 0.1 end ensure client.dispose end ``` ### Response #### Success Response (200) - **`TD::Types::User`** - Information about the current user upon successful authentication. #### Response Example (on successful authentication) ```json { "@type": "user", "id": 123456789, "first_name": "John", "last_name": "Doe", "username": "johndoe", "phone_number": "+11234567890", "profile_photo": null, "is_contact": true, "is_blocked": false, "is_mutual_contact": false, "is_verified": false, "is_scam": false, "is_fake": false, "restriction_reason": "", "language_code": "en", "emoji_status": null, "active_stories_max_count": 0, "stories_max_count": 0, "stories_are_hidden": false } ``` ``` -------------------------------- ### Override TDLib Client Configuration per Instance in Ruby Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Demonstrates how to initialize a TD::Client instance with specific configuration overrides, such as database and files directory paths, and a custom timeout. This allows for flexible configuration of individual client instances without affecting global settings. ```ruby # Override global configuration for specific client instance client = TD::Client.new( database_directory: '/tmp/telegram_test_db', files_directory: '/tmp/telegram_test_files', timeout: 30 ) client.connect ``` -------------------------------- ### Client Configuration Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Configure global settings for the tdlib-ruby client, including library paths, API credentials, and storage options. ```APIDOC ## Client Configuration ### Description Global configuration setup for TDLib library path and client parameters. ### Method Configuration Block ### Endpoint N/A ### Parameters #### Global Configuration - **lib_path** (String) - Required - Path to directory containing libtdjson library. - **encryption_key** (String) - Optional - Database encryption key. #### Client Configuration (config.client) - **api_id** (Integer) - Required - Telegram API ID. - **api_hash** (String) - Required - Telegram API Hash. - **use_test_dc** (Boolean) - Optional - Use test data center (default: false). - **database_directory** (String) - Optional - Path for database storage. - **files_directory** (String) - Optional - Path for file storage. - **use_file_database** (Boolean) - Optional - Enable file database (default: true). - **use_chat_info_database** (Boolean) - Optional - Enable chat info database (default: true). - **use_secret_chats** (Boolean) - Optional - Enable secret chats (default: true). - **use_message_database** (Boolean) - Optional - Enable message database (default: true). - **system_language_code** (String) - Optional - Client system language code (default: 'en'). - **device_model** (String) - Optional - Client device model (default: 'Desktop'). - **system_version** (String) - Optional - Client system version (default: 'Linux 5.15'). - **application_version** (String) - Optional - Client application version (default: '1.0.0'). - **enable_storage_optimizer** (Boolean) - Optional - Enable storage optimizer (default: true). - **ignore_file_names** (Boolean) - Optional - Ignore file names (default: false). ### Request Example ```ruby require 'tdlib-ruby' TD.configure do |config| config.lib_path = '/usr/local/lib/tdlib' config.encryption_key = 'my_secure_encryption_key_32bytes' config.client.api_id = 123456 config.client.api_hash = 'abcdef123456789abcdef123456789ab' config.client.use_test_dc = false config.client.database_directory = "#{Dir.home}/.my_telegram_app/db" config.client.files_directory = "#{Dir.home}/.my_telegram_app/files" config.client.use_file_database = true config.client.use_chat_info_database = true config.client.use_secret_chats = true config.client.use_message_database = true config.client.system_language_code = 'en' config.client.device_model = 'Desktop' config.client.system_version = 'Linux 5.15' config.client.application_version = '1.0.0' config.client.enable_storage_optimizer = true config.client.ignore_file_names = false end ``` ### Response N/A (Configuration is applied internally) ``` -------------------------------- ### Custom Client Configuration Override Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Initialize a TDLib client with specific configuration overrides for that instance, bypassing global settings. ```APIDOC ## Custom Client Configuration Override ### Description Initialize client with per-instance configuration overrides. ### Method `TD::Client.new(options)` `client.connect` ### Endpoint N/A ### Parameters #### `TD::Client.new` Options - **database_directory** (String) - Optional - Path for database storage. - **files_directory** (String) - Optional - Path for file storage. - **timeout** (Integer) - Optional - Client timeout in seconds (default: 30). ### Request Example ```ruby # Override global configuration for specific client instance client = TD::Client.new( database_directory: '/tmp/telegram_test_db', files_directory: '/tmp/telegram_test_files', timeout: 30 ) client.connect ``` ### Response N/A (Instance-specific configuration is applied internally) ``` -------------------------------- ### Initialize TD::Client with Custom Directories (Ruby) Source: https://github.com/southbridgeio/tdlib-ruby/blob/master/README.md Enables overriding default database and file directories during TD::Client initialization. Useful for custom storage solutions. Depends on the TD::Client class. ```ruby TD::Client.new(database_directory: 'will override value from config', files_directory: 'will override value from config') ``` -------------------------------- ### Connect and Authenticate TDLib Client in Ruby Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Initializes a TDLib client, configures logging, connects to the Telegram servers, and manages the authentication process by handling different authorization states (phone number, code, password) until the client is ready. It also disposes of the client upon completion or closure. ```ruby require 'tdlib-ruby' TD.configure do |config| config.lib_path = '/usr/local/lib/tdlib' config.client.api_id = 123456 config.client.api_hash = 'your_api_hash_here' end TD::Api.set_log_verbosity_level(1) client = TD::Client.new # Track authentication state auth_state = nil # Register handler for authorization state updates client.on(TD::Types::Update::AuthorizationState) do |update| auth_state = case update.authorization_state when TD::Types::AuthorizationState::WaitPhoneNumber :wait_phone_number when TD::Types::AuthorizationState::WaitCode :wait_code when TD::Types::AuthorizationState::WaitPassword :wait_password when TD::Types::AuthorizationState::Ready :ready when TD::Types::AuthorizationState::Closed :closed else nil end end # Connect to TDLib client.connect # Authentication loop begin loop do case auth_state when :wait_phone_number puts 'Enter phone number (with country code):' phone = STDIN.gets.strip client.set_authentication_phone_number( phone_number: phone, settings: nil ).wait when :wait_code puts 'Enter authentication code from SMS/Telegram:' code = STDIN.gets.strip client.check_authentication_code(code: code).wait when :wait_password puts 'Enter 2FA password:' password = STDIN.gets.strip client.check_authentication_password(password: password).wait when :ready # Successfully authenticated me = client.get_me.value! puts "Authenticated as: #{me.first_name} #{me.last_name} (@#{me.username})" break when :closed puts "Client closed" break end sleep 0.1 end ensure client.dispose end ``` -------------------------------- ### TDLib Configuration Options in Ruby Source: https://github.com/southbridgeio/tdlib-ruby/blob/master/README.md Details the various configuration options available for the tdlib-ruby client. This includes setting the TDLib library path, encryption key, API credentials, testing data centers, database and file directories, and system/application information for the client. These settings allow for customization of the Telegram client's behavior and storage. ```ruby TD.configure do |config| config.lib_path = 'path/to/dir_containing_libtdjson' # libtdjson will be searched in this directory (*.so, *.dylib, *.dll are valid extensions). For Rails projects, if not set, will be considered as project_root_path/vendor. If not set and file doesn't exist in vendor, it will try to find lib by ldconfig (only on Linux). config.encryption_key = 'your_encryption_key' # it's not required config.client.api_id = 12345 config.client.api_hash = 'your_api_hash' config.client.use_test_dc = true # default: false config.client.database_directory = 'path/to/db/dir' # default: "#{Dir.home}/.tdlib-ruby/db" config.client.files_directory = 'path/to/files/dir' # default: "#{Dir.home}/.tdlib-ruby/files" config.client.use_file_database = true # default: true config.client.use_chat_info_database = true # default: true config.client.use_secret_chats = true # default: true config.client.use_message_database = true # default: true config.client.system_language_code = 'ru' # default: 'en' config.client.device_model = 'Some device model' # default: 'Ruby TD client' config.client.system_version = '42' # default: 'Unknown' config.client.application_version = '1.0' # default: '1.0' config.client.enable_storage_optimizer = true # default: true config.client.ignore_file_names = true # default: false end ``` -------------------------------- ### Asynchronous Query Execution with Promises in Ruby Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Demonstrates sending asynchronous requests using TD::Client.broadcast and handling responses with promise chaining (.then, .rescue, .wait). It also shows how to execute multiple asynchronous operations concurrently using Concurrent::Promises.zip. ```ruby client = TD::Client.new client.connect # Asynchronous request with promise chaining client.broadcast({ '@type' => 'getMe' }) .then { |user| puts "User ID: #{user.id}" puts "Username: @#{user.username}" puts "Phone: #{user.phone_number}" } .rescue { |error| puts "Error #{error.code}: #{error.message}" } .wait # Multiple asynchronous operations promises = [] promises << client.get_me .then { |user| puts "Current user: #{user.first_name}" } promises << client.get_chats(limit: 10) .then { |chats| puts "Retrieved #{chats.chat_ids.size} chats" } promises << client.search_public_chat(username: 'telegram') .then { |chat| puts "Found chat: #{chat.title}" } .rescue { |error| puts "Search failed: #{error.message}" } # Wait for all promises to complete Concurrent::Promises.zip(*promises).wait ``` -------------------------------- ### Error Handling with tdlib-ruby Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Demonstrates robust error handling strategies for TDLib interactions, including using `.rescue` with asynchronous promises to catch specific error codes and messages, and employing traditional `begin-rescue` blocks for synchronous operations. ```ruby client = TD::Client.new client.connect # Handle errors with promises client.get_chat(chat_id: 999999999) .then { |chat| puts "Chat: #{chat.title}" } .rescue { |error| puts "Error code: #{error.code}" puts "Error message: #{error.message}" # Handle specific error codes case error.code when 400 puts "Bad request - invalid chat ID" when 404 puts "Chat not found" when 500 puts "Internal server error" else puts "Unexpected error" end } .wait # Synchronous error handling begin chat = client.get_chat(chat_id: 123456789).value! puts "Chat found: #{chat.title}" rescue TD::Error => e puts "Failed to retrieve chat" puts "Code: #{e.code}, Message: #{e.message}" # Error object delegates to TD::Types::Error puts "Error type: #{e.class.name}" end ``` -------------------------------- ### Synchronous Query Execution with Fetch in Ruby Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Illustrates how to execute TDLib requests synchronously using TD::Client.fetch or convenience methods followed by .value!. This approach blocks until a response is received. Error handling for synchronous calls is also demonstrated. ```ruby client = TD::Client.new client.connect begin # Synchronous request (blocks until response) user = client.fetch({ '@type' => 'getMe' }) puts "User: #{user.first_name} #{user.last_name}" # Using convenience methods (also synchronous when .value! is called) chats = client.get_chats(limit: 20).value! puts "Total chats: #{chats.chat_ids.size}" # Error handling with synchronous calls begin chat = client.get_chat(chat_id: 123456789).value! puts "Chat title: #{chat.title}" rescue TD::Error => e puts "Failed to get chat: #{e.message} (code: #{e.code})" end rescue TD::Error => e puts "Request failed: #{e.message}" ensure client.dispose end ``` -------------------------------- ### Send Local Video Message Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Illustrates sending a local video file as a message. This involves using `InputMessageVideo` with `InputFileLocal` for the video path, along with duration, dimensions, and an optional caption. ```ruby client.send_message( chat_id: chat_id, input_message_content: TD::Types::InputMessageContent::InputMessageVideo.new( video: TD::Types::InputFile::InputFileLocal.new( path: '/path/to/video.mp4' ), duration: 60, width: 1920, height: 1080, caption: TD::Types::FormattedText.new(text: 'Video clip', entities: []) ) ).wait ``` -------------------------------- ### Synchronous Execute for Local TDLib Operations in Ruby Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Shows how to use the `execute` method for synchronous, local TDLib operations that do not require network requests, such as text entity extraction. It highlights that only specific methods support `execute`. ```ruby # Execute operates synchronously on certain local TDLib operations # Only specific methods support execute (primarily configuration and utility methods) result = client.execute({ '@type' => 'getTextEntities', 'text' => '@username #hashtag https://example.com' }) puts "Found #{result.entities.size} entities" result.entities.each do |entity| puts "Type: #{entity.type['@type']}, Offset: #{entity.offset}, Length: #{entity.length}" end ``` -------------------------------- ### Chat Operations with tdlib-ruby Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Demonstrates essential chat management functions, including retrieving chat details, fetching message history, marking messages as read, pinning messages, and leaving chats. It utilizes both synchronous and asynchronous operations. ```ruby client = TD::Client.new client.connect # Get chat information chat_id = 123456789 chat = client.get_chat(chat_id: chat_id).value! puts "Chat: #{chat.title}" puts "Type: #{chat.type.class.name}" puts "Unread count: #{chat.unread_count}" # Get chat history (messages) client.get_chat_history( chat_id: chat_id, from_message_id: 0, offset: 0, limit: 20, only_local: false ).then { |messages| puts "\nLast #{messages.messages.size} messages:" messages.messages.reverse.each do |msg| if msg.content.is_a?(TD::Types::MessageContent::MessageText) sender_id = msg.sender_id text = msg.content.text.text puts "[#{msg.date}] #{sender_id}: #{text}" end end }.wait # Mark chat as read client.view_messages( chat_id: chat_id, message_ids: [chat.last_message.id], force_read: true ).wait # Pin a message message_id = 123456 client.pin_chat_message( chat_id: chat_id, message_id: message_id, disable_notification: false, only_for_self: false ).wait # Leave a chat/group client.leave_chat(chat_id: chat_id).wait ``` -------------------------------- ### Log Configuration Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Control the logging level and output file for TDLib. ```APIDOC ## Log Configuration ### Description Control TDLib logging verbosity and output destination. ### Method `TD::Api.set_log_verbosity_level(level)` `TD::Api.set_log_file_path(path)` ### Endpoint N/A ### Parameters #### `set_log_verbosity_level` - **level** (Integer) - Required - Logging verbosity level (0 = fatal, 1 = errors, 2 = warnings, 3 = info, 4 = debug, 5 = verbose). #### `set_log_file_path` - **path** (String) - Required - Path to the custom log file. ### Request Example ```ruby # Set log verbosity level to info TD::Api.set_log_verbosity_level(3) # Set custom log file path TD::Api.set_log_file_path('/var/log/telegram/tdlib.log') # Disable logging TD::Api.set_log_verbosity_level(0) ``` ### Response N/A (Logging settings are applied internally) ``` -------------------------------- ### Send Local Photo Message Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Demonstrates sending a local photo file as a message. It uses `InputMessagePhoto` with `InputFileLocal` pointing to the file path and includes an optional caption. ```ruby client.send_message( chat_id: chat_id, input_message_content: TD::Types::InputMessageContent::InputMessagePhoto.new( photo: TD::Types::InputFile::InputFileLocal.new( path: '/path/to/photo.jpg' ), caption: TD::Types::FormattedText.new( text: 'Check out this photo!', entities: [] ), width: 0, height: 0 ) ).then { |message| puts "Photo sent successfully" }.wait ``` -------------------------------- ### Configure TDLib Logging with Ruby Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Manages TDLib logging verbosity and directs log output to a specified file. This allows for controlling the level of detail in logs, from fatal errors to verbose debug information, and disabling logging entirely. ```ruby # Set log verbosity level (0 = fatal, 1 = errors, 2 = warnings, 3 = info, 4 = debug, 5 = verbose) TD::Api.set_log_verbosity_level(1) # Set custom log file path TD::Api.set_log_file_path('/var/log/telegram/tdlib.log') # Disable logging (set to 0) TD::Api.set_log_verbosity_level(0) ``` -------------------------------- ### Handle Timeout Errors with TD::Client in Ruby Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt This snippet demonstrates how to handle timeout errors when creating and connecting a TD::Client instance in Ruby. It shows how to set a custom timeout value and catch specific TD::Error exceptions, checking if the error message indicates a timeout. ```ruby begin # Create client with custom timeout client = TD::Client.new(timeout: 5) client.connect result = client.get_me.value! rescue TD::Error => e if e.message.include?('Timeout') puts "Request timed out after 5 seconds" end end ``` -------------------------------- ### Download Document File Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Shows how to download document files received in messages. It identifies `MessageDocument` content, extracts the file information, and uses `download_file` with `synchronous: true` to wait for the download completion. ```ruby client.on(TD::Types::Update::NewMessage) do |update| message = update.message if message.content.is_a?(TD::Types::MessageContent::MessageDocument) document = message.content.document file = document.document puts "Downloading document: #{document.file_name}" client.download_file( file_id: file.id, priority: 32, offset: 0, limit: 0, synchronous: true # Wait until download completes ).then { |downloaded_file| puts "Document saved to: #{downloaded_file.local.path}" }.wait end end client.connect ``` -------------------------------- ### Set TDLib Log File Path (Ruby) Source: https://github.com/southbridgeio/tdlib-ruby/blob/master/README.md Specifies the file path where TDLib logs will be written. This helps in managing and analyzing log data. Requires the TD::Api module. ```ruby TD::Api.set_log_file_path('path/to/log_file') ``` -------------------------------- ### Registering Update Handlers with String Names in Ruby Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Shows an alternative method for registering update handlers using string names of update types (e.g., 'updateNewMessage') instead of TD::Types::Update constants. This approach is functionally equivalent to using class constants. ```ruby client = TD::Client.new # Register handler using string type name client.on('updateNewMessage') do |update| message = update.message puts "New message received in chat #{message.chat_id}" end # This is equivalent to: # client.on(TD::Types::Update::NewMessage) do |update| # ... # end client.connect ``` -------------------------------- ### Send Local Document Message Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Shows how to send a local document file as a message. It utilizes `InputMessageDocument` with `InputFileLocal` specifying the file path and allows for a caption. ```ruby client.send_message( chat_id: chat_id, input_message_content: TD::Types::InputMessageContent::InputMessageDocument.new( document: TD::Types::InputFile::InputFileLocal.new( path: '/path/to/document.pdf' ), caption: TD::Types::FormattedText.new( text: 'Important document', entities: [] ) ) ).wait ``` -------------------------------- ### Search Public Chat by Username Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Shows how to find a public Telegram chat using its username. It uses the `search_public_chat` method and handles success and error cases with `.then` and `.rescue`. ```ruby client.search_public_chat(username: 'telegram') .then { |chat| puts "Found: #{chat.title}" puts "ID: #{chat.id}" puts "Type: #{chat.type.class.name}" } .rescue { |error| puts "Chat not found: #{error.message}" } .wait ``` -------------------------------- ### Send Formatted Text with Entities Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Demonstrates how to send messages with rich text formatting, such as bold and italic, using TD::Types::TextEntity. This requires defining the text and its corresponding entities. ```ruby entities = [ TD::Types::TextEntity.new( offset: 0, length: 5, type: TD::Types::TextEntityType::Bold.new ), TD::Types::TextEntity.new( offset: 11, length: 7, type: TD::Types::TextEntityType::Italic.new ) ] client.send_message( chat_id: 123456789, input_message_content: TD::Types::InputMessageContent::InputMessageText.new( text: TD::Types::FormattedText.new( text: 'Hello, tdlib-ruby users!', entities: entities ), disable_web_page_preview: false, clear_draft: true ) ).wait ``` -------------------------------- ### Set TDLib Log Verbosity Level (Ruby) Source: https://github.com/southbridgeio/tdlib-ruby/blob/master/README.md Allows control over the level of detail in TDLib logs. Set to 1 to reduce log size. No specific dependencies beyond the TD::Api module. ```ruby TD::Api.set_log_verbosity_level(1) ``` -------------------------------- ### Search Messages in a Chat Source: https://context7.com/southbridgeio/tdlib-ruby/llms.txt Illustrates how to search for messages within a specific chat using various filters like query, sender ID, and message filter. It then iterates through the found messages and prints their text content if they are text messages. ```ruby client.search_chat_messages( chat_id: 123456789, query: 'hello', sender_id: nil, from_message_id: 0, offset: 0, limit: 50, filter: TD::Types::SearchMessagesFilter::SearchMessagesFilterEmpty.new ).then { |messages| puts "Found #{messages.total_count} messages" messages.messages.each do |msg| if msg.content.is_a?(TD::Types::MessageContent::MessageText) puts "- #{msg.content.text.text}" end end }.wait ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.