首页 > 解决方案 > 从 Discord Bot 发送消息时遇到问题

问题描述

我目前正在尝试使用 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:'Client' object has no attribute 'send'”时返回错误

在这一点上,我已经在这里待了几个小时,任何人都将不胜感激

标签: pythonwindowsdiscord

解决方案


考虑到这有“!” 在它的开头,我们可以通过更改以下内容将其转换为命令并使其更紧凑,而不是使其成为 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')

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


推荐阅读