Warm tip: This article is reproduced from serverfault.com, please click

refactoring-Python。

(refactoring - Python. Code repeats several times because the command to execute it is different)

发布于 2020-12-31 12:06:06

我已经使用 Python 修补了一个 Discord 机器人,它已经运行良好,但存在一个问题。

这段代码重复了几次,对于每个类别的帖子一次,现在我有随机的、有趣的、体育、游戏和新闻,所以你可以看到它的冗余以及它会进一步变成什么,如果需要做更多的话类别。

if '!random' in messageContent:
                channel = int(chanRandom.strip('"'))
                channel = client.get_channel(channel)
                while c < 50:
                    if messageContent == '!random':
                        submission = next(x for x in randomList[sortListHot] if not x.stickied)
                        sortType   = 'Hot sorting'
                    elif messageContent == '!random top':
                        submission = next(x for x in randomList[sortListTop] if not x.stickied)
                        sortType   = 'Top sorting'
                    elif messageContent == '!random new':
                        submission = next(x for x in randomList[sortListNew] if not x.stickied)
                        sortType   = 'New sorting'
                    with open(urlFile, 'r') as urlRead:
                        if str(submission.url) not in urlRead.read():
                            await channel.send(f"{submission.url}\n{submission.title}\n<https://reddit.com{submission.permalink}>")
                            await channel.send("-------------------------")
                            with open(urlFile, 'a+') as urlWrite:
                                urlWrite.write(str(f'{submission.url}\n'))
                            c += 2
                        else:
                            print(f'{messageContent} repost: {submission.url}')
                await channel.send(sortType)

我现在的想法是创建一个包含每个可能命令的列表,但问题是在正确的频道中发布变量channel = int(chanRandom.strip('"')),该变量根据所使用的命令等而变化channel = int(chanNews.strip('"'))

内存使用也存在问题,因为我认为机器人正在保存所有内容,但没有必要,但这是下一次的事情。

任何帮助都感激不尽。

Questioner
HASJ
Viewed
0
Diggy. 2020-12-31 22:45:10

我在这里看不到所有变量的内容,但是如果你想减少代码重复,我建议你制作一个字典并将不同的变量映射到用户输入。

这是它的想法:

my_mapping = {
    "!random": (sortListHot, "Hot sorting"),
    "!random top": (sortListTop, "Top sorting"),
    "!random new": (sortListNew, "New sorting")
}

sorting_type = my_mapping[messageContent.lower()][0]  # sortListHot/Top/New
sorting_text = my_mapping[messageContent.lower()][1]  # "Hot/Top/New sorting"

submission = next(x for x in randomList[sortingType] if not x.stickied)

将这些映射到字典还可以轻松灵活地添加更多条目(只需添加一个新键,其值为遵循当前模式的元组)。

.lower()是为不区分大小写增加。

我还可以建议查看命令装饰器而不是使用on_message事件。


参考: