繁体   English   中英

AttributeError: 'Client' 对象没有属性 'send_message' (Discord Bot)

[英]AttributeError: 'Client' object has no attribute 'send_message' (Discord Bot)

出于某种原因,send_message 在我的 Discord 机器人上无法正常工作,我无论如何都找不到修复它。

import asyncio
import discord

client = discord.Client()

@client.async_event
async def on_message(message):
    author = message.author
   if message.content.startswith('!test'):
        print('on_message !test')
        await test(author, message)
async def test(author, message):
    print('in test function')
    await client.send_message(message.channel, 'Hi %s, i heard you.' % author)
client.run("key")
on_message !test
in test function
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\indit\AppData\Roaming\Python\Python36\site-packages\discord\client.py", line 223, in _run_event
    yield from coro(*args, **kwargs)
  File "bot.py", line 15, in on_message
    await test(author, message)
  File "bot.py", line 21, in test
    await client.send_message(message.channel, 'Hi %s, i heard you.' % author)
AttributeError: 'Client' object has no attribute 'send_message'

你可能运行discord.py的重写版本,因为discord.Client对象没有一个有send_message方法。

要解决您的问题,您可以将其设置为:

async def test(author, message):
    await message.channel.send('I heard you! {0.name}'.format(author))

但对于我看到你在做什么,我建议使用命令扩展

这使得为​​机器人创建机器人和命令变得更加简单,例如,这里有一些与您的代码完全相同的代码

from discord.ext import commands

bot = commands.Bot(command_prefix='!')

@bot.command()
async def test(ctx):
    await ctx.send('I heard you! {0}'.format(ctx.author))

bot.run('token')

根据discord.py文档,迁移到 v1.0 给 API 带来了许多重大变化,包括许多功能discord.Client移出并放入各自的模型中

例如在您的特定情况下: Client.send_message(abc.Messageable) --> abc.Messageable.send()

因此,您的代码将从此重新设计:

await client.send_message(message.channel, 'I heard you! {0}'.format(message.author))

对此:

await message.channel.send('I heard you! {0}'.format(message.author))

这使得代码在描述实际不和谐实体时更加一致和准确,即不和谐Message被发送到Channelabc.Messageable子类)而不是Client本身是很直观的。

从这个意义上说,有一个相当大的迁移列表; 你可以找到所有他们在这里下的Models are Stateful部分。

我认为send_message()不能再用于send_message()函数了。 但这并不意味着我们不能发送消息。 确实存在将消息发送到通道的另一种方式。

您可以使用:

await message.channel.send("")

以此目的。

因此,让我们现在将其应用到您的代码中。

import asyncio
import discord

client = discord.Client()

@client.async_event
async def on_message(message):
    author = message.author
   if message.content.startswith('!test'):
        print('on_message !test')
        await test(author, message)
async def test(author, message):
    print('in test function')
    await message.channel.send(F'Hi {author}, I heard you.')

client.run("key")

现在这将解决您的问题,您将能够使用您的机器人轻松发送消息。

谢谢你! :D

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM