Bot继续执行循环的随机部分

时间:2020-04-17 05:44:23

标签: discord.py

我试图制造一个能够在检测到页面状态更改时发送消息的机器人,但是在3-5秒后,它会随机发送“服务器处于联机状态”,即使页面没有任何变化。

import os
import discord
from dotenv import load_dotenv
import time
import requests

def check(r):
    if "online" in r.text:
        return True
    else:
        return False

online = False

load_dotenv()
TOKEN = "#hidden"
GUILD = #hidden

client = discord.Client()

@client.event 
async def on_ready():
    for guild in client.guilds:
        if guild.name == GUILD:
            break
    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})')
    channel = client.get_channel(#hidden)

    last_status = check(requests.get("#page"))
    while True:
        if check(requests.get("#page")) == last_status:
            continue
        else:
            if check(requests.get(#page")):
                await channel.send("server is online")
                last_status = check(requests.get("#page"))
            else:
                await channel.send("Server is offline")
                last_status = check(requests.get("#page"))


client.run(TOKEN)

1 个答案:

答案 0 :(得分:0)

可能是因为您有on_ready函数的多个运行实例。

Discord API通常会发送一条重新连接指令(尤其是在由于流行病导致的过载期间)。
当discord.py收到此指令时,它将重新连接并再次调用on_ready,而不会杀死其他指令。

解决方案是使用asyncio.ensure_futureclient.wait_until_ready来确保只有一个实例

代码:

import os
import discord
from dotenv import load_dotenv
import time
import requests
import asyncio

def check(r):
    if "online" in r.text:
        return True
    else:
        return False

online = False

load_dotenv()
TOKEN = "#hidden"
GUILD = #hidden

client = discord.Client()

async def routine():
    await client.wait_until_ready()

    channel = client.get_channel(#hidden)    
    last_status = check(requests.get("#page"))

    while True:
        if check(requests.get("#page")) == last_status:
            continue
        else:
            if check(requests.get(#page")):
                await channel.send("server is online")
                last_status = check(requests.get("#page"))
            else:
                await channel.send("Server is offline")
                last_status = check(requests.get("#page"))


@client.event 
async def on_ready():
    for guild in client.guilds:
        if guild.name == GUILD:
            break
    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})')

asyncio.ensure_future(routine())
client.run(TOKEN)