Running a Speed test and Sending Results via Telegram Bot

Running a Speed test and Sending Results via Telegram Bot

Introduction

In an era where internet speed is crucial for work, entertainment, and daily communication, monitoring your internet performance can be quite beneficial. This blog post will guide you through setting up a simple script that runs a speed test on your connection and automatically sends the results to a Telegram chat. This setup is perfect for keeping track of your internet speed without manual intervention.

Installation Steps

Step 1: Install Speedtest CLI

First, ensure you have Python and pip installed on your system. If not, you can install them using:

sudo apt update
sudo apt install python3 python3-pip -y

Next, install the speedtest-cli using pip:

pip3 install speedtest-cli

Step 2: Create the Script

Copy and Paste the Script Content: (You will need to add your own BOT Token and Chat ID)

#!/bin/bash

# -------------------------------
# Internet Speed Test Script
# -------------------------------
# This script performs an internet speed test every hour and sends
# the results to a specified Telegram channel using MarkdownV2 formatting.
# -------------------------------

# -------------------------------
# Configuration
# -------------------------------

# Telegram Bot Token and Chat ID
# IMPORTANT: Replace these with your actual Bot Token and Chat ID.
BOT_TOKEN="ENTER TELEGRAM BOT TOKEN"
CHAT_ID="ENETER TELEGRAM CHAT ID"

# Path to speedtest-cli
SPEEDTEST_CMD="/usr/bin/speedtest-cli"

# Log File Path
LOG_FILE="$HOME/scripts/speedtest.log"

# -------------------------------
# Perform the Speed Test
# -------------------------------

# Check if speedtest-cli exists and is executable
if [ ! -x "$SPEEDTEST_CMD" ]; then
    echo "$(date +"%Y-%m-%d %H:%M:%S") - ERROR: speedtest-cli not found or not executable at $SPEEDTEST_CMD" >> "$LOG_FILE"
    exit 1
fi

# Perform the speed test and capture the output
SPEEDTEST_OUTPUT=$("$SPEEDTEST_CMD" --simple 2>&1)
SPEEDTEST_EXIT_CODE=$?

# Log the raw speedtest output
echo "$(date +"%Y-%m-%d %H:%M:%S") - Speedtest Output: $SPEEDTEST_OUTPUT" >> "$LOG_FILE"

if [ $SPEEDTEST_EXIT_CODE -ne 0 ]; then
    # Speed Test Failed
    CURRENT_TIME=$(date +"%H:%M:%S")  # Get only the time
    MESSAGE="*Internet Speed Test Failed*\nError: $SPEEDTEST_OUTPUT\nTime: $CURRENT_TIME"
else
    # Speed Test Succeeded
    # Extract the required metrics
    PING=$(echo "$SPEEDTEST_OUTPUT" | grep 'Ping' | awk '{print $2 " " $3}')
    DOWNLOAD=$(echo "$SPEEDTEST_OUTPUT" | grep 'Download' | awk '{print $2 " " $3}')
    UPLOAD=$(echo "$SPEEDTEST_OUTPUT" | grep 'Upload' | awk '{print $2 " " $3}')
    
    # Log the extracted metrics
    echo "$(date +"%Y-%m-%d %H:%M:%S") - Extracted Metrics - Ping: $PING | Download: $DOWNLOAD | Upload: $UPLOAD" >> "$LOG_FILE"

    # Escape reserved characters for MarkdownV2
    escape_md() {
        local input="$1"
        # Escape the special characters for MarkdownV2
        echo "$input" | sed -e 's/_/\\_/g' -e 's/\*/\\*/g' -e 's/\[/\\[/g' -e 's/\]/\\]/g' -e 's/~/\\~/g' -e 's/`/\\`/g' -e 's/-/\\-/g' -e 's/\./\\./g'
    }

    PING=$(escape_md "$PING")
    DOWNLOAD=$(escape_md "$DOWNLOAD")
    UPLOAD=$(escape_md "$UPLOAD")

    # Create the message with MarkdownV2 for bold labels and arrows
    CURRENT_TIME=$(date +"%H:%M:%S")  # Get only the time
    MESSAGE=$(printf "*Internet Speed Test Results*\n\n*Ping:* %s\n*Download:* ⬇️ %s\n*Upload:* ⬆️ %s\n*Time:* %s" "$PING" "$DOWNLOAD" "$UPLOAD" "$CURRENT_TIME")
fi

# -------------------------------
# Send the Message to Telegram
# -------------------------------

# Log the message before sending
echo "$(date +"%Y-%m-%d %H:%M:%S") - Preparing to send message: $MESSAGE" >> "$LOG_FILE"

# Send the message to Telegram with MarkdownV2 formatting
RESPONSE=$(curl -s -X POST "https://api.telegram.org/bot${BOT_TOKEN}/sendMessage" \
    -d chat_id="${CHAT_ID}" \
    -d text="${MESSAGE}" \
    -d parse_mode="MarkdownV2")

# Log the Telegram API response
echo "$(date +"%Y-%m-%d %H:%M:%S") - Telegram Response: $RESPONSE" >> "$LOG_FILE"

# Check for success or failure
if [[ $RESPONSE == *'"ok":true'* ]]; then
    echo "Message sent successfully"
else
    echo "Failed to send message"
fi

Save and exit. In nano, this would be CTRL + O to save, then CTRL + X to exit.

Create the Script File:

Open a text editor like nano or vim:

nano ~/scripts/speedtest_telegram.sh

Create a Directory for Scripts:

mkdir -p ~/scripts

Step 3: Make the Script Executable
Make your script executable:

chmod +x ~/scripts/speedtest_telegram.sh

Configuration
Create a Telegram Bot:

  • BotFather: Use Telegram's BotFather to create a bot and obtain the bot token.

Obtain Your Chat ID:

  • Chat ID: You'll need this to send messages. Here’s how you can get it:
    • Send a message to your bot and check the API response for your chat ID.
    • Alternatively, use GetIDBot to find your chat ID quickly.

Usage

Automated with Cron:
To automate the speed test, add a cron job. Open your crontab for editing:
bash

crontab -e


Add the following line to run the script every hour:
bash

0 * * * * ~/scripts/speedtest_telegram.sh

Manual Execution:
Run the script directly with:
bash

~/scripts/speedtest_telegram.sh

Conclusion

With these steps, you've automated the process of checking your internet speed and receiving notifications via Telegram, making it easier to monitor your connection's performance over time. Whether you're troubleshooting connectivity issues or just curious about your ISP's performance, this setup will provide you with timely and precise data directly to your device. Remember to tweak the script according to your specific needs or the specifics of your network setup. Enjoy your automated speed testing!