【发布时间】:2021-11-03 21:30:49
【问题描述】:
我是 python 和 Discord API 的新手,遇到了一个问题。在我的机器人中,如果用户输入!dm,我希望它直接向他们发送随机输出消息。我找到了一种方法,因此当用户发送!dm 时,机器人会向他们发送消息,我也让机器人发送随机消息。但无论出于何种原因,当机器人发送一条随机消息时,我在控制台中收到一个错误,但它仍然可以工作。
# !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")
这是错误
(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'
机器人仍然会向用户发送适当的输出,并且这只发生在我发送随机消息时。
【问题讨论】: