【问题标题】:Python - Discord.py - Prevent reuse of same code multiple times in on_message functionPython - Discord.py - 防止在 on_message 函数中多次重复使用相同的代码
【发布时间】:2020-11-03 19:54:18
【问题描述】:

我使用 Discord.py 创建了一个简单的机器人,它输出文本文件的内容,其中包含抓取的体育赛事和频道数据(抓取的数据来自我创建的其他小脚本,但未包含在此处)。

discordbot.py

import discord
import os
from dotenv import load_dotenv


client = discord.Client()

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')

client = discord.Client()

@client.event
async def on_ready():
    for guild in client.guilds:
        if guild.name == GUILD:
            break

    print(
        f'{client.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})'
    )

                
@client.event
async def on_message(message):
    id = client.get_guild(73194****229982)
    

    if str(message.channel) == "boxingmma":
        if message.content.find("!boxing") != -1:

            with open('/home/brendan/Desktop/boxingtest.txt', 'r') as file:
                msg = file.read(2000).strip()
                while len(msg) > 0:
                    await message.author.send(msg)
                    msg = file.read(2000).strip()
                    
    if str(message.channel) == "football":
        if message.content.find("!english") != -1:

            with open('/home/brendan/Desktop/splittest.txt', 'r') as file:
                msg = file.read(2000).strip()
                while len(msg) > 0:
                    await message.author.send(msg)
                    msg = file.read(2000).strip()
                    
    if str(message.channel) == "football":
        if message.content.find("!scottish") != -1:

            with open('/home/brendan/Desktop/testing2.txt', 'r') as file:
                msg = file.read(2000).strip()
                while len(msg) > 0:
                    await message.author.send(msg)
                    msg = file.read(2000).strip()
            


client.run("NzMxOTQ4Mzk5NzY2NjY3NDg2.XwuPsw.iN****-e2yDnRS_uWqff43Thvqw")

机器人运行良好,当在相关的不和谐频道上运行命令时,会向向机器人发送请求的用户发送 DM。这段代码最大的问题是 on_message 函数中的重复代码。三个不同的双 if 语句的唯一区别是通道名称,例如足球或拳击,例如命令!scottish, !english, !boxing 和抓取数据的文件路径。

我很好奇是否有人知道无论如何这可以改进或重复代码重用的方法?我试图将这些作为来自另一个函数的位置参数传递,例如:

def callall():
    on_message(channel="football", command="!english", filepath="/home/brendan/Desktop/test.txt")

但似乎在研究后无法将参数传递给 discord.py 中的 on_message

任何关于如何重新使用重复代码或改进一般程序流程的方法的建议将不胜感激

谢谢大家。

【问题讨论】:

  • 必须在on_message 事件中吗?您可以使用 discord.py 的 commands 框架创建命令。
  • 您是否考虑过使用 dict 并对其进行循环。例如:您可以将football 作为键,将/home/brendan/Desktop/splittest.txt 作为值。
  • @Mr_Spaar - 不必局限于 on_message 事件。
  • @SahilM - 这听起来是个不错的选择。您能否在答案中概述这一点?谢谢

标签: python text-files discord.py


【解决方案1】:

你可以有一个字典

dict = {"boxingmma":"/home/brendan/Desktop/boxingtest.txt", "football":"/home/brendan/Desktop/splittest.txt", "football1":"/home/brendan/Desktop/testing2.txt"}

for key, value in dict:
    if str(message.channel) == key:
        if message.content.find("!boxing") != -1:

            with open(value, 'r') as file:
                msg = file.read(2000).strip()
                while len(msg) > 0:
                    await message.author.send(msg)
                    msg = file.read(2000).strip()

对于第三个值,我将 football 设为 football1,因为键不能重复。

【讨论】:

    猜你喜欢
    • 2019-08-23
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-12
    • 2018-05-25
    • 1970-01-01
    • 2017-04-09
    相关资源
    最近更新 更多