这是我想出的代码。 它运行并发送消息“服务器离线”,但它并未离线。 我也尝试过使用 ping 命令,但似乎也不起作用。 想知道我是否缺少一个库来运行这些函数或一些可以解决问题的代码,或者是否只是服务器拒绝我的 ping 和套接字连接。 我能够使用其他方法 ping 它,所以我认为情况并非如此。 有一次我让它在线显示,但当它离线时它没有发送通知,我不知道我做了什么才能实现这一点。
import os
import discord
import socket
import asyncio
TOKEN = os.environ['TOKEN']
CHANNEL_ID = 1170961716901855262
SERVER_IP = '5.62.122.45'
SERVER_PORT = 7783
client = discord.Client(intents=discord.Intents.all())
async def check_server_status():
prev_status = None
while True:
# Attempt to create a socket to the server on the specified port
try:
await client.wait_until_ready()
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(5)
s.connect((SERVER_IP, SERVER_PORT))
current_status = "online"
except (socket.timeout, ConnectionRefusedError):
current_status = "offline"
if current_status != prev_status:
prev_status = current_status
channel = client.get_channel(CHANNEL_ID)
await channel.send(f"Server is now {current_status}")
await asyncio.sleep(60) # Check the server status every 60 seconds
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
client.loop.create_task(check_server_status())
client.run(TOKEN)
我尝试了其他 IP 地址和端口,但它们都重新离线。我正在使用 replit,所以我不知道这是否是原因?
您可以添加 on_disconnect() 事件,当机器人与 Discord 服务器断开连接时将触发该事件。它是由discord.py库中的discord so实现的,当机器人与Discord服务器断开连接时会自动触发。
@client.event
async def on_disconnect():
channel = client.get_channel(CHANNEL_ID)
await channel.send("Server is now offline")