如何修复向不和谐频道发送消息时"Empty message"发送到控制台 - Python 不和谐机器人



我正在用python创建一个不和聊天机器人,但我得到的是"空消息"当我试图在我的服务器上输入任何命令,我试着问chatGPT,但它没有帮助,例如:Vaclavak #notshowingmytag说:"(机器人测试)空的消息

下面是我的代码:

bot.py:

import discord
import responses
import random

async def send_message(message, user_message, is_private):
try:
response = responses.handle_response(user_message)
if response:
await message.author.send(response) if is_private else await message.channel.send(response)
else:
print("Empty message")
except Exception as e:
print(e)

def run_discord_bot():
TOKEN = 'the token is here, not gonna show it lol'
intents = discord.Intents.default()
client = discord.Client(intents=intents)
@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.startswith('?'):
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)
client.run(TOKEN)
if __name__ == "__main__":
run_discord_bot()

main.py:

import bot


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

responses.py:

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.`"

我希望bot能正确响应

为了访问消息内容,您需要启用message_content意图(了解更多)。所以,如果你做了这个小小的改变,你的代码应该可以工作了:

def run_discord_bot():
TOKEN = 'the token is here, not gonna show it lol'
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
...

确保您已授权开发人员门户中的特权消息内容。