I'm new to python and the Discord API and I ran into an issue. In my bot, if a user types !dm
I want it to directly message them a random output. I have found a way so when the user sends !dm
, the bot messages them and I got the bot to send a random message too. but for whatever reason, when the bot sends a random message i get an error in the console but it still wokrs.
# !dm with one output
import discord
client = discord.Client()
@client.event
async def on_message(message):
if message.content.lower() == "!dm":
await message.author.send("Text")
return
client.run("TOKEN")
# !dm with 5 outputs
import discord
import random
client = discord.Client()
@client.event
async def on_message(message):
username = str(message.author).split("#")[0]
user_message = str(message.content)
channel = str(message.channel.name)
server = str(message.guild.name)
if user_message.lower() == "!dm":
await message.channel.send(f"Sent you a dm {username}")
randomoutput = int(random.randrange(5))
print(f"({server}) >> {username} ran !dm in {channel} and got output {randomoutput}")
if randomoutput == 0:
await message.author.send("Output 0")
return
elif randomoutput == 1:
await message.author.send("Output 1")
return
elif randomoutput == 2:
await message.author.send("Output 2")
return
elif randomoutput == 3:
await message.author.send("Output 3")
return
elif randomoutput == 4:
await message.author.send("Output 4")
return
return
client.run("Token")
Heres the error
(server) >> user ran !dm in channel and got output 4
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\%username%\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "botdir\test.py", line 10, in on_message
channel = str(message.channel.name)
AttributeError: 'DMChannel' object has no attribute 'name'
The bot will still dm the user the appropriate output and this only happens when i send a random message.
By the looks of the error, you are trying to get the name
attribute of a DMChannel
, when there is no such thing. To simplify, while a channel in a server has a name (e.g. #general
or #bot-commands
), a direct message does not so trying to get it's name results in an error.
To fix this, remove the line:
channel = str(message.channel.name)
and it's take out the usage of that varable in the print
statement:
print(f"({server}) >> {username} ran !dm in {channel}... // remove the "channel" variable
and you won't get that error.
Note: Having not run the code, I cannot guarantee the rest of the program will work without another error, but it looks correct.