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)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.