首页 > 解决方案 > 即使我希望机器人为一个人发送它,捐赠命令也会为所有流媒体发送相同的图片 | 不和谐.py

问题描述

我做了一个捐赠命令。但是,我想让它变得更好。

我在想这个:

  @commands.command()
  async def donate(self, ctx):
    await ctx.send("Aight, Who do you want to donate to?")
    streamer = await self.bot.wait_for('message', check=lambda message : message.author == ctx.author)
    await ctx.send(f"Ok, so you are donating to {streamer.content}. How much money you gonna donate?")
    amount = await self.bot.wait_for('message', check=lambda message : message.author == ctx.author)
    await ctx.send(f"Aight, you are donating ${amount.content} to {streamer.content}. What's the donatation message?")
    donation = await self.bot.wait_for('message', check=lambda message : message.author == ctx.author)
    await ctx.send(f"You have just donated ${amount.content} to {streamer.content} with the message: {donation.content}")
    if streamer.content == "CallMeCarson" or "callmecarson" or "carson":
      await ctx.send(file=discord.File("./Images/callmecarsoncrying.jpg"))
      return```
Im new to python, So sorry if this is very easy to do.

标签: discord.py

解决方案


问题在以下行:

if streamer.content == "CallMeCarson" or "callmecarson" or "carson":

这与以下含义相同:

if streamer.content == "CallMeCarson" or string == True or string == True:

python 中的非空字符串是truthy,所以它总是True& 传递,所以它总是适用于每个流媒体。

在 python 中使用andoror时,您需要重复您尝试比较的参数。

if streamer.content == "CallMeCarson" or streamer.content == "callmecarson" or streamer.content == "carson":

但这已经过时了,因为您可以将其转换为小写并检查是否carson在其中:

if "carson" in streamer.content.lower():

假设您计划为多个流媒体执行此操作,我建议您制作一个dict以避免 900 个 if 语句。您以后可以将所有其他名称和图像路径添加到此 dict 中。

streamers = {"carson": "callmecarsoncrying", "streamer2": "streamer2_image_name"}
for key in streamers:
    if key in streamer.content.lower():
        return await ctx.send(file=discord.File(f"./Images/{streamers[key]}.jpg"))

最后一行将发送消息,然后在找到匹配项时break退出循环(by returning),因此不会检查其他流媒体。这样,代码看起来更干净且更易于维护。


推荐阅读