Reputation: 3
I want to make discord bot which ping the minecraft server and: if server respond he edit lock voice channel name to "Server Status - Online". Else he edit channel name: "Server Status - Offline" I'm use mcstatus to ping the server and this work! But sometimes bot have lags and i don't know how fix it. P.s. Sorry for my bad english.
from mcstatus import MinecraftServer
import discord
from discord.ext import commands
import time
TOKEN = "token here"
client = discord.Client()
@client.event
async def on_ready():
print("Bot Connected")
await client.wait_until_ready()
channel = client.get_channel(id)
while True:
time.sleep(30)
try:
server = MinecraftServer.lookup("26.51.174.109:25565")
status = server.status()
await channel.edit(name = "Server Status - Online")
except:
await channel.edit(name = "Server Status - Offline")
client.run( TOKEN )
UPD: I rewrite the code, but problem not lost.
import discord
import asyncio
import time
import socket
TOKEN = "token"
client = discord.Client()
@client.event
async def on_ready():
print("Bot Connected")
await client.wait_until_ready()
channel = client.get_channel(id)
def ping(ip, port):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ip, int(port)))
return True
except:
return False
while True:
online = ping("26.51.174.109", "25565")
if online == True:
print("server online")
await channel.edit(name = "Server Status - Online")
else:
print("server offline")
await channel.edit(name = "Server Status - Offline")
await asyncio.sleep(5)
client.run( TOKEN )
Upvotes: 0
Views: 2019
Reputation: 375
mcstatus began offering asynchronous versions of functions as of version 4.1. Tacking on async_
is the way to use those. Replacing synchronous functions with asynchronous versions should help with hiccups. There could still be occasional network congestion that slows down the retrieval of information, and adjusting timeouts to lower numbers can help to skip over failed connections faster.
Instead of time.sleep
:
import asyncio
await asyncio.sleep(30)
Instead of server.status
:
from mcstatus import JavaServer
server = JavaServer("26.51.174.109", 25565, timeout=3)
status = await server.async_status()
Upvotes: 1