python - 有没有办法阻止不和谐位运行此代码?
问题描述
Heyyyyy 我正在制作一个不和谐的机器人,它里面有一个 !kill 命令。你会像这样使用它:
!kill MySecretCode !yes 或 !no 有没有办法在我执行 !no 后阻止代码监听 !yes 函数?这是代码(Python):
@client.command()
@commands.has_any_role("Server Owner")
async def kill(ctx, code):
if code == "MySecretCode":
channel = discord.utils.get(ctx.author.guild.text_channels, name="new-channel")
emb = discord.Embed(color=discord.Color.orange(), title="**Terminate Bot?**",description=f"Are you sure you want to terminate this bot?\nTo continue with termination, type '!yes'.\nTo cancel the termination, type '!no'.")
await channel.send(embed=emb)
@client.command()
async def yes(ctx):
channel = discord.utils.get(ctx.author.guild.text_channels, name="new-channel")
emb = discord.Embed(color=discord.Color.red(), title="**Terminating**",description=f"Process terminating...")
await channel.send(embed=emb)
await client.close()
print("Bot terminated")
@client.command()
async def no(ctx):
channel = discord.utils.get(ctx.author.guild.text_channels, name="new-channel")
emb = discord.Embed(color=discord.Color.green(), title="**Termination Canceled**",description=f"You canceled the termination process")
await channel.send(embed=emb)
解决方案
您应该考虑使用wait_for
discord.py 中针对这种情况制作的函数。wait_for
是一个事件函数,它将返回匹配“检查规则”的下一条发送消息。它只会返回或收听 1 条消息。返回消息对象后,事件将结束。
@client.command()
@commands.has_any_role("Server Owner")
async def kill(ctx, code):
def check_rule(message: discord.Message): # Checks if the author is the sender that triggered the !kill command.
return message.author.id == ctx.message.author.id
if code == "MySecretCode":
channel = discord.utils.get(ctx.author.guild.text_channels, name="new-channel")
emb = discord.Embed(color=discord.Color.orange(), title="**Terminate Bot?**",description=f"Are you sure you want to terminate this bot?\nTo continue with termination, type '!yes'.\nTo cancel the termination, type '!no'.")
await channel.send(embed=emb)
try:
# timeout after 10 seconds
answer = (await client.wait_for('message', check=check_rule, timeout=10)).content
except (asyncio.exceptions.TimeoutError,
discord.ext.commands.errors.CommandInvokeError):
await ctx.send("Took too long to answer.")
return
if answer == '!yes':
# turn off the bot
elif answer == '!no':
# don't turn off
else:
# invalid answer
推荐阅读
- google-cloud-dataflow - 使用云函数触发数据流(Python SDK)作业
- javascript - 需要将 gpa 计算器与 HTML 中的可填写表格相关联
- rust - 为什么在实现相同的特征时,Rust 可以接受不同的结构?
- android - 如何使用 FileProvider 和 EncryptedFile?
- javascript - 使用设置间隔函数制作动画
- node.js - 当我处理错误时,NodeJS 抛出 UnhandledPromiseRejectionWarning
- android - Android 推送通知服务器实现
- javascript - 连接MongoDB Native Driver Node JS的正确方法
- javascript - 如何使用 Javascript 加载单独的 .html 页面
- python - 为什么从 google_screener_data_extract 导入 GoogleStockDataExtract 时出现 SyntaxError: invalid syntax