SpeedTest Notification for Telegram: Difference between revisions

From AbahDoku Wiki
m 7 revisions imported
 
(No difference)

Latest revision as of 22:48, 19 November 2024

SpeedTest Notification for Telegram pada Armbian Server (Arm64)[edit]

Install Python dan Library Telegram Bot[edit]

Seperti biasa, selalu lakukan update sebelum menginstall paket yang diperlukan

sudo apt-get update

Install beberapa paket yang diperlukan

sudo apt-get install python3 python3-pip

Install

pip3 install python-telegram-bot

Buat file speedtest_bot.py[edit]

Script berikut baru di ujicoba pada Ubuntu Server 20.40 LTS.

Buat Script Python untuk menjalankan speedtest dan mengirimkan hsailnya ke telegram, simpan dalam file speedtest_bot.py

import asyncio
import subprocess
import telegram

BOT_TOKEN = 'ISI_BOT_TOKEN_ANDA'
CHAT_ID = 'ISI_CHAT_ID_ANDA'  # Masukkan ID chat Anda atau ID grup yang akan menerima laporan

bot = telegram.Bot(token=BOT_TOKEN)

async def run_speedtest():
    retries = 3
    for attempt in range(retries):
        result = subprocess.run(['speedtest', '--output-header'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = result.stdout.decode('utf-8'), result.stderr.decode('utf-8')
        if stderr:
            print(f"Attempt {attempt + 1} failed: {stderr}")
            if attempt < retries - 1:
                await asyncio.sleep(10)  # Wait for 10 seconds before retrying
            else:
                return None, stderr
        else:
            return stdout, None
    return None, "Max retries reached"

def format_result(result):
    try:
        lines = result.strip().split('\n')
        lines = [line.strip() for line in lines if line.strip()]

        server = lines[1].split(':', 1)[1].strip() if len(lines) > 1 else 'N/A'
        isp = lines[2].split(':', 1)[1].strip() if len(lines) > 2 else 'N/A'
        idle_latency = lines[3].split(':', 1)[1].strip() if len(lines) > 3 else 'N/A'
        download = lines[4].split(':', 1)[1].strip() if len(lines) > 4 else 'N/A'
        download_latency = lines[5].split(':', 1)[1].strip() if len(lines) > 5 else 'N/A'
        upload = lines[6].split(':', 1)[1].strip() if len(lines) > 6 else 'N/A'
        upload_latency = lines[7].split(':', 1)[1].strip() if len(lines) > 7 else 'N/A'
        packet_loss = lines[8].split(':', 1)[1].strip() if len(lines) > 8 else 'N/A'
        result_url = lines[9].split(':', 1)[1].strip() if len(lines) > 9 else 'N/A'

        formatted_result = f"""
*Speedtest by Ookla via Urang SEKURA*

*Server:* {server}
*ISP:* {isp}
*Idle Latency:* {idle_latency}
*Download:* {download}
*Download Latency:* {download_latency}
*Upload:* {upload}
*Upload Latency:* {upload_latency}
*Packet Loss:* {packet_loss}
*Result URL:* {result_url}
"""
    except Exception as e:
        formatted_result = f"Error formatting result: {e}"

    print("Formatted Result:", formatted_result)  # Debugging
    return formatted_result

async def send_report():
    stdout, stderr = await run_speedtest()
    if stderr:
        print("Speedtest Error:", stderr)
        await bot.send_message(chat_id=CHAT_ID, text=f"Speedtest Error: {stderr}", parse_mode='Markdown')
    else:
        formatted_result = format_result(stdout)
        await bot.send_message(chat_id=CHAT_ID, text=formatted_result, parse_mode='Markdown')
    print("Message sent")  # Debugging

async def main():
    while True:
        await send_report()
        await asyncio.sleep(300)  # Atur interval waktu (dalam detik) untuk mengirimkan laporan

if __name__ == '__main__':
    asyncio.run(main())

. . . . . ============> MASIH ADA LANJUTANNYA ---->> SHOLAT JUM'AT DULU

SpeedTest Notification for Telegram pada Ubuntu Server LTS 20.04[edit]