1
我在Python中犯了一個不和機器人,我一直試圖讓它ping一個網站,然後說它是否上漲或下跌。 這裏是我的代碼:Ping一個網站與Python中的不和機器人
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命令嘗試執行ping命令時,bot發揮了作用,所以它不是連接性不協調,運行程序時也沒有出現錯誤。
感謝@squaswin,但它似乎仍然沒有運行循環......我設法讓我的代碼,將其置於一個on_ready觸發工作,但我還是想它的工作作爲背景任務。一個想法:該代碼是創建一個循環,但它告訴客戶端運行它? –
你能向我們展示你的問題中的編輯代碼嗎? – xNinjaKittyx
通過創建該任務,您可以讓asyncio在可以時運行代碼。由於代碼由asyncio作爲後臺任務運行,因此只要客戶端連接 - 並且while循環不會拋出未捕獲的異常 - 客戶端將運行它。 – squaswin