【问题标题】:Issues with dm a user with a discord bot (python)使用不和谐机器人(python)的用户的 dm 问题
【发布时间】: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'

机器人仍然会向用户发送适当的输出,并且这只发生在我发送随机消息时。

【问题讨论】:

    标签: python discord


    【解决方案1】:

    从错误的外观来看,您正在尝试获取DMChannelname 属性,而实际上并没有这样的东西。为简化起见,虽然服务器中的频道有名称(例如 #general#bot-commands),但直接消息不会因此尝试获取其名称会导致错误。

    要解决此问题,请删除以下行:

    channel = str(message.channel.name)
    

    它在print 语句中删除了该变量的用法:

    print(f"({server}) >> {username} ran !dm in {channel}... // remove the "channel" variable
    

    你不会得到那个错误。

    注意:由于没有运行代码,我不能保证程序的其余部分可以正常运行而不会出现其他错误,但它看起来是正确的。

    【讨论】:

    • 我必须删除用户名、user_message、频道和服务器变量才能使其正常工作,但这很好。感谢您的帮助
    猜你喜欢
    • 2018-07-21
    • 2020-06-08
    • 2021-11-09
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 2022-10-13
    • 2021-12-21
    相关资源
    最近更新 更多