我有下面的脚本,我想在其中循环发送消息到不和谐频道。 Discord 在循环内将消息发送到频道(因此它实际上在工作),但每次等待再次进入循环时我确实在循环内收到一些错误和警告(我应该每 60 秒进入循环一次)。
这里是我的脚本正文:
import discord
import asyncio
TOKEN = 'XXXXXXXXXXXXXXXXXXXXXXX'
channel_id = 111111111111111111111111
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
await send_message_in_loop()
async def send_message_in_loop():
channel = client.get_channel(channel_id)
while True:
try:
while True:
# ==================================================
# DOING SOME STUFF HERE INCDLUGING SOME "time.sleep"
# ==================================================
passedTime=SERVERTIME # the server time is being updated by server API
# I want to enter the loop when the seconds of the server time are within 3 to 6
if (passedTime)>3 and (passedTime)<6:
# ==================================================
# DOING SOME STUFF HERE INCDLUGING SOME "time.sleep"
# ==================================================
message='last check: '+str(SERVERTIME)
task = asyncio.get_event_loop().create_task(channel.send(message))
await asyncio.gather(task)
await asyncio.sleep(5)
except:
print('repeat')
client.run(TOKEN)
错误如下:
ERROR discord.client Attempting a reconnect in 0.59s
Traceback (most recent call last):
File "C:\Users\lt13485\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py",
line 659, in connect
await self.ws.poll_event()
File "C:\Users\lt13485\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\gateway.py", line 646, in poll_event
raise ConnectionClosed(self.socket, shard_id=self.shard_id, code=code) from None
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1000
我也收到以下警告:
WARNING discord.gateway Shard ID None heartbeat blocked for more than 10 seconds.
Loop thread traceback (most recent call last):
我很感激任何帮助!
我实际上希望不会在我的终端中收到错误,因为我已经在那里打印了一些东西
欢迎来到SO!在我的机器人中,我使用
@tasks.loop
装饰器处理定时循环:
from discord.ext import tasks
import discord
@tasks.loop(seconds=5.0, count=5) # get rid of count=5 for an infinite loop
async def slow_count():
print(slow_count.current_loop)
@slow_count.after_loop
async def after_slow_count():
print('done!')
我认为这是做这件事的标准,这对你来说可能很奇怪,因为他们构建的 API 就是这样工作的。
您的客户端陷入了 while True 循环,导致您的错误,因为它无法更新它的数据库,也无法尝试重新连接或做其他事情。
本质上,您在 while 循环中阻塞了不和谐线程,这是不应该的
为了实现你想要做的事情,你应该在 discord api 中使用一个函数,它允许你每隔 X 秒调用一个函数
@tasks.loop(seconds=5) // your timer
async def send_message_in_loop():
enter code here
另外,你需要告诉discord才能启动这个功能
@client.event
async def on_ready():
send_message_in_loop.start()