Discord机器人独立函数无法接收消息的问题求助
问题排查与解决
问题根源
你定义的spam是一个独立异步函数,但没有在on_message事件处理器中被调用。Discord.py的on_message事件只会执行自身内部逻辑,不会自动触发未关联的外部函数,所以用户发送$long时,机器人根本没机会执行spam里的判断逻辑。
修复方案
方案1:在on_message中调用spam函数
直接在on_message事件里添加对spam的调用,让机器人能处理$long指令:
import discord import mysql.connector client = discord.Client(intents=discord.Intents.all()) mylb = mysql.connector.connect( host='localhost', user='root', password="", database="worst") cursor = mylb.cursor() @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith('$hello'): await message.channel.send('Hello!') # 调用spam函数处理$long指令 await spam(message) async def spam(message): if message.author == client.user: return if message.content.startswith('$long'): await message.channel.send("spam") client.run('my token')
方案2:将spam逻辑整合到on_message中
如果函数逻辑简单,直接把判断放到on_message里会更简洁:
import discord import mysql.connector client = discord.Client(intents=discord.Intents.all()) mylb = mysql.connector.connect( host='localhost', user='root', password="", database="worst") cursor = mylb.cursor() @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith('$hello'): await message.channel.send('Hello!') elif message.content.startswith('$long'): await message.channel.send("spam") client.run('my token')
方案3:使用commands.Bot简化命令管理(推荐)
如果后续要扩展更多命令,建议改用commands.Bot,它自带命令装饰器,代码更易维护:
import discord from discord.ext import commands import mysql.connector # 初始化Bot,命令前缀设为$ bot = commands.Bot(command_prefix='$', intents=discord.Intents.all()) mylb = mysql.connector.connect( host='localhost', user='root', password="", database="worst") cursor = mylb.cursor() @bot.event async def on_ready(): print('We have logged in as {0.user}'.format(bot)) @bot.command() async def hello(ctx): await ctx.send('Hello!') @bot.command() async def long(ctx): await ctx.send("spam") bot.run('my token')
额外提醒
- 确认机器人Token正确,且已被邀请到目标服务器,拥有发送消息的权限
- MySQL连接如果失败可能导致机器人崩溃,建议添加异常处理逻辑
内容的提问来源于stack exchange,提问作者Mudit Dagar
相关产品推荐
相关产品推荐

