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

问题描述 投票:1回答:1

我在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也没有在运行程序时出现错误。

python python-3.x discord discord.py
1个回答
2
投票

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

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

client.loop.create_task(my_background_task())

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

Example code

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.