【发布时间】: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