使用python中的discord机器人ping一个网站

我在python中制作了一个discord bot,我一直试图让它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命令时,机器人确实工作,所以它不是与discord的连接,运行程序时也没有出现错误 .

回答(1)

2 years ago

您没有告诉循环开始运行此任务 .

在on_ready函数中,您需要添加:

client.loop.create_task(my_background_task())

这应该启动后台任务,并且作为在on_ready中启动它的额外奖励,您不再需要等到准备好了 .

Example code