SpeedTest Notification for Telegram: Difference between revisions

From AbahDoku Wiki
Line 5: Line 5:
  pip3 install python-telegram-bot
  pip3 install python-telegram-bot
== Buat file speedtest_bot.py ==
== Buat file speedtest_bot.py ==
Script berikut baru di ujicoba pada Ubuntu Server 20.40 LTS
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
Buat Script Python untuk menjalankan speedtest dan mengirimkan hsailnya ke telegram, simpan dalam file speedtest_bot.py
  import asyncio
  import asyncio

Revision as of 02:40, 9 August 2024

SpeedTest Notification for Telegram pada Armbian Server (Arm64)

Install Python dan Library Telegram Bot

sudo apt-get update
sudo apt-get install python3 python3-pip
pip3 install python-telegram-bot

Buat file speedtest_bot.py

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 = '1931317277:AAGRG4emfwGpsDnzgUt1fQ9Malk4ZeGPl_E'
CHAT_ID = '1952568357'  # 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 7 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())

SpeedTest Notification for Telegram pada Ubuntu Server LTS 20.04