Python-显示消息输入的命令错误(Discord.py)

时间:2020-07-17 08:54:43

标签: python text-files discord.py

我当前正在运行以下代码,以查找词典中的项目(通道名称,命令和包含要输出数据的文本文件路径)。

下面是我以前使用的代码,可以正常工作,但是当输入字典中不存在的命令时,Discord中不会显示任何消息。

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 ifif语句,如下面的代码所示,但是我收到的输出是一个不断循环的“错误命令”输出。看来,即使命令是字典中的值,如果输出了下面的代码,该“错误命令”也将输出。

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

感谢任何可以为该问题提供帮助或解决方案的人。


更新:

我能够使用Mr_Spaar提供的第一部分代码。输出的结果与预期不符,但是当我检查终端时,出现以下错误:

File "discordbot4.py", line 72, in on_message
    await message.author.send("Wrong command")
AttributeError: 'ClientUser' object has no attribute '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")


1 个答案:

答案 0 :(得分:1)

如果找到了命令,则可以使用return来执行此操作:

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

但是,使用on_message事件创建命令并不是最佳选择,您可以使用commands框架:

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