Python Discord.py防止在on_消息函数中多次重用同一代码

2024-04-23 19:16:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Discord.py创建了一个简单的bot,该bot输出文本文件的内容,这些文本文件包含已删除的体育器材和频道数据(已删除的数据是从我创建的其他小脚本接收的,但此处未包含)

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")

bot运行正常,当在相关discord通道上运行命令时,会向向bot发送请求的用户发送DM。这段代码的最大问题是on_message函数中的重复代码。三种不同的双if语句的唯一区别是频道名称,例如足球或拳击,命令,例如!苏格兰人的英语装箱和刮取数据的文件路径

我很好奇,是否有人知道这种方法可以改进,或者重复代码可以重用?我尝试从另一个函数将这些作为位置参数传递,例如:

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

但在研究了这一点之后,似乎不可能在discord.py中将参数传递给on_消息

任何关于如何恢复重复代码的建议,或改进通用程序流程的方法,都将不胜感激

谢谢大家


Tags: clientmessagehomereadifonbotchannel
1条回答
网友
1楼 · 发布于 2024-04-23 19:16:50

你可以有一个口述作为

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()

对于第三个值,我将足球视为足球1,因为按键不能重复

相关问题 更多 >