背景循环与反应Discord.Py

问题描述 投票:0回答:1

我有一个背景循环,每隔X分钟吐出一个表情符号并附加一个反应。我想要当有人按下消息的反应时,它会删除消息,然后发送另一条消息说“messageauthor抓住了战利品”,然后将金额添加到现金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())
python python-3.x discord discord.py
1个回答
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)
© www.soinside.com 2019 - 2024. All rights reserved.