How to Set up Bidirectional SMS Integration with Telegram

How to Set up Bidirectional SMS Integration with Telegram

This guide describes how to set up bidirectional SMS integration with Telegram on a RobustOS Pro device. After setup, you'll be able to:
  1. Receive device SMS messages in your Telegram chat
  2. Send SMS from Telegram using simple commands

Prerequisites

  1. RobustOS Pro device with cellular connection
  2. Working SMS functionality (verify with sudo sms NUMBER "test message")
  3. Python 3.x (preinstalled on ROS PRO)

Step 1: Create Telegram Bot

  1. Open Telegram app
  2. Search for "@BotFather"
  3. Start chat and send /newbot command
  4. Choose a name for your bot
  5. Save the API token you receive (looks like 123456789:ABCdefGHIjklMNOpqrsTUVwxyz)

Step 2: Get Your Chat ID

  1. Start a chat with your new bot
  2. Send any message to the bot
  3. Open in browser: https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates
  4. Find your chat ID in the response (it's a number like 271084513)

Step 3: Install Required Package

sudo apt-get update
sudo apt-get install python3-requests

Step 4: Create Integration Script

Create a new file sms-telegram.py:
#!/usr/bin/env python3
import sys
import dbus
import requests
import subprocess
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib

class SMSMonitor:
    def __init__(self):
        # Initialize D-Bus
        DBusGMainLoop(set_as_default=True)
        self.bus = dbus.SystemBus()
        
        # Set up monitoring paths
        self.sms_path = '/org/freedesktop/ModemManager1/SMS'
        
        # Telegram settings
        self.token = "YOUR_BOT_TOKEN"  # Replace with your bot token
        self.chat_id = "YOUR_CHAT_ID"  # Replace with your chat ID
        self.last_update_id = 0
        
        # Monitor for new messages
        self.bus.add_signal_receiver(
            handler_function=self.on_message_added,
            signal_name='Added',
            dbus_interface='org.freedesktop.ModemManager1.Modem.Messaging',
            path='/org/freedesktop/ModemManager1/Modem/0'
        )
        
        # Add periodic check for Telegram messages
        GLib.timeout_add_seconds(2, self.check_telegram_messages)
        
        print("SMS Monitor started. Waiting for messages...")

    def on_message_added(self, path, received):
        try:
            if self.sms_path in path:
                # Get the SMS object
                sms_obj = self.bus.get_object('org.freedesktop.ModemManager1', path)
                props = sms_obj.GetAll('org.freedesktop.ModemManager1.Sms', 
                                     dbus_interface='org.freedesktop.DBus.Properties')
                
                # Format and display message
                if 'Text' in props and 'Number' in props:
                    # Console output
                    print("\n=== New SMS Message ===")
                    print(f"From: {props['Number']}")
                    print(f"Message: {props['Text']}")
                    if 'Timestamp' in props:
                        print(f"Time: {props['Timestamp']}")
                    print("=====================")
                    sys.stdout.flush()
                    
                    # Send to Telegram
                    message = f"=== New SMS Message ===\n"
                    message += f"From: {props['Number']}\n"
                    message += f"Message: {props['Text']}"
                    if 'Timestamp' in props:
                        message += f"\nTime: {props['Timestamp']}"
                    message += "\n====================="
                    
                    self.send_telegram_message(message)
                    
        except Exception as e:
            print(f"Error processing message: {str(e)}", file=sys.stderr)
            sys.stderr.flush()

    def check_telegram_messages(self):
        try:
            url = f"https://api.telegram.org/bot{self.token}/getUpdates"
            params = {'offset': self.last_update_id + 1, 'timeout': 1}
            response = requests.get(url, params=params).json()
            
            if response.get('ok'):
                for update in response['result']:
                    self.last_update_id = update['update_id']
                    
                    if 'message' in update and 'text' in update['message']:
                        text = update['message']['text'].lower()
                        if text.startswith('send sms to '):
                            parts = text[12:].split(' ', 1)
                            if len(parts) == 2:
                                number, message = parts
                                result = subprocess.run(['sudo', 'sms', number, message], 
                                                      capture_output=True, text=True)
                                if result.returncode == 0 and "OK" in result.stdout:
                                    self.send_telegram_message(f"✅ SMS sent to {number}")
                                else:
                                    self.send_telegram_message(f"❌ Failed to send SMS to {number}")
                            else:
                                self.send_telegram_message("❌ Invalid format. Use: send sms to NUMBER MESSAGE")
        except Exception as e:
            print(f"Error checking Telegram messages: {str(e)}")
        return True

    def send_telegram_message(self, message):
        url = f"https://api.telegram.org/bot{self.token}/sendMessage"
        data = {'chat_id': self.chat_id, 'text': message}
        try:
            requests.post(url, data=data)
        except Exception as e:
            print(f"Error sending to Telegram: {str(e)}")

    def run(self):
        try:
            loop = GLib.MainLoop()
            loop.run()
        except KeyboardInterrupt:
            print("\nMonitoring stopped")
            sys.exit(0)

if __name__ == '__main__':
    monitor = SMSMonitor()
    monitor.run()

Step 5: Configure

  1. Replace YOUR_BOT_TOKEN with your Telegram bot token
  2. Replace YOUR_CHAT_ID with your chat ID number

Step 6: Make Executable and Run

chmod +x sms-telegram.py
./sms-telegram.py

Usage

Receiving SMS

Any SMS received by your ROS PRO will automatically appear in your Telegram chat.

Sending SMS

To send an SMS, message your bot with:
send sms to NUMBER MESSAGE

Example:

send sms to +36707397959 Hello from Telegram

Run as System Service

1. Create service file:
sudo nano /etc/systemd/system/sms-telegram.service
2. Add content:
[Unit]
Description=SMS-Telegram Integration
After=network.target ModemManager.service

[Service]
ExecStart=/full/path/to/sms-telegram.py
Restart=always
User=your_username

[Install]
WantedBy=multi-user.target
3. Start service:
sudo systemctl enable sms-telegram
sudo systemctl start sms-telegram

Quick Troubleshooting

1. Test SMS sending:
sudo sms NUMBER "test"
2. Check if script is running:
ps aux | grep sms-telegram
3. View service logs:
journalctl -u sms-telegram -f


    • Related Articles

    • How to Integrate MQTT-Telegram Alarm

      This guide explains how to set up a system where your ROS PRO device acts as an MQTT broker and forwards alarm messages to Telegram. Prerequisites ROS PRO device with network connection Telegram account Step 1: Create Telegram Bot Open Telegram app ...
    • How to Enable RCMS via SMS

      Prerequisites 1. Device mobile number 2. Admin credentials 3. RCMS server details: Server IP/URL Port number Primary server IP for ping detection SMS Configuration Command Send the following SMS command to the device: admin:admin; set rcms enable ...
    • How to Set NTP via Command Line

      Understanding the Configuration Structure First, it's helpful to understand how to access the complete configuration structure: 1. You can download the XML configuration from: Web UI → System → Profile → XML Configuration File → Generate → Download ...
    • Can I activate the RCMS App via SMS?

      A: Yes, for devices already in the field it is possible to install and activate the RCMS App remotely using SMS
    • How to Set up RS422 Serial Connection

      1. Physical Connection Setup Hardware Requirements MOXA Uport 1150 device Serial cable RobustOS PRO device with RS422 interface Pinout Connections Connect the following pins between your devices: T+ → RX1+ T- → RX1- R+ (D+) → TX1+ R- (D-) → TX1- GND ...