首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Discord.py机器人:发送与爱人之间的两个人

Discord.py机器人:发送与爱人之间的两个人
EN

Code Review用户
提问于 2021-04-12 17:57:30
回答 2查看 1.1K关注 0票数 7

我正在创建一个不和谐的机器人,我做了一个!爱的命令,它是测试两个人或实体之间的爱率。

例句:!爱玛

结果:佩米斯蒂尔和艾玛之间的关系是x%。

下面是代码:

代码语言:javascript
复制
@bot.command(name="love", aliases=["l"])
async def love(ctx, Personne1, Personne2):
    if ctx.message.channel.id != 763352957579690018:
        printIt = 1
        wordBanList = ['@everyone', '@here', '<@&763489250162507809>','<@&777564025432965121>','<@&822200827347075132>',
                       '<@&763815680306184242>','<@&764422266560839680<','<@&763815728972300338>','<@&763815728972300338>',
                       '<@&763815228323528725>','<@&763815784904261632>','<@&764422166116171806>','<@&764422057353936897>',
                       '<@&804807279043674143>','<@&828664814678179861>','<@&823562218095640646>','<@&823638574809219163>']
        LoveRate = str(random.randrange(0, 100))
        for y in range(len(wordBanList)):
            if(Personne1 == wordBanList[y] or Personne2 == wordBanList[y]):
                printIt = 0

        if(printIt == 0):
            await ctx.send("Tu t'es pris pour qui ?")
            if debug == True:
                print("[DEBUG] !love : Someone tried to use a banned word !")
        else:
            await ctx.send("L'amour entre **"+Personne1+"** et **"+Personne2+"** est de **"+LoveRate+"%** <:flushed:830502924479758356>")
            if debug == True:
                print("[DEBUG] !love : The love rate ("+LoveRate+"%) between "+Personne1+" and "+Personne2+" has been printed in channel ID "+str(ctx.channel.id))
    else:
        botChannel = discord.utils.get(ctx.guild.channels, id=768194273970880533)
        messageBot = await ctx.send("Va faire cette commande dans "+botChannel.mention+" ou je te soulève <:rage:831149184895811614>")
        await asyncio.sleep(5)
        await ctx.message.delete()
        await messageBot.delete()

我很确定这段代码是可优化的,但我不知道怎么做,有人能帮我吗?)

EN

回答 2

Code Review用户

回答已采纳

发布于 2021-04-12 19:42:15

从不迭代python

中的索引。

在Python中,通常不推荐这种模式:

代码语言:javascript
复制
for y in range(len(wordBanList)):
    if(Personne1 == wordBanList[y] or Personne2 == wordBanList[y]):
        printIt = 0

您几乎不需要通过它们的索引来迭代和访问元素。相反,您应该直接迭代可迭代的元素:

代码语言:javascript
复制
for word in wordBanList:
    if Personne1 == word or Personne2 == word:
        printIt = 0

还请注意,您不需要or语句周围的括号。

如果您也需要索引,可以使用内置的enumerate

代码语言:javascript
复制
for index, word in enumerate(wordBanList):
    ...

成员资格测试

正如Harsha所指出的,sets是针对成员资格测试而优化的,所以在可能的情况下使用它们。这样做还可以使printIt的分配更加简洁:

代码语言:javascript
复制
wordBanList = {'@everyone', '@here', '<@&763489250162507809>', ...}
printIt = 0 if (Personne1 in wordBanList or Personne2 in wordBanList) else 1

这里也不需要副词,但可能会提高可读性。

命名约定

PEP 8

函数名应该是小写,必要时用下划线分隔单词,以提高可读性。变量名与函数名遵循相同的约定。

变量和函数名应该跟随snake_case。

debug == True

作为一般的经验法则,您应该始终将is与内置常量:TrueFalseNone一起使用。检查debug的真实性(if debug:)也足够了。但是,这取决于用例,因为表达式不是等价的。对于所有falsey值,第二个都会失败,而不仅仅是False (例如空字符串、空列表)。如果您感兴趣,可以阅读更多关于Truthy和Falsy在Python中的价值的内容。

字符串格式

代码语言:javascript
复制
LoveRate = str(random.randrange(0, 100))

LoveRate (或更好的love_rate)不应该是str类型,因为您只需要它的str-represantation来打印它。通过使用F-字符串,您可以让Python处理格式设置。那样的话,你就不必再考虑向str转换了。

代码语言:javascript
复制
print("[DEBUG] !love : The love rate ("+LoveRate+"%) between "+Personne1+" and "+Personne2+" has been printed in channel ID "+str(ctx.channel.id))

变成了

代码语言:javascript
复制
print(f"[DEBUG] !love : The love rate ({LoveRate}%) between {Personne1} and {Personne2} has been printed in channel ID {ctx.channel.id}")

还有几个小问题:

  1. 与将主代码包装在if-else-block中不同,我们可以使用ctx.message.channel.id == 763352957579690018作为退出条件。
  2. print_it的类型是int,但基本上是bool类型的变量。我们也可以完全消除这个变量,因为我们只使用它一次。
  3. 理想情况下,行长不应超过80个字符。您可以使用parantheses在多行之间方便地连接字符串,如本reddit尖端所述。我的IDE只设置为100个字符的硬包装,因此这是下面几行的最大长度。
代码语言:javascript
复制
@bot.command(name="love", aliases=["l"])
async def love(ctx, personne1, personne2):
    if ctx.message.channel.id == 763352957579690018:
        bot_channel = discord.utils.get(ctx.guild.channels, id=768194273970880533)
        message_bot = await ctx.send(f"Va faire cette commande dans {bot_channel.mention} "
                                     f"ou je te soulève <:rage:831149184895811614>")
        await asyncio.sleep(5)
        await ctx.message.delete()
        await message_bot.delete()
        return

    word_ban_list = {'@everyone', '@here', '<@&763489250162507809>', '<@&777564025432965121>',
                     '<@&822200827347075132>', '<@&763815680306184242>', '<@&764422266560839680<',
                     '<@&763815728972300338>', '<@&763815728972300338>', '<@&763815228323528725>',
                     '<@&763815784904261632>', '<@&764422166116171806>', '<@&764422057353936897>',
                     '<@&804807279043674143>', '<@&828664814678179861>', '<@&823562218095640646>',
                     '<@&823638574809219163>'}

    love_rate = str(random.randrange(0, 100))

    if personne1 in word_ban_list or personne2 in word_ban_list:
        await ctx.send("Tu t'es pris pour qui ?")
        if debug:
            print("[DEBUG] !love : Someone tried to use a banned word !")
    else:
        await ctx.send(f"L'amour entre **{personne1}** et **{personne2}** est de **{love_rate}%** "
                       f"<:flushed:830502924479758356>")
        if debug:
            print(f"[DEBUG] !love : The love rate ({love_rate}%) between {personne1} and"
                  f"{personne2} has been printed in channel ID {ctx.channel.id}")
票数 6
EN

Code Review用户

发布于 2021-04-12 18:13:27

代码语言:javascript
复制
for y in range(len(wordBanList)):
            if(Personne1 == wordBanList[y] or Personne2 == wordBanList[y]):
                printIt = 0

这段代码正在检查Personne1或Personne2是否在wordBanList中,是否有O(len(wordBanList))运行时时间。您可以将wordBanList的数据类型更改为set(),并具有O(1)运行时。因此,您的代码可以转换为:

代码语言:javascript
复制
if Personne1 in wordBanList or Personne2 in wordBanList:
    printIt = 0

P.S:如果你有一个小的wordBanList (比如<100个单词),把wordBanList作为一个列表与集合没有太大的不同。但是,当有大量的单词(>10,000,000)时,差异是显著的。https://towardsdatascience.com/faster-lookups-in-python-1d7503e9cd38

票数 3
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/259422

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档