【问题标题】:Discord Bot - AttributeError: 'Client' object has no attribute 'commands'Discord Bot - AttributeError:“客户端”对象没有属性“命令”
【发布时间】:2019-10-15 14:06:18
【问题描述】:

我正在尝试创建一个新的 Discord 机器人,但在尝试创建一条向该机器人当前所在的所有 Discord 服务器公布的消息时出现问题。

我试图解决问题无济于事,这包括查找它、阅读文档,当然还有尝试新代码。


import discord
import asyncio 
from discord.ext import commands
from discord.ext.commands import Bot

TOKEN = [REDACTED]



# client = discord.Client()

client = Bot("!")

@client.event
async def on_message(message):
    # we do not want the bot to reply to itself
    if message.author == client.user:
        return

    if message.content.startswith('!hello'):
        @client.command(pass_context=True)
        async def broadcast(ctx, *, msg):
                for server in bot.guilds:
                    for channel in server.channels:
                        try:
                            await channel.send(msg)
                        except Exception:
                            continue
                        else:
                            break

我希望程序将我的消息发送到机器人当前所在的所有服务器。

例如:!你好,你好,这是一个公告!

应该触发 !hello 之后的消息在每个服务器上广播。

编辑:经过一些帮助后,我仍然遇到问题!现在的错误是执行命令后什么都没有出现,如果我再执行一次,它会出现错误:“命令广播已注册。”

【问题讨论】:

    标签: python-3.x discord discord.py


    【解决方案1】:

    为什么要在 client.event 这样的内部使用 client.command

    只需使用命令:

    @client.command(pass_context=True)
    async def hello(ctx, *, msg):
        for server in client.servers:
            for channel in server.channels:
                try:
                    await client.send_message(channel, msg)
                except Exception:
                    continue
                else:
                    break
    

    这会将消息发送到公会中的 first 频道,在该频道中,机器人具有发送消息的权限。

    对于将来的参考,请考虑升级到最新的 API 版本,因为旧版本不受支持,您将很难获得帮助。对于新 API,代码如下所示:

    @client.command()
    async def hello(ctx, *, msg):
        for server in bot.guilds:
            for channel in server.channels:
                try:
                    await channel.send(msg)
                except Exception:
                    continue
                else:
                    break
    

    编辑:根据 Patrick 的评论,您的具体错误表明您使用的是 Client 而不是 Bot ,如果是这样,请改用 @bot.command

    【讨论】:

    • 我唯一要补充的是,他们看到的错误表明他们使用的是Client而不是Bot
    • 你刚刚看到错误出现在标题中:/ 感谢@PatrickHaugh 的提醒
    • @PatrickHaugh 如果我使用 'Bot' ,我会得到:“NameError: name 'Bot' is not defined” 我将客户端定义为:“client = discord.Client()” 这应该可以正常工作?我仍然得到同样的错误:(
    • 没有。使用from discord.ext.commands import Bot,然后使用client = Bot("!")
    • @PatrickHaugh 谢谢你的帮助,我还在苦苦挣扎!我已使用包含所有更改的完整脚本更新了我的原始帖子。
    猜你喜欢
    • 2019-09-10
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 2018-03-20
    • 2020-10-25
    相关资源
    最近更新 更多