You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Discord.py自定义on_message事件导致命令无法运行的问题求助

问题修复:自定义on_message后Discord Bot命令无法触发

这问题我之前也踩过坑!原因很直白:当你给commands.Bot自定义了on_message事件处理函数时,Bot默认的命令解析逻辑会被覆盖——它不会自动判断这条消息是不是命令了,所以你的hello命令自然触发不了。

具体修复方案

  1. 手动触发命令处理逻辑:在on_message函数末尾(确保不会被提前return打断的位置)添加await bot.process_commands(message),让Bot在处理完你的违禁词检查后,继续解析并执行命令。
  2. 修复hello命令的异步问题:原代码里的context.send('Hello!')缺少await关键字,这会导致运行报错,必须补上。

修改后的完整代码

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='//')

# 用with语句读取文件更安全,自动关闭文件
with open('*Filelocation*', 'r') as bdl:
    badwordslist = bdl.read().split()

@bot.command()
async def hello(context):
    print('it works')
    await context.send('Hello!')  # 补上await关键字

@bot.event
async def on_connect():
    print('Connected.')

@bot.event
async def on_ready():
    print('READY.')

@bot.event
async def on_message(message):
    # 处理违禁词检查逻辑
    for badword in message.content.lower().split():
        if badword in badwordslist:
            await message.channel.send(f'Hey! {message.author.mention} ! Don\'t be rude!')
            print(f'{message.author} Said A Bad Word.')
            break
    # 必须添加这行,让Bot处理命令
    await bot.process_commands(message)

bot.run("*Token*")

额外提个小优化:用with语句读取文件比手动调用close()更稳妥,能避免忘记关闭文件导致的资源泄漏,我已经在代码里帮你调整了。

内容的提问来源于stack exchange,提问作者behrad badeli

火山引擎 最新活动