我有一个背景循环,每隔X分钟就会吐出一个表情符号,并带有反应。我希望有人按下消息的响应时,它将删除该消息,然后发送另一条消息,说“消息作者已抓住战利品”,然后将金额添加到现金json文件中。
现在,我的代码正在使后台循环正常工作,但是我不确定如何获取有关后台循环的message.author.id,因此我可以在on_reaction_add中引用它。当前代码使机器人在退出后台循环时做出一次反应,然后在on_reaction_add中再次做出反应。我试图让它等待用户使用相同的表情符号而不是漫游器对后台循环消息做出反应。
client = discord.Client()
emoji_msg_grab = {}
try:
with open("cash.json") as fp:
cash = json.load(fp)
except Exception:
cash = {}
def save_cash():
with open("cash.json", "w+") as fp:
json.dump(cash, fp, sort_keys=True, indent=4)
def add_dollars(user: discord.User, dollars: int):
id = user.id
if id not in cash:
cash[id] = {}
cash[id]["dollars"] = cash[id].get("dollars", 0) + dollars
print("{} now has {} dollars".format(user.name, cash[id]["dollars"]))
save_cash()
async def background_loop():
await client.wait_until_ready()
while not client.is_closed:
channel = client.get_channel("479919577279758340")
emojigrab = ''
emojimsgid = await client.send_message(channel, emojigrab)
await client.add_reaction(emojimsgid, "")
user_id = emojimsgid.author.id
emoji_msg_grab[user_id] = {"emoji_msg_id": emojimsgid.id, "emoji_user_id": user_id}
await asyncio.sleep(600)
@client.event
async def on_reaction_add(reaction, user):
msgid = reaction.message.id
chat = reaction.message.channel
if reaction.emoji == "" and msgid == emoji_msg_grab[user.id]["emoji_msg_id"] and user.id == emoji_msg_grab[user.id]["emoji_user_id"]:
emoji_msg_grab[user.id]["emoji_msg_id"] = None
await client.send_message(chat, "{} has grabbed the loot!".format(user.mention))
await client.delete_message(reaction.message)
add_dollars(user, 250)
client.loop.create_task(background_loop())
答案 0 :(得分:1)
我将使用Client.wait_for_reaction
而不是on_reaction_add
:
async def background_loop():
await client.wait_until_ready()
channel = client.get_channel("479919577279758340")
while not client.is_closed:
emojigrab = ''
emojimsg = await client.send_message(channel, emojigrab)
await client.add_reaction(emojimsg, "")
res = await client.wait_for_reaction(emoji="", message=emojimsg, timeout=600,
check=lambda reaction, user: user != client.user)
if res: # not None
await client.delete_message(emojimsg)
await client.send_message(channel, "{} has grabbed the loot!".format(res.user.mention))
await asyncio.sleep(1)
add_dollars(res.user, 250)