1

I am trying to make my Discord bot ping a server and reply “{time} ms” but failed. I searched google but all the codes are just replying “Network Active” or “Network Error”.

Here is my code (Copied on Stack Overflow)(I use linux as server so I use “-c 1 ”

import os
@commands.command()
async def ping(self, ctx, ip):
    host = ip
    response = os.system(“ping “ + “-c 1 ” + host)
    if response == 0:
        ping_status = “Network Active”
    else:
        ping_status = “Network Error”
    await ctx.send(ping_status)
Adrian0811
  • 13
  • 2

1 Answers1

3

you can use this code to get times returned by ping.

import re
import subprocess

output = subprocess.check_output(['ping', '-c', '5', 'google.com'])
output = output.decode('utf-8').splitlines()
times = []
for o in output:
    m = re.search(r'time=([\d]+\.?[\d]*)', o)
    if m:
        times.append(m.group(1))
print(times)

you should save output of ping, and then extract times with the aim of regex.

Fatemeh Karimi
  • 914
  • 2
  • 16
  • 23
  • 2
    Considering that the OP is using `asyncio`, [`create_subprocess_exec`](https://docs.python.org/3/library/asyncio-subprocess.html#creating-subprocesses) might be a better choice. – bereal Jun 30 '20 at 06:34