python - 用 python 来 Ping 一个带有不和谐机器人的网站

标签 python python-3.x discord discord.py

我正在用 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 中启动它的额外好处,您不再需要等到准备就绪。

Example code

关于python - 用 python 来 Ping 一个带有不和谐机器人的网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45674339/

相关文章:

python - switch_to_alert.text() 不起作用

python - 我正在尝试将数据框插入本地 MySQL 数据库

python - ytdl python "KeyError: formats"

python - 在 Pandas 中保存 csv 文件时如何添加交替空行

python-3.x - 从一个单词中获取所有可能的 pos 标签

python - 四舍五入到最接近的百位时,如何包含 0

python - 字典在 python 3 中不可订购?

python - 列出没有共同公会的 friend ,discord.py 重写

python - Discord.py purge 命令中的人员列表和已删除消息数

python - 根据条件合并 Dataframe 行