Python-显示消息的命令输入错误(Discord.py)
我目前正在运行以下代码以查找字典中的项(通道名称、命令和包含要输出的数据的文本文件路径) 下面是我以前使用的代码,它工作正常,但当输入字典中不存在的命令时,Discord中没有显示消息Python-显示消息的命令输入错误(Discord.py),python,text-files,discord.py,Python,Text Files,Discord.py,我目前正在运行以下代码以查找字典中的项(通道名称、命令和包含要输出的数据的文本文件路径) 下面是我以前使用的代码,它工作正常,但当输入字典中不存在的命令时,Discord中没有显示消息 for id, info in dict.items(): if str(message.channel) == info["channel"]: print(info["channel"]) if me
for id, info in dict.items():
if str(message.channel) == info["channel"]:
print(info["channel"])
if message.content.find (info["command"]) != -1:
print(info["command"])
print(info["textfile"])
with open(info["textfile"], 'r') as file:
msg = file.read().strip().split ("--------------------")
await message.channel.send("Info sent in DM")
for item in msg:
print (item)
await message.author.send(item)
这段代码工作正常,但我希望如果用户输入的命令不在其中一个口述条目中,则会以不协调的方式向用户显示一条消息。我尝试添加和if-elif语句,如下面的代码所示,但我收到的输出是一个无休止的“错误命令”循环。下面的代码显示,即使命令是字典中的值,也会输出“不正确的命令”
dict = {"boxingchannel" : {"channel": "boxingmma", "command": "!boxing", "textfile":"/var/output/boxingtest.txt" },
"footballchannel" : {"channel": "football", "command": "!english", "textfile":"/var/output/englandtest.txt" },
"helpchannel" : {"channel": "general", "command": "!buffer", "textfile":"/home/brendan/Desktop/Python/tryfirst.txt"}
}
for id, info in dict.items():
if str(message.channel) == info["channel"]:
print(info["channel"])
if str(message.content.find) == (info["command"]):
print(info["command"])
print(info["textfile"])
with open(info["textfile"], 'r') as file:
msg = file.read().strip().split ("--------------------")
await message.channel.send("Info sent in DM")
for item in msg:
print (item)
await message.author.send(item)
elif str(message.content.find) != (info["command"]):
await message.channel.send("Incorrect command")
感谢任何能为这个问题提供帮助或解决方案的人
更新: 我能够使用_Spaar先生提供的第一段代码。这会在discord中按预期输出,但当我检查终端时,会出现以下错误:
File "discordbot4.py", line 72, in on_message
await message.author.send("Wrong command")
AttributeError: 'ClientUser' object has no attribute 'send'
我已经查找了此错误,并看到有一个讨论指出客户端没有send类,但我不确定我需要做什么或调查以防止显示此错误
感谢您为解决此问题提供帮助
完整代码:
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_member_join(member):
await member.send("```Welcome to Sports Schedule server. \n This is a bot only server which you can send messages and automatically receive a response. \nCommands accepted by bot can be found by sending message !help in any of the channels. \n Enjoy your stay.```")
@client.event
async def on_message(message):
id = client.get_guild(731946041****229982)
online = 0
idle = 0
offline = 0
if message.content == "!users":
for m in id.members:
if str(m.status) == "online":
online += 1
if str(m.status) == "offline":
offline += 1
else:
idle += 1
await message.channel.send(f"```Online: {online}.\nIdle/busy/dnd: {idle}.\nOffline: {offline} .\nTotal Members: {id.member_count}```")
dict = {"boxingchannel" : {"channel": "boxingmma", "command": "!boxing", "textfile":"/var/output/boxingtest.txt" },
"footballchannel" : {"channel": "football", "command": "!english", "textfile":"/var/output/englandtest.txt" },
"helpchannel" : {"channel": "general", "command": "!buffer", "textfile":"/home/brendan/Desktop/Python/tryfirst.txt"}
}
for id, info in dict.items():
if str(message.channel) == info["channel"]:
print(info["channel"])
if message.content.find (info["command"]) != -1:
print(info["command"])
print(info["textfile"])
with open(info["textfile"], 'r') as file:
msg = file.read().strip().split ("--------------------")
await message.channel.send("Info sent in DM")
for item in msg:
print (item)
await message.author.send(item)
return
await message.author.send("Wrong command")
client.run("NzMxOTQ4Mzk5N*****jY3NDg2.XwuPsw.iNu1Ju-e2yDnRS_uWqff43Thvqw")
如果找到命令,可以使用
return
,以这种方式执行此操作:
对于目录项()中的id、信息:
如果str(message.channel)==info[“channel”]:
打印(信息[“频道”])
如果message.content.find(信息[“命令])!=-1:
打印(信息[“命令”])
打印(信息[“文本文件”])
打开(信息[“textfile”],“r”)作为文件:
msg=file.read().strip().split(“-------------------”)
wait message.channel.send(“在DM中发送的信息”)
对于msg中的项目:
打印(项目)
等待消息。作者。发送(项目)
返回
等待消息.author.send(“输入了错误的命令”)
但是,使用on_message
事件来创建命令并不是最佳选择,您可以使用以下框架:
from discord.ext import commands
@commands.command(aliases=["english", "football"])
async def buffer(ctx):
command_list = {
"boxing" : {"channel": "boxingmma", "textfile":"/var/output/boxingtest.txt" },
"english" : {"channel": "football", "textfile":"/var/output/englandtest.txt" },
"buffer" : {"channel": "general", "textfile":"/home/brendan/Desktop/Python/tryfirst.txt"},
}
try:
command = command_list[ctx.invoked_with]
if ctx.channel.name == command['channel']:
with open(command["textfile"], 'r') as file:
msg = file.read().strip().split("--------------------")
await ctx.send("Info sent in DM")
await message.author.send('\n'.join(msg))
return
await ctx.send("Wrong channel!")
except:
await ctx.send("Wrong command!")
谢谢@Mr_Spaar,我能够在你的第一段代码中添加一个else语句,但是我随后收到了一个无休止的“错误命令”或“在DM中发送的信息”消息循环。经过更多的调查,我发现第二个问题是由于不和谐的机器人对自身的反应。我在on_message函数的开头添加了以下代码以停止此操作,现在一切正常。-<代码>如果message.author==client.user:return