如果出现循环中断,为什么 discord.py bot 会发送多条消息?
Why does discord.py bot sends multiple messages if there is a break out of loop?
我的 discord.py 机器人用于在分配给该特定服务器的 SQLite3 数据库中的流媒体上线时在“流媒体”文本频道中发送通知。问题是当循环中断时,bot 会发送多条通知消息(实际上正好等于 channel.history 限制)。什么可能导致此问题?
P/S:不要介意我这 79 行以上的代码,当我完成逻辑后它们会得到修复。
def _checkuser(user: str) -> dict | None:
"""Запрос к Twitch с проверкой, стримит ли указанный пользователь."""
stream = requests.get(
'https://api.twitch.tv/helix/streams?user_login=' + user,
headers=TWITCH_HEADERS,
)
stream_data = stream.json()
if len(stream_data['data']) == 1:
return stream_data['data'][0]
else:
return None
@bot.event
async def on_ready() -> None:
"""Обработчик события при запуске бота."""
@tasks.loop(seconds=10)
async def live_notification_loop() -> None:
"""Луп проверки стримеров."""
for guild in bot.guilds:
cursor.execute(
f'SELECT id, name FROM streamers WHERE server_id = {guild.id}'
)
streamers = cursor.fetchmany()
if streamers is not None:
channel: discord.TextChannel = discord.utils.get(
guild.channels,
name='streamers',
)
for user_id, name in streamers:
status = _checkuser(name)
user = bot.get_user(user_id)
if status:
# messages = await channel.history(limit=200).flatten()
# for message in messages:
async for message in channel.history(limit=10):
if str(user.mention) in message.content:
break
else:
ALERT_MSG = '{streamer} запустил трансляцию. Не пропустите!'
ALERT_EMBED = discord.Embed(
title=EMBED_TITLE,
description=f'{status["user_name"]} играет в {status["game_name"]} для {status["viewer_count"]} зрителей.',
url=f'https://twitch.tv/{status["user_name"]}',
colour=0x6441A5,
timestamp=datetime.utcnow(),
)
ALERT_EMBED.set_author(
name=f'{status["user_name"]} запустил трансляцию на Twitch.',
url=f'https://twitch.tv/{status["user_name"]}'
)
ALERT_EMBED.set_image(
url=status["thumbnail_url"].format(
width=640,
height=360,
)
)
await channel.send(
ALERT_MSG.format(
streamer=user.mention
),
embed=ALERT_EMBED,
)
live_notification_loop.start()
在 await.send 之后添加了中断,现在一条通知消息。
我的 discord.py 机器人用于在分配给该特定服务器的 SQLite3 数据库中的流媒体上线时在“流媒体”文本频道中发送通知。问题是当循环中断时,bot 会发送多条通知消息(实际上正好等于 channel.history 限制)。什么可能导致此问题?
P/S:不要介意我这 79 行以上的代码,当我完成逻辑后它们会得到修复。
def _checkuser(user: str) -> dict | None:
"""Запрос к Twitch с проверкой, стримит ли указанный пользователь."""
stream = requests.get(
'https://api.twitch.tv/helix/streams?user_login=' + user,
headers=TWITCH_HEADERS,
)
stream_data = stream.json()
if len(stream_data['data']) == 1:
return stream_data['data'][0]
else:
return None
@bot.event
async def on_ready() -> None:
"""Обработчик события при запуске бота."""
@tasks.loop(seconds=10)
async def live_notification_loop() -> None:
"""Луп проверки стримеров."""
for guild in bot.guilds:
cursor.execute(
f'SELECT id, name FROM streamers WHERE server_id = {guild.id}'
)
streamers = cursor.fetchmany()
if streamers is not None:
channel: discord.TextChannel = discord.utils.get(
guild.channels,
name='streamers',
)
for user_id, name in streamers:
status = _checkuser(name)
user = bot.get_user(user_id)
if status:
# messages = await channel.history(limit=200).flatten()
# for message in messages:
async for message in channel.history(limit=10):
if str(user.mention) in message.content:
break
else:
ALERT_MSG = '{streamer} запустил трансляцию. Не пропустите!'
ALERT_EMBED = discord.Embed(
title=EMBED_TITLE,
description=f'{status["user_name"]} играет в {status["game_name"]} для {status["viewer_count"]} зрителей.',
url=f'https://twitch.tv/{status["user_name"]}',
colour=0x6441A5,
timestamp=datetime.utcnow(),
)
ALERT_EMBED.set_author(
name=f'{status["user_name"]} запустил трансляцию на Twitch.',
url=f'https://twitch.tv/{status["user_name"]}'
)
ALERT_EMBED.set_image(
url=status["thumbnail_url"].format(
width=640,
height=360,
)
)
await channel.send(
ALERT_MSG.format(
streamer=user.mention
),
embed=ALERT_EMBED,
)
live_notification_loop.start()
在 await.send 之后添加了中断,现在一条通知消息。