discord.py 接收空字符串而不是消息

问题描述 投票:0回答:1

我正在用 discord.py 在 Python 上制作一个 discord 机器人

我有那个问题,当我运行机器人时,它可以工作,但它接收到空字符串而不是消息。

测试反应:

import random


def handle_response(message) -> str:
    p_message = message.lower()
    if p_message == 'hello':
        return 'Hey there!'

    if p_message == 'roll':
        return str(random.randint(1, 6))

    if p_message == '!help':
        return "`This is a help message that you can modify.`"

    #  return 'Yeah, I don\'t know. Try typing "!help".'

主要:

import bot

if __name__ == '__main__':
    bot.run_discord_bot()

问题代码又名机器人:


import discord
import responses


# Send messages
async def send_message(message, user_message, is_private):
    try:
        response = responses.handle_response(user_message)
        await message.author.send(response) if is_private else await message.channel.send(response)

    except Exception as e:
        print(e)


def run_discord_bot():
    TOKEN = 'Our_Token'
    client = discord.Client(intents=discord.Intents.default())

    @client.event
    async def on_ready():
        print(f'{client.user} is now running!')

    @client.event
    async def on_message(message):
        # Make sure bot doesn't get stuck in an infinite loop
        if message.author == client.user:
            return

        # Get data about the user
        username = str(message.author)
        user_message = str(message.content)
        channel = str(message.channel)

        # Debug printing
        print(f"{username} said: '{user_message}' ({channel})")

        # If the user message contains a '?' in front of the text, it becomes a private message
        if user_message[0] == '?':
            user_message = user_message[1:]  # [1:] Removes the '?'
            await send_message(message, user_message, is_private=True)
        else:
            await send_message(message, user_message, is_private=False)

    # Remember to run your bot with your personal TOKEN
    client.run(TOKEN)

每条消息后,控制台返回:

预期行为:

它应该接收消息(不是空字符串),如果消息在 responses.py 中,它应该返回一条消息(机器人应该发送消息)。

python discord.py bots message
1个回答
3
投票

问题是您没有启用

message_content
意图 - 您需要设置它才能阅读消息内容。

intents = discord.Intents.default()
intents.message_content = True  # explicitly enable the message content intents
client = discord.Client(intents=intents)

您还需要在 Discord 开发者门户中为您的机器人/应用程序启用此意图。

© www.soinside.com 2019 - 2024. All rights reserved.