我正在用 python 制作一个不和谐的机器人,我一直在尝试让它 ping 一个网站,然后判断它是打开还是关闭。 这是我的代码:
import logging
logging.basicConfig(level=logging.INFO)
import discord
from discord.ext import commands
import os
website = "mywebsite.com"
des = "a website status bot"
prefix = "."
client = commands.Bot(description=des, command_prefix=prefix)
async def my_background_task():
await client.wait_until_ready()
channel = discord.Object(id='my server id went here')
response = 0
while not client.is_closed:
print("loop") #debugger
await asyncio.sleep(10)
global response
pr = response
response = os.system("ping -c 1 " + website)
if response != 0:
response = 1
if pr != response:
if response == 0:
await client.send_message(channel, 'mywebsite is up!')
else:
await client.send_message(channel, 'mywebsite is down!')
client.run("discord-bot-code-went-here")
由于某种原因,它没有运行循环。有什么想法吗?
谢谢。
旁注:当我尝试用它执行 ping pong 命令时,该机器人确实工作了,所以它不是不和谐的连接,运行程序时也没有出现错误。
最佳答案
您没有告诉循环开始运行此任务。
在 on_ready 函数中,您需要添加:
client.loop.create_task(my_background_task())
这应该启动后台任务,并且作为在 on_ready 中启动它的额外好处,您不再需要等到准备就绪。
关于python - 用 python 来 Ping 一个带有不和谐机器人的网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45674339/