从Discord Bot发送消息时遇到问题

时间:2020-07-17 08:41:16

标签: python windows discord

我目前正在尝试使用Python制作Discord机器人,以自动化一些无聊的东西。我目前正在尝试制作一些可以响应消息的内容,然后将其发送回去。

我的代码在这里:

import discord



TOKEN = '(The correct Token, hidden for obvious reasons)'

client = discord.Client()

@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'):
        msg = 'Hello {0.author.mention}'.format(message)
        await client.send(message.channel, msg)

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

client.run(TOKEN)

当我运行此代码时,该漫游器会联机显示,并在有人键入!hello时识别。但是,此后立即返回错误,尝试发送消息“ AttributeError:'客户端'对象没有属性'发送'”

我在这里已经待了好几个小时了,任何帮助都将不胜感激

1 个答案:

答案 0 :(得分:0)

考虑到此为“!”在开始时,我们可以通过更改以下内容并将其变得更紧凑,而不必将其变成on_message事件,而只需将其转换为命令即可。

原始代码:

import discord



TOKEN = '(The correct Token, hidden for obvious reasons)'

client = discord.Client()

@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'):
        msg = 'Hello {0.author.mention}'.format(message)
        await client.send(message.channel, msg)

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

client.run(TOKEN)

修改后的代码:

import discord
from discord.ext import commands #imports the commands module

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

@client.command()
async def Hello(ctx):
    await ctx.send(f'Hello {ctx.message.author}')

#the rest is the same as your original code
@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

client.run('Token')

希望这会有所帮助!祝你好运 -兰登