Discord.py购买数字商品反应确认功能多触发及取消功能问题求助
代码修改方案
核心修改点如下:
- 绑定反应与对应确认消息:在校验函数
check中新增对反应所属消息ID的匹配,避免多笔交易的反应互相干扰 - 新增取消反应支持:添加❌作为取消标识,同时在校验规则中允许匹配两种表情,收到反应后根据表情类型执行对应逻辑
- 保留
wait_for的实现方式,天然支持多服务器、多用户同时发起请求,不会互相冲突,无需使用全局on_reaction_add事件
修改后的完整代码:
@client.event async def on_message(message): channel = message.channel embedVar2 = discord.Embed(title="Item buying", description="<@"+ str(message.author.id) +"> Are you sure you want to buy " + str(conditions[1]) + " quantity of " + str(conditions[0]), color = 0x9A9B9D) embedVar2.add_field(name="\u200b", value= "It will cost $" + str(price) + " you will have $" + str(endbal) + " remaining \nReact with ✅ to confirm, ❌ to cancel", inline=False) # 补充原代码缺失的确认消息发送逻辑 confirm_message = await channel.send(embed=embedVar2) # 同时添加确认和取消两个反应 await confirm_message.add_reaction("✅") await confirm_message.add_reaction("❌") def check(reaction, user): # 新增消息ID校验,确保只捕获当前交易确认消息的反应 return reaction.message.id == confirm_message.id and user == message.author and str(reaction.emoji) in ['✅', '❌'] try: reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check) except asyncio.TimeoutError: # 超时取消逻辑 embedVar5 = discord.Embed(title="Money transfer", description="<@"+ str(message.author.id) +"> Are you sure you want to buy " + str(conditions[1]) + " quantity of " + str(conditions[0]), color = 0xFF0A26) embedVar5.add_field(name="\u200b", value= "It would have cost $" + str(price) + " you would have had $" + str(endbal) + " remaining \nTransaction canceled due to timeout", inline=False) await confirm_message.edit(embed = embedVar5) return else: # 根据用户点击的表情执行对应逻辑 if str(reaction.emoji) == '✅': # 交易确认逻辑 embedVar4 = discord.Embed(title="Money transfer", description="<@"+ str(message.author.id) +"> Are you sure you want to buy " + str(conditions[1]) + " quantity of " + str(conditions[0]), color = 0x77FF87) embedVar4.add_field(name="\u200b", value= "It will cost $" + str(price) + " you now have $" + str(endbal) + " remaining \nTransaction confirmed", inline=False) await confirm_message.edit(embed = embedVar4) # 此处可后续补充数字商品发货逻辑 else: # 用户主动取消逻辑 embedVar5 = discord.Embed(title="Money transfer", description="<@"+ str(message.author.id) +"> Are you sure you want to buy " + str(conditions[1]) + " quantity of " + str(conditions[0]), color = 0xFF0A26) embedVar5.add_field(name="\u200b", value= "It would have cost $" + str(price) + " you would have had $" + str(endbal) + " remaining \nTransaction canceled by user", inline=False) await confirm_message.edit(embed = embedVar5) return
内容的提问来源于stack exchange,提问作者noel puig
相关产品推荐
相关产品推荐

