### Control Hardware via Telegram Commands Source: https://context7.com/witnessmenow/universal-arduino-telegram-bot/llms.txt Receives commands via Telegram messages to control hardware components like LEDs. It processes specific commands such as /ledon, /ledoff, and /status, updating the hardware state and sending confirmation or status messages back to the user. This example assumes a predefined `ledPin` and `ledStatus` variable. ```cpp const int ledPin = LED_BUILTIN; int ledStatus = 0; void handleNewMessages(int numNewMessages) { for (int i = 0; i < numNewMessages; i++) { String chat_id = bot.messages[i].chat_id; String text = bot.messages[i].text; if (text == "/ledon") { digitalWrite(ledPin, LOW); // Active LOW ledStatus = 1; bot.sendMessage(chat_id, "LED is ON", ""); } else if (text == "/ledoff") { digitalWrite(ledPin, HIGH); ledStatus = 0; bot.sendMessage(chat_id, "LED is OFF", ""); } else if (text == "/status") { String msg = ledStatus ? "LED is ON" : "LED is OFF"; bot.sendMessage(chat_id, msg, ""); } } } void setup() { pinMode(ledPin, OUTPUT); digitalWrite(ledPin, HIGH); // Start with LED off // WiFi and SSL setup as in previous examples... } void loop() { if (millis() - bot_lasttime > BOT_MTBS) { int numNewMessages = bot.getUpdates(bot.last_message_received + 1); if (numNewMessages) { handleNewMessages(numNewMessages); } bot_lasttime = millis(); } } ``` -------------------------------- ### Set Bot Commands Menu with Arduino Telegram Bot Source: https://context7.com/witnessmenow/universal-arduino-telegram-bot/llms.txt This code snippet shows how to programmatically set the bot's command list, which appears in the Telegram client's UI. This improves discoverability of bot commands. It uses the `bot.setMyCommands()` function, which accepts a JSON string representing an array of command objects. The `setup()` function includes WiFi connection and SSL configuration before calling `setupBotCommands()`. ```cpp void setupBotCommands() { // JSON array of command objects String commands = "[" "{\"command\":\"start\",\"description\":\"Start the bot\"}," "{\"command\":\"help\",\"description\":\"Show help message\"}," "{\"command\":\"status\",\"description\":\"Get system status\"}," "{\"command\":\"ledon\",\"description\":\"Turn LED on\"}," "{\"command\":\"ledoff\",\"description\":\"Turn LED off\"}," "{\"command\":\"settings\",\"description\":\"Open settings menu\"}" "]"; bool success = bot.setMyCommands(commands); if (success) { Serial.println("Bot commands set successfully"); } else { Serial.println("Failed to set bot commands"); } } void setup() { Serial.begin(115200); // Connect to WiFi and configure SSL... WiFi.begin(WIFI_SSID, WIFI_PASSWORD); secured_client.setTrustAnchors(&cert); while (WiFi.status() != WL_CONNECTED) { delay(500); } // Set bot commands after connection setupBotCommands(); Serial.println("Bot is ready"); } ``` -------------------------------- ### Arduino ESP32: Update Firmware and SPIFFS via Telegram Source: https://github.com/witnessmenow/universal-arduino-telegram-bot/blob/master/README.md This example demonstrates how to update the firmware and SPIFFS (Serial Peripheral Interface Flash File System) on an ESP32 device using Telegram. Files are sent as regular messages with specific captions like 'update firmware' or 'update spiffs' to trigger the process. The code is written for the ESP32 platform. ```arduino // Example code for telegramOTA.ino would go here // This snippet is a placeholder for the actual Arduino code found at the provided link. ``` -------------------------------- ### Send Photo with Arduino Source: https://github.com/witnessmenow/universal-arduino-telegram-bot/blob/master/README.md Examples demonstrate sending photos from an Arduino device to a Telegram chat. Photos can be sent directly from a URL, as binary data from an SD card, or by using a file ID. The examples cover different methods for photo transmission. ```Arduino #include #include // WiFi credentials const char* ssid = "YOUR_SSID"; const char* password = "YOUR_PASSWORD"; // Telegram Bot Token String botToken = "YOUR_BOT_TOKEN"; WiFiClientSecure client; UniversalTelegramBot bot(botToken, client); void setup() { Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi..."); } Serial.println("Connected to WiFi"); // Example: Sending photo from URL // bot.sendMessage("YOUR_CHAT_ID", "Sending photo from URL..."); // bot.sendPhotoByUrl("YOUR_CHAT_ID", "https://www.arduino.cc/about/img/logo.png"); // Example: Sending photo from SD card (requires SD library and setup) // bot.sendMessage("YOUR_CHAT_ID", "Sending photo from SD card..."); // File photoFile = SD.open("/photo.jpg"); // if (photoFile) { // bot.sendPhoto("YOUR_CHAT_ID", photoFile); // photoFile.close(); // } // Example: Sending photo by File ID // bot.sendMessage("YOUR_CHAT_ID", "Sending photo by File ID..."); // bot.sendPhotoById("YOUR_CHAT_ID", "FILE_ID_OF_YOUR_PHOTO"); } void loop() { // Nothing here for this example } ``` -------------------------------- ### Arduino Telegram Bot: Read Channel Posts Source: https://github.com/witnessmenow/universal-arduino-telegram-bot/blob/master/README.md This section provides an example of how an Arduino Telegram bot can read messages posted in Telegram channels. It allows the Arduino to monitor and react to content shared in specific channels. The implementation is usually done within the Arduino IDE. ```arduino // Example code for ChannelPost.ino would go here // This snippet is a placeholder for the actual Arduino code found at the provided link. ``` -------------------------------- ### Arduino Telegram Bot: Handle Location Data Source: https://github.com/witnessmenow/universal-arduino-telegram-bot/blob/master/README.md This snippet demonstrates how an Arduino bot can receive and process location data from Telegram. It supports both single location data points and live location updates. The example is typically implemented using the Arduino IDE. ```arduino // Example code for Location.ino would go here // This snippet is a placeholder for the actual Arduino code found at the provided link. ``` -------------------------------- ### Include and Initialize Universal Telegram Bot Library Source: https://github.com/witnessmenow/universal-arduino-telegram-bot/blob/master/README.md This snippet demonstrates how to include the UniversalTelegramBot library and initialize a bot instance with a provided Bot Token and a WiFiClientSecure object. The Bot Token is obtained from Telegram's BotFather, and the WiFiClientSecure is used for secure network communication. ```arduino #include // Telegram BOT Token (Get from Botfather) #define BOT_TOKEN "XXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" WiFiClientSecure secured_client; UniversalTelegramBot bot(BOT_TOKEN, secured_client); ``` -------------------------------- ### Initialize Arduino Telegram Bot and Receive Messages Source: https://context7.com/witnessmenow/universal-arduino-telegram-bot/llms.txt Initializes the Universal Arduino Telegram Bot library, connects to WiFi, and sets up secure client for Telegram API communication. It then polls for incoming messages, storing them in the bot.messages array for further processing. Requires WiFi credentials and a bot token. ```cpp #include #include #include #define WIFI_SSID "MyNetwork" #define WIFI_PASSWORD "MyPassword123" #define BOT_TOKEN "1234567890:ABCdefGHIjklMNOpqrsTUVwxyz123456789" X509List cert(TELEGRAM_CERTIFICATE_ROOT); WiFiClientSecure secured_client; UniversalTelegramBot bot(BOT_TOKEN, secured_client); unsigned long bot_lasttime = 0; const unsigned long BOT_MTBS = 1000; // Poll every 1 second void setup() { Serial.begin(115200); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); secured_client.setTrustAnchors(&cert); configTime(0, 0, "pool.ntp.org"); // Required for SSL while (WiFi.status() != WL_CONNECTED) { delay(500); } Serial.println("Connected to WiFi"); } void loop() { if (millis() - bot_lasttime > BOT_MTBS) { int numNewMessages = bot.getUpdates(bot.last_message_received + 1); for (int i = 0; i < numNewMessages; i++) { String chat_id = bot.messages[i].chat_id; String text = bot.messages[i].text; String from_name = bot.messages[i].from_name; Serial.printf("Message from %s: %s\n", from_name.c_str(), text.c_str()); } bot_lasttime = millis(); } } ``` -------------------------------- ### Handle Callback Queries and Edit Messages - Arduino C++ Source: https://context7.com/witnessmenow/universal-arduino-telegram-bot/llms.txt This Arduino C++ code snippet shows how to handle callback queries from inline keyboards and edit existing messages. It parses incoming messages, identifies callback queries, and responds accordingly. It includes logic to answer callback queries, send alerts, and use `sendMessageWithInlineKeyboard` to either send a new message with a keyboard or edit an existing one by providing the `message_id`. ```cpp void handleNewMessages(int numNewMessages) { for (int i = 0; i < numNewMessages; i++) { String chat_id = bot.messages[i].chat_id; String text = bot.messages[i].text; int message_id = bot.messages[i].message_id; if (bot.messages[i].type == "callback_query") { String callback_data = text; String query_id = bot.messages[i].query_id; // Answer callback query with optional alert if (callback_data == "delete") { bot.answerCallbackQuery(query_id, "Delete confirmed!", true); bot.sendMessage(chat_id, "Item deleted", ""); } else if (callback_data == "edit") { bot.answerCallbackQuery(query_id); // Edit the original message String newKeyboard = "[[{\"text\":\"Saved\",\"callback_data\":\"saved\"}]]"; bot.sendMessageWithInlineKeyboard( chat_id, "Message updated!", "", newKeyboard, message_id // Provide message_id to edit existing message ); } else { bot.answerCallbackQuery(query_id, "Processing...", false); } } else if (text == "/menu") { String keyboard = "[[{\"text\":\"Edit\",\"callback_data\":\"edit\"}," + "{\"text\":\"Delete\",\"callback_data\":\"delete\"}]]"; bot.sendMessageWithInlineKeyboard(chat_id, "Select action:", "", keyboard); } } } ``` -------------------------------- ### Send Text Messages with Formatting Source: https://context7.com/witnessmenow/universal-arduino-telegram-bot/llms.txt Sends text messages to a specified chat ID, supporting Markdown or HTML for rich text formatting. This function handles different commands like /start and /status, responding with formatted messages or error notifications. It relies on the bot instance and the chat_id of the incoming message. ```cpp void handleCommand(String chat_id, String text) { if (text == "/start") { String welcome = "Welcome! Available commands:\n"; welcome += "/help - Show this help message\n"; welcome += "/status - Get current status\n"; // Send with Markdown formatting bool sent = bot.sendMessage(chat_id, welcome, "Markdown"); if (!sent) { Serial.println("Failed to send message"); } } else if (text == "/status") { String status = "*System Status*\n\n"; status += "Uptime: " + String(millis() / 1000) + " seconds\n"; status += "Free heap: " + String(ESP.getFreeHeap()) + " bytes\n"; bot.sendMessage(chat_id, status, "Markdown"); } else { bot.sendMessage(chat_id, "Unknown command. Type /start for help.", ""); } } void loop() { if (millis() - bot_lasttime > BOT_MTBS) { int numNewMessages = bot.getUpdates(bot.last_message_received + 1); for (int i = 0; i < numNewMessages; i++) { handleCommand(bot.messages[i].chat_id, bot.messages[i].text); } bot_lasttime = millis(); } } ``` -------------------------------- ### Send Reply Keyboard with Arduino Source: https://github.com/witnessmenow/universal-arduino-telegram-bot/blob/master/README.md This function sends a reply keyboard to a specified chat. Reply keyboards act as a menu for users. It supports optional parameters for resizing the keyboard, making it a one-time use, and making it selective. The function returns true upon successful message transmission. ```Arduino bool sendMessageWithReplyKeyboard(String chat_id, String text, String parse_mode, String keyboard, bool resize = false, bool oneTime = false, bool selective = false) ``` -------------------------------- ### Set Bot Commands Programmatically - Arduino Source: https://github.com/witnessmenow/universal-arduino-telegram-bot/blob/master/README.md This snippet demonstrates how to programmatically set bot commands for your Telegram bot using the Universal Arduino Telegram Bot library. These commands will appear in the Telegram client's text input area, providing users with quick access to bot functionalities. Ensure your bot object is properly initialized before calling this method. ```arduino bot.setMyCommands("[{\"command\":\"help\", \"description\":\"get help\"},{\"command\":\"start\",\"description\":\"start conversation\"}]"); ``` -------------------------------- ### Send Chat Actions with Arduino Telegram Bot Source: https://context7.com/witnessmenow/universal-arduino-telegram-bot/llms.txt Demonstrates how to send chat action indicators like 'typing...' or 'upload_photo' to the user. This improves the user experience by showing that the bot is processing a request. It requires the `bot.sendChatAction()` function from the Arduino Telegram Bot library. The function takes the chat ID and the action type as arguments. ```cpp void sendChatActionExample(String chat_id) { // Show "typing..." indicator bot.sendChatAction(chat_id, "typing"); delay(2000); // Simulate processing time bot.sendMessage(chat_id, "Processing complete!", ""); } void handleLongOperation(String chat_id, String text) { if (text == "/analyze") { // Show typing indicator during analysis bot.sendChatAction(chat_id, "typing"); // Perform long operation int result = 0; for (int i = 0; i < 1000000; i++) { result += i; } bot.sendMessage(chat_id, "Analysis result: " + String(result), ""); } else if (text == "/photo") { // Show upload_photo indicator bot.sendChatAction(chat_id, "upload_photo"); delay(3000); // Simulate photo capture/processing sendPhotoFromURL(chat_id); } else if (text == "/location") { // Available actions: typing, upload_photo, record_video, // upload_video, record_audio, upload_audio, upload_document, // find_location, record_video_note, upload_video_note bot.sendChatAction(chat_id, "find_location"); delay(2000); bot.sendMessage(chat_id, "Location: 40.7128° N, 74.0060° W", ""); } } ``` -------------------------------- ### Send Chat Actions with Arduino Source: https://github.com/witnessmenow/universal-arduino-telegram-bot/blob/master/README.md This function allows the bot to send chat actions like 'typing' or 'sending photo' to inform the user about the bot's current activity. A predefined list of supported chat actions is available in the Telegram API documentation. The function returns true if the action is sent successfully. ```Arduino bool sendChatAction(String chat_id, String chat_action) ``` -------------------------------- ### Send Inline Keyboard with Arduino Source: https://github.com/witnessmenow/universal-arduino-telegram-bot/blob/master/README.md This function sends an inline keyboard to a specified chat. Inline keyboards support URLs and callbacks. The parse_mode can be left blank. The function returns true if the message is sent successfully. ```Arduino bool sendMessageWithInlineKeyboard(String chat_id, String text, String parse_mode, String keyboard) ``` -------------------------------- ### Receiving Messages API Source: https://github.com/witnessmenow/universal-arduino-telegram-bot/blob/master/README.md This API allows your bot to read messages sent to it, useful for sending commands to your Arduino. It retrieves pending messages from Telegram and stores them. ```APIDOC ## Receiving Messages ### Description Your bot can read messages that are sent to it. This is useful for sending commands to your arduino such as toggle and LED. ### Method GET ### Endpoint `/getUpdates` ### Parameters #### Query Parameters - **offset** (long) - Required - Offset should be set to **bot.last_message_received** + 1. ### Request Example ```json { "message": "No request body needed for this operation" } ``` ### Response #### Success Response (200) - **messages_received** (int) - The number of new messages received. #### Response Example ```json { "messages_received": 5 } ``` ``` -------------------------------- ### Sending Messages API Source: https://github.com/witnessmenow/universal-arduino-telegram-bot/blob/master/README.md This API enables your bot to send messages to any Telegram chat or group, useful for event notifications from your Arduino. Bots can only message users who have messaged them first. ```APIDOC ## Sending Messages ### Description Your bot can send messages to any Telegram or group. This can be useful to get the arduino to notify you of an event e.g. Button pressed etc (Note: bots can only message you if you messaged them first). ### Method POST ### Endpoint `/sendMessage` ### Parameters #### Request Body - **chat_id** (String) - Required - The unique identifier for the target chat. - **text** (String) - Required - The text message to send. - **parse_mode** (String) - Optional - Mode for parsing entities in the message text (e.g., "MarkdownV2", "HTML"). ### Request Example ```json { "chat_id": "123456789", "text": "Hello from Arduino!", "parse_mode": "HTML" } ``` ### Response #### Success Response (200) - **sent_successfully** (bool) - Indicates if the message was sent successfully. #### Response Example ```json { "sent_successfully": true } ``` ``` -------------------------------- ### Arduino: Receive Telegram Messages Source: https://github.com/witnessmenow/universal-arduino-telegram-bot/blob/master/README.md This feature allows your Arduino bot to read incoming messages from Telegram, enabling command functionalities like toggling LEDs. It uses the `getUpdates` function, which requires an offset to retrieve new messages and stores them in `bot.messages`. The function returns the count of newly received messages. ```Arduino int getUpdates(long offset) ``` -------------------------------- ### Handle Location Data with Arduino Telegram Bot Source: https://context7.com/witnessmenow/universal-arduino-telegram-bot/llms.txt This function processes incoming messages to detect and handle shared location data, including single points and live location updates. It extracts latitude and longitude, formats a message with location details and a Google Maps link, and calculates the distance from a reference point using the Haversine formula. This requires functions for parsing message data and a `calculateDistance` function. ```cpp void handleNewMessages(int numNewMessages) { for (int i = 0; i < numNewMessages; i++) { String chat_id = bot.messages[i].chat_id; // Check if message contains location if (bot.messages[i].longitude != 0 && bot.messages[i].latitude != 0) { float lat = bot.messages[i].latitude; float lon = bot.messages[i].longitude; Serial.printf("Received location: %f, %f\n", lat, lon); String locationMsg = "Your location:\n"; locationMsg += "Latitude: " + String(lat, 6) + "\n"; locationMsg += "Longitude: " + String(lon, 6) + "\n"; locationMsg += "Google Maps: https://maps.google.com/?q=" + String(lat, 6) + "," + String(lon, 6); bot.sendMessage(chat_id, locationMsg, ""); // Calculate distance from reference point float refLat = 40.7128; float refLon = -74.0060; float distance = calculateDistance(lat, lon, refLat, refLon); bot.sendMessage(chat_id, "Distance from NYC: " + String(distance) + " km", ""); } } } float calculateDistance(float lat1, float lon1, float lat2, float lon2) { // Haversine formula for distance calculation float dLat = radians(lat2 - lat1); float dLon = radians(lon2 - lon1); float a = sin(dLat/2) * sin(dLat/2) + cos(radians(lat1)) * cos(radians(lat2)) * sin(dLon/2) * sin(dLon/2); float c = 2 * atan2(sqrt(a), sqrt(1-a)); return 6371 * c; // Earth radius in km } ``` -------------------------------- ### Enable Long Polling for Reduced Network Load - Arduino C++ Source: https://context7.com/witnessmenow/universal-arduino-telegram-bot/llms.txt This Arduino C++ code snippet demonstrates how to enable long polling for the Telegram bot. Long polling keeps a single connection open, reducing network requests and improving responsiveness. It involves setting the `longPoll` and `waitForResponse` parameters of the bot object. The `loop` function checks for new messages less frequently due to the nature of long polling. ```cpp void setup() { Serial.begin(115200); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); secured_client.setTrustAnchors(&cert); configTime(0, 0, "pool.ntp.org"); while (WiFi.status() != WL_CONNECTED) { delay(500); } // Enable long polling - wait up to 60 seconds for new messages bot.longPoll = 60; // Adjust response timeout (default 1500ms) bot.waitForResponse = 2000; Serial.println("Long polling enabled"); } void loop() { // With long polling, check less frequently // The bot will wait on the server side for messages if (millis() - bot_lasttime > 5000) { // Check every 5 seconds int numNewMessages = bot.getUpdates(bot.last_message_received + 1); if (numNewMessages) { Serial.printf("Received %d messages\n", numNewMessages); handleNewMessages(numNewMessages); } bot_lasttime = millis(); } // Other non-blocking code can run here yield(); } ``` -------------------------------- ### Arduino: Send Telegram Messages Source: https://github.com/witnessmenow/universal-arduino-telegram-bot/blob/master/README.md This feature enables your Arduino bot to send messages to Telegram chats or groups, useful for notifications like button presses. The `sendMessage` function is used for this purpose, requiring a chat ID and the message text. An optional `parse_mode` parameter can be included. The function returns a boolean indicating success. ```Arduino bool sendMessage(String chat_id, String text, String parse_mode = "") ``` -------------------------------- ### Arduino Telegram Bot: Configure Long Polling Source: https://github.com/witnessmenow/universal-arduino-telegram-bot/blob/master/README.md This snippet explains how to configure the long polling interval for an Arduino Telegram bot. Setting a longer interval reduces the number of requests and data usage but ties up the Arduino during the wait period. The value represents the duration in seconds. ```arduino bot.longPoll = 60; // Where 60 is the amount of seconds it should wait ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.