我目前正在开发一个购物车管理器,用户有机会获得赠品(先到先得)。基本上我会自动发布一些嵌入内容,第一个使用react的人将获得奖品和来自机器人的用 DM 编写的消息。第一名获得奖品的用户将获得5分钟的冷却时间(这样做的原因是同一用户不能在5分钟内获得二等奖)
我写过这样的东西:
# -*- coding: utf-8 -*-
import asyncio
from datetime import datetime
from discord import Client, Embed, Object
client = Client()
lock = asyncio.Lock()
PRIVATE_CHANNEL_ID = xxxxxxxxxxxxxx
PUBLIC_CHANNEL_ID = xxxxxxxxxxxxx
EMOJI_ID = "\N{SHOPPING TROLLEY}"
# ----------------------------------------------------- #
@client.event
async def on_ready():
print(f'{client.user.name} Logged In!')
@client.event
async def on_raw_reaction_add(payload):
if payload.channel_id == PUBLIC_CHANNEL_ID and '\U0001f6d2' == str(payload.emoji) and payload.user_id != client.user.id:
async with lock:
# Check if person is rate limited
我已经阅读了有关冷却映射的内容并找到了一个示例:
class SomeCog(commands.Cog):
def __init__(self):
self._cd = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)
async def cog_check(self, ctx):
bucket = self._cd.get_bucket(ctx.message)
retry_after = bucket.update_rate_limit()
if retry_after:
# you're rate limited
# helpful message here
pass
# you're not rate limited
但是我的问题是,我不知道如何为对给定 react 首先使用react的用户应用冷却时间,我想知道如何做到这一点?如何使用 CooldownMapping
对用户应用冷却时间,使其在接下来的 5 分钟内无法使用react?
最佳答案
您拥有的代码展示了如何在 cog 中的命令之间具有共同的速率限制,要对 on_raw_reaction_add
事件进行冷却,您需要不同的方法。
raw_reaction_add_cooldown = commands.CooldownMapping.from_cooldown(
1, 60.0, commands.BucketType.user # change rate and per accordingly
)
async def get_raw_reaction_add_ratelimit(payload: discord.RawReactionActionEvent) -> Optional[float]:
guild = client.get_guild(payload.guild_id)
channel = client.get_channel(payload.channel_id)
if guild is None or channel is None:
return None
author = guild.get_member(payload.user_id)
message = await channel.fetch_message(payload.message_id)
if author is None or message is None:
return None
# overwriting author attribute since otherwise it will check the ratelimit
# of the user who SENT the message, not the one that reacted
message.author = author
bucket = raw_reaction_add_cooldown.get_bucket(message)
return bucket.update_rate_limit()
使用它非常简单,调用该函数并检查None
@client.event
async def on_raw_reaction_add(payload):
ratelimit = await get_raw_reaction_add_ratelimit(payload)
if ratelimit is None:
print("NO RATELIMIT")
else:
print("RATELIMIT")
关于python - 如何为最先 react 的用户添加冷却映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71322042/