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)
2
  • What's the error that you're getting? Commented Jun 30, 2020 at 6:13
  • @bereal the codes can run but i hope it can reply "{time} ms" Commented Jun 30, 2020 at 6:21

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Considering that the OP is using asyncio, create_subprocess_exec might be a better choice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.