在 python 中使用 discord 机器人对网站执行 ping 操作

Pinging a website with discord bots in python

我正在 python 中制作一个 discord 机器人,我一直在尝试让它 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 的连接,当 运行 程序时也没有出现错误。

你没有告诉循环开始运行这个任务。

在一个on_ready函数中,你需要添加:

client.loop.create_task(my_background_task())

这应该会启动后台任务,作为在 on_ready 中启动它的额外好处,您不再需要等到准备就绪。

Example code