Brendan Rodgers
Brendan Rodgers

Reputation: 305

Python - Displaying message is wrong command entered (Discord.py)

I am currently running the following code to look for items in a dictionary (channel name, command and text file path containing the data that is to be outputted).

Below is the code I was using previously which worked correctly, but when a command that wasn't present in the dictionary was entered there was no message display in 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)
                        

This code works fine but I wanted a message to be displayed to the user in discord if they enter a command that is not in one of the dictonary entries. I tried adding and if elif statement, as can be seen in the code below, but the output I receive is an endless loop of "Incorrect command" being outputted. It also appears that with the code below that "Incorrect command" if outputted even if the command is a value in the dictionary.

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

Thanks to anyone who can provide assistance or a solution to this issue.


UPDATE:

I was able to use the first section of code kindly provided by Mr_Spaar . This outputs as expected in discord, but when I check the terminal I get the following error:

File "discordbot4.py", line 72, in on_message
    await message.author.send("Wrong command")
AttributeError: 'ClientUser' object has no attribute 'send'

I have looked this error up and see there is a discussion stating the Client does not have a class of send, but I am unsure what I would need to do or investigate to prevent this error from being displayed.

Thank you for anyone who can provide assistance in solving the issue.

FULL CODE:

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


Upvotes: 0

Views: 319

Answers (1)

MrSpaar
MrSpaar

Reputation: 3994

You can do it this way, using return if the command was found:

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

However, using a on_message event to create command isn't really optimal, you could use the commands framework:

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

Upvotes: 1

Related Questions