### Add telegram-daemon Script to init.d Source: https://github.com/vysheng/tg/wiki/Running-Telegram-CLI-as-Daemon This command copies the 'telegram-daemon' initialization script to the '/etc/init.d/' directory. This allows the system to manage the telegram-daemon process (start, stop, status) using the init system. ```bash sudo cp telegram-daemon /etc/init.d/ ``` -------------------------------- ### Compile and Install libconfig Source: https://github.com/vysheng/tg/blob/master/README-Cygwin.md Downloads, configures, compiles, and installs the libconfig library, which is not available through Cygwin's package manager. This library is needed for configuration file parsing. ```bash wget http://www.hyperrealm.com/libconfig/libconfig-1.5.tar.gz tar xvf libconfig-1.5.tar.gz && cd libconfig-1.5 ./configure make && make install && cd .. ``` -------------------------------- ### Setup Server Key Directory Source: https://github.com/vysheng/tg/wiki/Running-Telegram-CLI-as-Daemon These commands create the '/etc/telegram-cli' directory and copy the 'server.pub' file into it. This directory and file are essential for the telegram-cli client to authenticate with the Telegram servers. ```bash sudo mkdir /etc/telegram-cli ``` ```bash sudo cp server.pub /etc/telegram-cli/server.pub ``` -------------------------------- ### Interact with Telegram Daemon via Netcat Source: https://github.com/vysheng/tg/wiki/Running-Telegram-CLI-as-Daemon This example shows how to connect to the running telegram-daemon on localhost port 2391 using netcat. It demonstrates sending commands like 'dialog_list' and 'msg' to interact with the Telegram service. ```bash nc localhost 2391 ``` ```bash dialog_list ``` ```bash msg vysheng kudos ``` -------------------------------- ### Create Binaries Directory for telegram-cli Source: https://github.com/vysheng/tg/wiki/Running-Telegram-CLI-as-Daemon This command creates a directory structure '/usr/share/telegram-daemon/bin' to store the 'telegram-cli' binary and the 'start-telegram-daemon' script. It then copies these files into the created directory. ```bash sudo mkdir /usr/share/telegram-daemon ``` ```bash sudo mkdir /usr/share/telegram-daemon/bin ``` ```bash sudo cp bin/telegram-cli /usr/share/telegram-daemon/bin/ ``` ```bash sudo cp start-telegram-daemon /usr/share/telegram-daemon/bin ``` -------------------------------- ### Run telegram-cli Source: https://github.com/vysheng/tg/blob/master/README-Cygwin.md Executes the compiled telegram-cli application. The '-k tg-server.pub' argument specifies the public key for the Telegram server. ```bash bin/telegram-cli -k tg-server.pub ``` -------------------------------- ### Install Cygwin Packages for Compilation Source: https://github.com/vysheng/tg/blob/master/README-Cygwin.md Installs the necessary compiler and development tools on Cygwin for building telegram-cli and its dependencies. This includes GCC, make, and other utilities required for the compilation process. ```bash apt-cyg install cygwin32-gcc-core cygwin32-gcc-g++ gcc-core gcc-g++ make wget patch diffutils grep tar gzip ``` -------------------------------- ### Install Additional Cygwin Libraries Source: https://github.com/vysheng/tg/blob/master/README-Cygwin.md Installs essential libraries required for telegram-cli's full functionality on Cygwin. This includes libraries for event handling, SSL, readline, Lua, and Python. ```bash apt-cyg install libevent-devel openssl-devel libreadline-devel lua-devel python3 ``` -------------------------------- ### Compile and Install libjansson Source: https://github.com/vysheng/tg/blob/master/README-Cygwin.md Downloads, configures, compiles, and installs the libjansson library, which is also not available through Cygwin's package manager. This library is necessary for JSON parsing. ```bash wget http://www.digip.org/jansson/releases/jansson-2.7.tar.gz tar xvf jansson-2.7.tar.gz && cd jansson-2.7 ./configure make && make install && cd .. ``` -------------------------------- ### Manage telegram-daemon Service Source: https://github.com/vysheng/tg/wiki/Running-Telegram-CLI-as-Daemon These commands demonstrate how to check the status of the 'telegram-daemon' service and how to restart a specific instance (e.g., 'z5'). This utilizes the init script placed in '/etc/init.d/'. ```bash /etc/init.d/telegram-daemon status ``` ```bash /etc/init.d/telegram-daemon restart z5 ``` ```bash /etc/init.d/telegram-daemon status ``` -------------------------------- ### Start Telegram CLI Client with Options Source: https://context7.com/vysheng/tg/llms.txt Demonstrates how to launch the Telegram CLI client with various configuration options, including specifying a server key, custom configuration directory, daemon mode, and script execution. Requires the `tg-server.pub` key for secure communication. ```bash # Start the client with default configuration ./bin/telegram-cli -k tg-server.pub # Start with custom config directory ./bin/telegram-cli -k tg-server.pub # Start in daemon mode with Python script ./bin/telegram-cli -k tg-server.pub -Z /path/to/script.py -d # Start with Lua script ./bin/telegram-cli -k tg-server.pub -s /path/to/script.lua ``` -------------------------------- ### Clone telegram-cli Repository Source: https://github.com/vysheng/tg/blob/master/README-Cygwin.md Clones the telegram-cli source code repository from GitHub, including all submodules. This is the first step to obtaining the source code for compilation. ```bash git clone --recursive https://github.com/vysheng/tg.git ``` -------------------------------- ### Create Base Directory for telegram-daemon Source: https://github.com/vysheng/tg/wiki/Running-Telegram-CLI-as-Daemon These commands create the base directory '/var/lib/telegram-daemon' for the daemon's data, including binlogs and Lua scripts. It also sets up subdirectories for logs and configuration. ```bash sudo mkdir /var/lib/telegram-daemon ``` ```bash sudo mkdir /var/log/telegram-daemon ``` -------------------------------- ### Python TGL Module - Send Messages and Handle Replies Source: https://context7.com/vysheng/tg/llms.txt Shows how to use the `tgl` Python module to send text messages to Telegram contacts, groups, or channels. Includes examples for disabling URL previews, replying to specific messages, and setting up a message receive handler for bot functionality. Requires the `tgl` library to be installed and configured. ```python import tgl # Set up callback handlers def message_callback(success, msg): if success: print(f"Message sent successfully: {msg.id}") else: print("Failed to send message") def on_msg_receive(msg): # Check if it's a direct message to us if msg.dest.id == our_id: peer = msg.src else: peer = msg.dest # Reply to messages starting with !ping if msg.text and msg.text.startswith("!ping"): peer.send_msg("PONG! Hello from bot", preview=False, reply=msg.id) # Send a simple message peer.send_msg("Hello, this is a test message") # Send message with URL preview disabled peer.send_msg("Check this out: https://example.com", preview=False) # Send message as reply to another message peer.send_msg("This is a reply", reply=123456, callback=message_callback) # Set up the event handler tgl.set_on_msg_receive(on_msg_receive) ``` -------------------------------- ### Compile telegram-cli Source: https://github.com/vysheng/tg/wiki/User-level-daemon-on-Arch-linux-with-systemd Commands to clone the telegram-cli repository recursively, configure the build, and compile the client. It specifically advises against running 'make install'. ```bash git clone --recursive {url}; ./configure; make; ``` -------------------------------- ### Generate Makefile and Patch telegram-cli Source: https://github.com/vysheng/tg/blob/master/README-Cygwin.md Navigates to the telegram-cli directory, generates the Makefile using configure, and then applies a patch to the Makefile and loop.c to ensure compatibility with Cygwin compilation. ```bash cd tg ./configure patch -p1 < telegram-cli-cygwin.patch ``` -------------------------------- ### CLI Commands: Interactive Telegram Operations Source: https://context7.com/vysheng/tg/llms.txt This section lists various command-line interface (CLI) commands for interacting with Telegram. It covers starting the CLI, messaging, contact management, multimedia operations, group chat administration, search queries, secret chat setup, information retrieval, message management, and other utilities. TAB completion and command history are supported. ```bash # Start CLI and login (interactive) ./bin/telegram-cli -k tg-server.pub # Messaging msg John_Doe Hello, how are you? msg My_Group_Chat Everyone, meeting at 3pm fwd Jane_Smith 12345 chat_with_peer John_Doe > Hello from chat mode > /exit # Contacts add_contact +1234567890 John Doe rename_contact John_Doe Jane Smith contact_list # Multimedia send_photo John_Doe /home/user/photo.jpg send_video My_Group /home/user/video.mp4 load_photo 12345 view_photo 12345 set_profile_photo /home/user/avatar.jpg # Group chats create_group_chat "Project Team" John_Doe Jane_Smith Bob_Anderson chat_add_user Project_Team Alice_Cooper chat_del_user Project_Team Bob_Anderson rename_chat Project_Team "Core Team" chat_set_photo Project_Team /home/user/team.jpg chat_info Project_Team # Search search John_Doe "budget report" global_search "meeting notes" # Secret chats create_secret_chat John_Doe visualize_key secret_John_Doe set_ttl secret_John_Doe 60 # Information user_info John_Doe history John_Doe 50 dialog_list contact_list stats get_self # Message management mark_read John_Doe delete_msg 12345 restore_msg 12345 # Other export_card import_card 000653bf:0738ca5d:5521fbac:29246815:a27d0cda safe_quit ``` -------------------------------- ### Compile telegram-cli Source: https://github.com/vysheng/tg/blob/master/README-Cygwin.md Compiles the telegram-cli source code after the Makefile has been generated and patched for Cygwin. This command will produce the executable file. ```bash make ``` -------------------------------- ### Create Configuration Directory for telegram-daemon Source: https://github.com/vysheng/tg/wiki/Running-Telegram-CLI-as-Daemon This command creates the '/etc/telegram-daemon' directory, which will store the configuration files for the telegram-daemon process. Specific configuration files like 'telegram-daemon.achat.conf' are created within this directory. ```bash sudo mkdir /etc/telegram-daemon ``` -------------------------------- ### Create telegramd User Source: https://github.com/vysheng/tg/wiki/Running-Telegram-CLI-as-Daemon This command creates a new system user named 'telegramd' which will be used to run the telegram-daemon process. This is a standard Linux command for user management. ```bash sudo adduser telegramd ``` -------------------------------- ### Interact with telegram-cli via Netcat Source: https://github.com/vysheng/tg/wiki/User-level-daemon-on-Arch-linux-with-systemd Example of sending a command to the running telegram-cli service using netcat. This demonstrates how scripts can communicate with the client by piping commands to the specified localhost port. ```bash echo "msg Girlfriend 'Lets go out?' " | nc localhost 2391 -c ``` -------------------------------- ### Configure telegram-cli Daemon (achat) Source: https://github.com/vysheng/tg/wiki/Running-Telegram-CLI-as-Daemon This block defines the command-line arguments for running the 'telegram-cli' as a daemon, specifically for the 'achat' configuration. It sets verbose logging, enables specific features, and binds to port 2391. This is typically placed in a configuration file. ```bash execute telegram-cli -d -vvvv -E -R -D -C -P 2391 ``` -------------------------------- ### Manage telegram-cli User Systemd Service Source: https://github.com/vysheng/tg/wiki/User-level-daemon-on-Arch-linux-with-systemd Commands to enable, start, and check the status of the user-level systemd service for telegram-cli. These commands must be run as a regular user, not root. ```bash systemctl --user enable telegram systemctl --user status telegram systemctl --user start telegram ``` -------------------------------- ### Python TGL Module - Retrieve Message History with Pagination Source: https://context7.com/vysheng/tg/llms.txt Demonstrates fetching message history for a given peer using the `peer.get_history()` method in the `tgl` Python module. This example shows how to handle pagination to retrieve the complete conversation history by making sequential requests until all messages are fetched. Requires the `tgl` library. ```python import tgl from functools import partial # Storage for accumulated history complete_history = [] BATCH_SIZE = 100 def history_callback(msg_list, peer, batch_size, success, msgs): if not success: print("Failed to retrieve history") return # Add received messages to our list msg_list.extend(msgs) print(f"Retrieved {len(msgs)} messages, total: {len(msg_list)}") # If we got a full batch, there might be more messages if len(msgs) == batch_size: # Request next batch starting from current position peer.get_history( len(msg_list), # offset batch_size, # limit partial(history_callback, msg_list, peer, batch_size) ) else: print(f"History retrieval complete: {len(msg_list)} total messages") # Process complete history for msg in msg_list: if msg.text: print(f"{msg.date}: {msg.src.name}: {msg.text}") ``` -------------------------------- ### Register telegram-cli client Source: https://github.com/vysheng/tg/wiki/User-level-daemon-on-Arch-linux-with-systemd Command to register the telegram-cli client with the server using a public key file. This step might require a significant startup time. ```bash ~/tg/bin/telegram-cli -k ~/tg/server.pub ``` -------------------------------- ### Peer Methods Source: https://github.com/vysheng/tg/blob/master/README-PY.md Provides documentation for various methods related to a Telegram peer (user, chat, or secret chat). ```APIDOC ## Peer Methods ### peer.rename_chat (new_name) #### Description Renames the current chat. #### Method POST #### Endpoint /vysheng/tg/peer/rename_chat #### Parameters - **new_name** (string) - Required - The new name for the chat. ### peer.chat_set_photo (file) #### Description Sets the avatar for a group chat to an image found at the specified file path. The calling peer must be of type `tgl.PEER_CHAT`. #### Method POST #### Endpoint /vysheng/tg/peer/chat_set_photo #### Parameters - **file** (string) - Required - The file path to the image to be set as the chat photo. ### peer.send_typing () #### Description Sends a "typing" notification to the peer. #### Method POST #### Endpoint /vysheng/tg/peer/send_typing ### peer.send_typing_abort () #### Description Aborts the "typing" notification to the peer. #### Method POST #### Endpoint /vysheng/tg/peer/send_typing_abort ### peer.send_msg (text, reply=msg_id, preview=bool) #### Description Sends a text message to the peer. Supports replying to a specific message and controlling URL preview. #### Method POST #### Endpoint /vysheng/tg/peer/send_msg #### Parameters - **text** (string) - Required - The message content. - **reply** (string) - Optional - The message ID to reply to. - **preview** (boolean) - Optional - Whether to force URL preview on or off. ### peer.fwd_msg (msg_id) #### Description Forwards a message with the given message ID to the peer. #### Method POST #### Endpoint /vysheng/tg/peer/fwd_msg #### Parameters - **msg_id** (string) - Required - The ID of the message to forward. ### peer.fwd_media (msg_id) #### Description Forwards media associated with a message ID to the peer. #### Method POST #### Endpoint /vysheng/tg/peer/fwd_media #### Parameters - **msg_id** (string) - Required - The ID of the message containing the media to forward. ### peer.send_photo (file) #### Description Sends a photo to the peer from the specified file path. #### Method POST #### Endpoint /vysheng/tg/peer/send_photo #### Parameters - **file** (string) - Required - The file path to the photo. ### peer.send_video (file) #### Description Sends a video to the peer from the specified file path. #### Method POST #### Endpoint /vysheng/tg/peer/send_video #### Parameters - **file** (string) - Required - The file path to the video. ### peer.send_audio (file) #### Description Sends an audio file to the peer from the specified file path. #### Method POST #### Endpoint /vysheng/tg/peer/send_audio #### Parameters - **file** (string) - Required - The file path to the audio file. ### peer.send_document (file) #### Description Sends a document to the peer from the specified file path. #### Method POST #### Endpoint /vysheng/tg/peer/send_document #### Parameters - **file** (string) - Required - The file path to the document. ### peer.send_text (file) #### Description Sends text content from a file to the peer. #### Method POST #### Endpoint /vysheng/tg/peer/send_text #### Parameters - **file** (string) - Required - The file path containing the text to send. ### peer.send_location (latitude, longitude) #### Description Sends a location message to the peer using latitude and longitude coordinates. #### Method POST #### Endpoint /vysheng/tg/peer/send_location #### Parameters - **latitude** (double) - Required - The latitude coordinate. - **longitude** (double) - Required - The longitude coordinate. ### peer.chat_add_user (user) #### Description Adds a user (peer object) to the group chat. The calling peer must be of type `tgl.PEER_CHAT`. #### Method POST #### Endpoint /vysheng/tg/peer/chat_add_user #### Parameters - **user** (object) - Required - The peer object representing the user to add. ### peer.chat_del_user (user) #### Description Removes a user (peer object) from the group chat. The calling peer must be of type `tgl.PEER_CHAT`. #### Method POST #### Endpoint /vysheng/tg/peer/chat_del_user #### Parameters - **user** (object) - Required - The peer object representing the user to remove. ### peer.mark_read () #### Description Marks the dialog with the peer as read. This cannot be done on a per-message level. #### Method POST #### Endpoint /vysheng/tg/peer/mark_read ### peer.msg_search (text, callback) #### Description Retrieves all messages from the peer that match the given search text. Requires a callback function. #### Method POST #### Endpoint /vysheng/tg/peer/msg_search #### Parameters - **text** (string) - Required - The text to search for in messages. - **callback** (function) - Required - The callback function to process search results. ### peer.get_history (offset, limit, callback) #### Description Retrieves the message history with the peer. Allows specifying an offset and limit for pagination. Requires a callback function. #### Method POST #### Endpoint /vysheng/tg/peer/get_history #### Parameters - **offset** (integer) - Required - The message offset to start retrieving from. - **limit** (integer) - Required - The maximum number of messages to retrieve. - **callback** (function) - Required - The callback function to process history results. ### peer.info () #### Description Retrieves information about the peer. #### Method GET #### Endpoint /vysheng/tg/peer/info ### Example Usage for peer.get_history: ```python from functools import partial history = [] # Get all the history, 100 msgs at a time peer.get_history(0, 100, partial(history_callback, 100, peer)) def history_callback(msg_count, peer, success, msgs): history.extend(msgs) if len(msgs) == msg_count: peer.get_history(len(history), msg_count, partial(history_callback, msg_count, peer)) ``` ``` -------------------------------- ### Create and Manage Group Chats Source: https://github.com/vysheng/tg/blob/master/README-PY.md Functions for creating new group chats with a list of peers, adding/removing users from existing chats, and renaming group chats. These operations require a valid peer list and appropriate permissions. ```python tgl.create_group_chat(peer_list, name) peer.rename_chat(new_name) peer.chat_add_user(user) peer.chat_del_user(user) ``` -------------------------------- ### Lua Scripting: Media and Chat Operations Source: https://context7.com/vysheng/tg/llms.txt This Lua script demonstrates various Telegram operations including sending and downloading media, creating and managing group chats, handling contacts, searching messages, retrieving chat history, sending locations, and updating user status. It relies on predefined functions like `send_photo`, `chat_add_user`, `msg_search`, etc. ```lua -- Send various media types function send_media_example(peer_name) send_photo(peer_name, '/path/to/photo.jpg', ok_cb, false) send_video(peer_name, '/path/to/video.mp4', ok_cb, false) send_audio(peer_name, '/path/to/audio.mp3', ok_cb, false) send_document(peer_name, '/path/to/doc.pdf', ok_cb, false) end -- Download media from message function download_callback(extra, success, result) if success == 1 then print("File downloaded to: " .. result) end end function on_msg_receive(msg) -- Auto-download photos if msg.media and msg.media.type == 'photo' then load_photo(msg.id, download_callback, false) end end -- Chat management function create_chat_example() create_group_chat('User_Name', 'My New Group', ok_cb, false) end function manage_chat(chat_name, user_name) -- Add user to chat chat_add_user(chat_name, user_name, ok_cb, false) -- Rename chat rename_chat(chat_name, 'New Chat Name', ok_cb, false) -- Set chat photo chat_set_photo(chat_name, '/path/to/photo.jpg', ok_cb, false) -- Remove user from chat chat_del_user(chat_name, user_name, ok_cb, false) end -- Contact operations function contact_operations() add_contact('+1234567890', 'John', 'Doe', ok_cb, false) rename_contact('+1234567890', 'Jane', 'Smith', ok_cb, false) end -- Search messages function search_callback(extra, success, results) if success == 1 then print("Found messages") -- Process results end end function search_example(peer_name) msg_search(peer_name, 'keyword', search_callback, false) msg_global_search('important', search_callback, false) end -- History retrieval function history_callback(extra, success, messages) if success == 1 then print("Retrieved " .. #messages .. " messages") end end function get_chat_history(peer_name) get_history(peer_name, 100, history_callback, false) end -- Send location function send_location_example(peer_name) send_location(peer_name, 40.7128, -74.0060, ok_cb, false) end -- Status updates function set_status_online() status_online() end function set_status_offline() status_offline() end ``` -------------------------------- ### Handle Media Operations - Python Source: https://context7.com/vysheng/tg/llms.txt Provides functions for sending and receiving media files like photos, videos, and documents asynchronously using callbacks. It also includes functionality to download media from received messages and set profile or chat photos. ```python import tgl import os def media_callback(success, msg): if success: print(f"Media sent successfully, message ID: {msg.id}") if msg.media: print(f"Media type: {msg.media.get('type', 'unknown')}") else: print("Failed to send media") def file_callback(success, file_path): if success: print(f"File downloaded to: {file_path}") if os.path.exists(file_path): file_size = os.path.getsize(file_path) print(f"File size: {file_size} bytes") else: print("Failed to download file") def on_msg_receive(msg): # Download photos automatically if msg.media and msg.media.get('type') == 'photo': print(f"Downloading photo from message {msg.id}") msg.load_photo(file_callback) # Download videos if msg.media and msg.media.get('type') == 'video': msg.load_video(file_callback) msg.load_video_thumb(file_callback) # Also get thumbnail # Send various media types # Assuming peer is defined elsewhere peer.send_photo("/path/to/image.jpg", callback=media_callback) peer.send_video("/path/to/video.mp4", callback=media_callback) peer.send_audio("/path/to/audio.mp3", callback=media_callback) peer.send_document("/path/to/document.pdf", callback=media_callback) peer.send_text("/path/to/textfile.txt", callback=media_callback) # Send location peer.send_location(40.7128, -74.0060, callback=media_callback) # NYC coordinates # Set profile photo tgl.set_profile_photo("/path/to/avatar.jpg") # Set group chat photo if peer.type == tgl.PEER_CHAT: peer.chat_set_photo("/path/to/group_photo.jpg") ``` -------------------------------- ### Python TGL Module: Event Handlers and Callbacks Source: https://context7.com/vysheng/tg/llms.txt Sets up event handlers for various Telegram events using the Python TGL module. This includes handling binlog replay, synchronization, user ID retrieval, message reception, and updates for users, chats, and secret chats. ```python import tgl our_id = 0 binlog_done = False def on_binlog_replay_end(): global binlog_done binlog_done = True print("Binlog replay completed - historical messages processed") def on_get_difference_end(): print("Synchronized with server - ready to receive new messages") def on_our_id(user_id): global our_id our_id = user_id print(f"Logged in as user ID: {our_id}") def on_msg_receive(msg): # Ignore our own messages during replay if msg.out and not binlog_done: return # Determine who to respond to if msg.dest.id == our_id: peer = msg.src # Direct message else: peer = msg.dest # Group message print(f"New message from {msg.src.name}: {msg.text}") # Auto-reply example if msg.text and "hello" in msg.text.lower(): peer.send_msg("Hello! How can I help you?") def on_user_update(peer, what_changed): print(f"User {peer.name} updated: {', '.join(what_changed)}") # Check user status if hasattr(peer, 'user_status'): if peer.user_status['online']: print(f" {peer.name} is now online") else: print(f" {peer.name} was last seen at {peer.user_status['when']}") def on_chat_update(peer, what_changed): print(f"Chat {peer.name} updated: {', '.join(what_changed)}") def on_secret_chat_update(peer, what_changed): print(f"Secret chat updated: {', '.join(what_changed)}") # Register all event handlers tgl.set_on_binlog_replay_end(on_binlog_replay_end) tgl.set_on_get_difference_end(on_get_difference_end) tgl.set_on_our_id(on_our_id) tgl.set_on_msg_receive(on_msg_receive) tgl.set_on_user_update(on_user_update) tgl.set_on_chat_update(on_chat_update) tgl.set_on_secret_chat_update(on_secret_chat_update) # Set online status tgl.status_online() # Graceful shutdown # tgl.safe_exit(0) ``` -------------------------------- ### Handling Asynchronous Events in Python with tgl Source: https://github.com/vysheng/tg/wiki/Scripting-notes This snippet demonstrates how to handle asynchronous events in Python using the `tgl` library. It defines an `on_loop` function to be executed during the event loop, preventing the main thread from blocking. The `tgl.set_on_loop` function is used to register this handler. ```python import tgl def on_loop(): do_something() send_a_message() tgl.set_on_loop(on_loop) ``` -------------------------------- ### tgl.create_group_chat Source: https://github.com/vysheng/tg/blob/master/README-PY.md Creates a group chat with a list of specified users. Requires more than one peer in the peer_list. ```APIDOC ## tgl.create_group_chat (peer_list, name) ### Description Creates a group chat with a list of specified users. Requires more than one peer in the peer_list. ### Method POST ### Endpoint /vysheng/tg/create_group_chat ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **peer_list** (list) - Required - A list of peers (user IDs or other peer objects) to include in the group chat. - **name** (string) - Required - The name of the group chat. ### Request Example ```json { "peer_list": [ "user_id_1", "user_id_2" ], "name": "My New Group" } ``` ### Response #### Success Response (200) - **chat_id** (string) - The ID of the newly created group chat. #### Response Example ```json { "chat_id": "123456789" } ``` ``` -------------------------------- ### Systemd User Service for telegram-cli Source: https://github.com/vysheng/tg/wiki/User-level-daemon-on-Arch-linux-with-systemd A systemd user service unit file to manage the telegram-cli client as a background service. It specifies the executable path, logging, and port configuration. This file should be placed in `~/.config/systemd/user/telegram.service`. ```systemd [Unit] Description=Telegram-cli systemd service for username1 [Service] ExecStart=/home/username1/tg/bin/telegram-cli -d -vvvv -P 2391 -L /var/log/telegram-daemon/telegram-cli.log [Install] WantedBy=default.target ``` -------------------------------- ### Lua Scripting: Message Handler and Event Callbacks Source: https://context7.com/vysheng/tg/llms.txt Implements message handling and event callbacks using Lua scripting for Telegram automation. It includes functions to process incoming messages, respond to specific commands like 'ping', forward messages, and handle various TGL events such as user updates and binlog completion. ```lua -- Initialize variables started = 0 our_id = 0 -- Callback function for operations function ok_cb(extra, success, result) if success == 1 then print("Operation successful") else print("Operation failed") end end -- Handle incoming messages function on_msg_receive(msg) -- Ignore messages before initialization if started == 0 then return end -- Ignore outgoing messages if msg.out then return end print("Received: " .. (msg.text or "")) -- Auto-reply to "ping" if msg.text == 'ping' then if msg.to.id == our_id then send_msg(msg.from.print_name, 'pong', ok_cb, false) else send_msg(msg.to.print_name, 'pong', ok_cb, false) end return end -- Forward message on "PING" if msg.text == 'PING' then if msg.to.id == our_id then fwd_msg(msg.from.print_name, msg.id, ok_cb, false) else fwd_msg(msg.to.print_name, msg.id, ok_cb, false) end return end end -- Store our user ID function on_our_id(id) our_id = id print("Our ID: " .. id) end -- Binlog replay complete - start processing function on_binlog_replay_end() started = 1 print("Ready to receive messages") postpone(cron, false, 1.0) -- Start periodic task end -- Periodic task (runs every second) function cron() -- Perform periodic actions here postpone(cron, false, 1.0) -- Schedule next run end -- Other event handlers function on_user_update(user, what) -- Handle user updates end function on_chat_update(chat, what) -- Handle chat updates end function on_secret_chat_update(schat, what) -- Handle secret chat updates end function on_get_difference_end() -- Synchronization complete end ``` -------------------------------- ### tgl.status_online Source: https://github.com/vysheng/tg/blob/master/README-PY.md Sets the user's status to online. ```APIDOC ## tgl.status_online () ### Description Sets the user's status to online. ### Method POST ### Endpoint /vysheng/tg/status_online ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **status** (string) - Indicates if the status update was successful. #### Response Example ```json { "status": "online" } ``` ``` -------------------------------- ### Global Message Search with Callback Source: https://context7.com/vysheng/tg/llms.txt Performs a global search across all conversations for a given query and executes a callback function with the results. Useful for finding specific messages quickly. ```python tgl.msg_global_search("important", callback=search_callback) ``` -------------------------------- ### tgl.import_chat_link Source: https://github.com/vysheng/tg/blob/master/README-PY.md Joins a Telegram channel or group using the provided invite link. ```APIDOC ## tgl.import_chat_link (link) ### Description Joins a Telegram channel or group using the provided invite link. ### Method POST ### Endpoint /vysheng/tg/import_chat_link ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **link** (string) - Required - The invite link to the chat. ### Request Example ```json { "link": "https://t.me/+abcdefghijk" } ``` ### Response #### Success Response (200) - **chat_id** (string) - The ID of the joined chat. #### Response Example ```json { "chat_id": "123456789" } ``` ``` -------------------------------- ### Checking User Online Status in Python with tgl Source: https://github.com/vysheng/tg/wiki/Scripting-notes This code snippet shows how to determine if a user is currently online using the `tgl` library in Python. It involves comparing the `user_status["when"]` timestamp with the current time. If the `user_status["when"]` is in the future relative to the current time, the user is considered online. ```python import datetime then = peer.user_status["when"] now = datetime.datetime.now() if then > now: # peer is online greet_peer() ``` -------------------------------- ### Manage Group Chats - Python Source: https://context7.com/vysheng/tg/llms.txt Enables the creation and management of group chats. This includes creating new group chats with multiple users, adding or removing users from existing chats, renaming chats, and retrieving chat information. Operations are asynchronous and use callbacks. ```python import tgl def chat_callback(success, peer): if success: print(f"Group chat created: {peer.name}, ID: {peer.id}") else: print("Failed to create group chat") def empty_callback(success): if success: print("Operation completed successfully") else: print("Operation failed") # Assuming user1_peer, user2_peer, user3_peer, chat_peer, user_peer are defined elsewhere user_list = [user1_peer, user2_peer, user3_peer] tgl.create_group_chat(user_list, "My New Group", callback=chat_callback) if chat_peer.type == tgl.PEER_CHAT: chat_peer.chat_add_user(user_peer, callback=empty_callback) if chat_peer.type == tgl.PEER_CHAT: chat_peer.chat_del_user(user_peer, callback=empty_callback) if chat_peer.type == tgl.PEER_CHAT: chat_peer.rename_chat("Updated Group Name", callback=empty_callback) chat_peer.info(callback=lambda success, peer: print(f"Chat members: {len(peer.user_list) if peer.user_list else 0}")) ``` -------------------------------- ### Find Messages with URLs using Callback Source: https://context7.com/vysheng/tg/llms.txt Searches for messages containing URLs (http/https) and processes them using a callback function. It extracts message text, sender, and date, then prints found URLs. ```python def find_urls_callback(success, msg_list): if success: urls_found = [] for msg in msg_list: if msg.text and ('http://' in msg.text or 'https://' in msg.text): urls_found.append((msg.text, msg.src.name, msg.date)) print(f"Found {len(urls_found)} messages with URLs") for text, sender, date in urls_found: print(f" [{date}] {sender}: {text[:50]}...") tgl.msg_global_search("https", callback=find_urls_callback) ``` -------------------------------- ### Python TGL Module - Contact Management Operations Source: https://context7.com/vysheng/tg/llms.txt Illustrates how to manage Telegram contacts using the `tgl` Python module. Covers retrieving the contact list, adding new contacts with phone numbers and names, renaming existing contacts, and removing contacts. Callbacks are used to handle asynchronous responses. ```python import tgl def contact_list_callback(success, peer_list): if success: print(f"Retrieved {len(peer_list)} contacts:") for peer in peer_list: if peer.type == tgl.PEER_USER: print(f" {peer.first_name} {peer.last_name}: {peer.phone}") else: print("Failed to retrieve contacts") def add_contact_callback(success, peer_list): if success: print("Contact added successfully") else: print("Failed to add contact") # Get contact list (callback required) tgl.get_contact_list(contact_list_callback) # Add a new contact tgl.add_contact("+1234567890", "John", "Doe", callback=add_contact_callback) # Rename an existing contact (updates first/last name for existing phone) tgl.rename_contact("+1234567890", "Jane", "Smith") # Remove contact from contact list tgl.del_contact(peer) ``` -------------------------------- ### Peer Attributes Source: https://github.com/vysheng/tg/blob/master/README-PY.md Provides details on the attributes available for a Telegram peer object. ```APIDOC ## Peer Attributes ### `id` - **Type**: `int` - **Description**: Telegram peer ID. ### `type` - **Type**: `int` - **Description**: Peer type. Can be compared with `tgl.PEER_CHAT`, `tgl.PEER_USER`, or `tgl.PEER_ENCR_CHAT`. ### `type_name` - **Type**: `string` - **Description**: Text representation of the peer type: `'chat'`, `'user'`, or `'secret_chat'`. ### `name` - **Type**: `string` - **Description**: The TG print version of the name. Usually `FirstName_LastName` for users, and the chat name with spaces replaced by `_` for chats. ### `user_id` - **Type**: `int` - **Description**: Used in secret chats; this is the ID of the user at the endpoint. ### `user_list` - **Type**: `peer_list` - **Description**: Only used in `tgl.PEER_CHAT` peers. Contains a list of users. This attribute is currently not reliably populating. ### `user_status` - **Type**: `dict` - **Description**: Only used in `tgl.PEER_USER` peers. A dictionary with the current status. Keys: `'online'` (`bool`), `'when'` (`datetime`). ### `phone` - **Type**: `string` - **Description**: Only used in `tgl.PEER_USER` peers. Phone number, only available if the user is in the contact list. ### `username` - **Type**: `string` - **Description**: Only used in `tgl.PEER_USER` peers. Will be `None` if a username is not set. ### `first_name` - **Type**: `string` - **Description**: Only used in `tgl.PEER_USER` peers. ### `last_name` - **Type**: `string` - **Description**: Only used in `tgl.PEER_USER` peers. ``` -------------------------------- ### User Status and Chat Interaction Source: https://github.com/vysheng/tg/blob/master/README-PY.md Functions to set the user's online or offline status, indicate typing activity, and mark conversations as read. These are used to manage presence and engagement within chats. ```python tgl.status_online() tgl.status_offline() peer.send_typing() peer.send_typing_abort() peer.mark_read() ``` -------------------------------- ### Join and Exit Operations Source: https://github.com/vysheng/tg/blob/master/README-PY.md Functions for joining a Telegram chat or channel via a link and for safely exiting the bot with an optional exit status. Safe exit ensures cleanup operations are performed. ```python tgl.import_chat_link(link) tgl.safe_exit(exit_status) ``` -------------------------------- ### Perform Message Search - Python Source: https://context7.com/vysheng/tg/llms.txt Enables searching for messages within conversations or globally. It accepts a search keyword and a callback function to process the list of found messages, displaying their date, sender, and text content. The search is performed asynchronously. ```python import tgl def search_callback(success, msg_list): if success: print(f"Found {len(msg_list)} messages:") for msg in msg_list: print(f" [{msg.date}] {msg.src.name}: {msg.text}") else: print("Search failed") # Assuming peer is defined elsewhere peer.msg_search("keyword", callback=search_callback) ``` -------------------------------- ### Set Chat Photo Source: https://github.com/vysheng/tg/blob/master/README-PY.md Sets the avatar for a group chat using an image file. The calling peer must be of type `tgl.PEER_CHAT`, and no file validation is performed. ```python peer.chat_set_photo(file) ``` -------------------------------- ### Manage Secret Chats - Python Source: https://context7.com/vysheng/tg/llms.txt Facilitates the creation and management of secret chats, providing end-to-end encryption. It allows initiating secret chats with users, sending encrypted messages, and setting up handlers for secret chat updates. All communication is encrypted. ```python import tgl def secret_chat_callback(success, peer): if success: print(f"Secret chat created with {peer.name}") print(f"Secret chat ID: {peer.id}") print(f"Partner user ID: {peer.user_id}") peer.send_msg("This is an encrypted message") else: print("Failed to create secret chat") def on_secret_chat_update(peer, what_changed): print(f"Secret chat {peer.name} updated: {what_changed}") # Assuming user_peer and secret_chat_peer are defined elsewhere tgl.create_secret_chat(user_peer, callback=secret_chat_callback) tgl.set_on_secret_chat_update(on_secret_chat_update) if secret_chat_peer.type == tgl.PEER_ENCR_CHAT: secret_chat_peer.send_msg("Secret message") secret_chat_peer.send_photo("/path/to/secret_photo.jpg") ``` -------------------------------- ### Message Operations Source: https://github.com/vysheng/tg/blob/master/README-PY.md Provides functionality to restore deleted messages, send various types of messages (text, media, location), forward messages, and search for messages within a chat. Message sending often requires a callback for confirmation. ```python tgl.restore_msg(msg_id) peer.send_msg(text, reply=msg_id, preview=bool) peer.fwd_msg(msg_id) peer.fwd_media(msg_id) peer.send_photo(file) peer.send_video(file) peer.send_audio(file) peer.send_document(file) peer.send_text(file) peer.send_location(latitude, longitude) peer.msg_search(text, callback) ``` -------------------------------- ### tgl.safe_exit Source: https://github.com/vysheng/tg/blob/master/README-PY.md Causes the bot to quit after cleaning up. An optional exit status can be provided. ```APIDOC ## tgl.safe_exit (exit_status) ### Description Causes the bot to quit after cleaning up. An optional exit status can be provided. ### Method POST ### Endpoint /vysheng/tg/safe_exit ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **exit_status** (integer) - Optional - The exit status code (0-255 on glibc). ### Request Example ```json { "exit_status": 0 } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message that the bot is exiting. #### Response Example ```json { "message": "Bot is safely exiting." } ``` ``` -------------------------------- ### Chat History Retrieval Source: https://github.com/vysheng/tg/blob/master/README-PY.md Allows retrieval of message history from a peer. It supports fetching messages in batches using offset and limit parameters, requiring a callback to process received messages. ```python peer.get_history(offset, limit, callback) from functools import partial history = [] # Get all the history, 100 msgs at a time peer.get_history(0, 100, partial(history_callback, 100, peer)) def history_callback(msg_count, peer, success, msgs): history.extend(msgs) if len(msgs) == msg_count: peer.get_history(len(history), msg_count, partial(history_callback, msg_count, peer)) ``` -------------------------------- ### Peer Information Retrieval Source: https://github.com/vysheng/tg/blob/master/README-PY.md Retrieves detailed information about a specific Telegram peer. The information includes the peer's ID, type, name, and user-specific details like username and first/last name. ```python peer.info() ``` -------------------------------- ### tgl.status_offline Source: https://github.com/vysheng/tg/blob/master/README-PY.md Sets the user's status to offline. ```APIDOC ## tgl.status_offline () ### Description Sets the user's status to offline. ### Method POST ### Endpoint /vysheng/tg/status_offline ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **status** (string) - Indicates if the status update was successful. #### Response Example ```json { "status": "offline" } ``` ``` -------------------------------- ### tgl.restore_msg Source: https://github.com/vysheng/tg/blob/master/README-PY.md Restores a deleted message by its message ID. ```APIDOC ## tgl.restore_msg (msg_id) ### Description Restores a deleted message by its message ID. ### Method POST ### Endpoint /vysheng/tg/restore_msg ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **msg_id** (string) - Required - The ID of the message to restore. ### Request Example ```json { "msg_id": "98765" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates if the message restoration was successful. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Retrieve Peer Message History - Python Source: https://context7.com/vysheng/tg/llms.txt Retrieves message history for a given peer. It allows specifying an offset from the most recent messages and a limit for the number of messages per batch. A callback function is used to process the retrieved history. ```python from functools import partial # Assuming peer and BATCH_SIZE are defined elsewhere peer.get_history( 0, # offset: start from most recent BATCH_SIZE, # limit: messages per batch partial(history_callback, complete_history, peer, BATCH_SIZE) ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.