【问题标题】:Pinging a website with discord bots in python在 python 中使用不和谐的机器人 ping 一个网站
【发布时间】:2018-01-22 06:45:37
【问题描述】:

我正在用 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 命令时,该机器人确实可以工作,因此它不是不和谐的连接,运行程序时也没有出现错误。

【问题讨论】:

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


    【解决方案1】:

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

    在 on_ready 函数中,需要添加:

    client.loop.create_task(my_background_task())
    

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

    Example code

    【讨论】:

    • 谢谢@squaswin,但它似乎仍然没有运行循环......我已经设法通过将代码放入 on_ready 触发器来使其工作,但我仍然希望它工作作为后台任务。一个想法:该代码正在创建一个循环,但它是否告诉客户端运行它?
    • 能否在您的问题中向我们展示您编辑的代码?
    • 通过创建任务,您要求 asyncio 尽可能运行代码。由于代码是由 asyncio 作为后台任务运行的,所以只要客户端已连接——并且 while 循环不会引发未捕获的异常——客户端就会运行它。
    猜你喜欢
    • 1970-01-01
    • 2021-09-17
    • 2020-07-25
    • 2021-05-17
    • 2021-05-24
    • 1970-01-01
    • 2022-06-12
    • 1970-01-01
    • 2021-10-30
    相关资源
    最近更新 更多