【问题标题】:Having trouble sending messages from a Discord Bot从 Discord Bot 发送消息时遇到问题
【发布时间】:2020-11-07 01:02:18
【问题描述】:

我目前正在尝试使用 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'”时返回错误

此时我已经在这里待了几个小时,如果有任何问题,我们将不胜感激

【问题讨论】:

    标签: python windows discord


    【解决方案1】:

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

    希望对您有所帮助!祝你好运, -兰登

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-09
      • 2020-12-01
      • 2021-03-02
      • 2021-01-12
      • 2021-06-05
      • 2012-12-07
      • 1970-01-01
      • 2020-12-03
      相关资源
      最近更新 更多