I’m working on a Discord bot that needs to do two things at once. It should listen for specific messages in the server and also respond to commands. Here’s what I’ve tried so far:
import discord
from discord.ext import commands
bot = commands.Bot(prefix='!')
bot.remove_command('default_help')
@bot.event
async def on_ready():
print('Bot is online')
@bot.event
async def on_message(msg):
if msg.author == bot.user:
return
if msg.embeds:
embed_content = msg.embeds[0].description
if embed_content == 'specific_text':
print('Specific embed detected')
await bot.process_commands(msg)
@bot.command()
async def greet(ctx):
await ctx.send('Hey there!')
bot.run('your_token_here')
The bot starts up, but it seems to get stuck in the message listening loop. It’s not responding to commands. I’ve heard about using subprocesses, but I’m not sure how to implement that here. Any ideas on how to make both the event listener and command handler work together?
Your approach is on the right track, but there’s a small issue in your code. The problem lies in the on_message event. While you’re correctly using bot.process_commands(msg), it’s important to note that this should be called regardless of whether an embed is detected or not.
Try modifying your on_message function like this:
@bot.event
async def on_message(msg):
if msg.author == bot.user:
return
if msg.embeds:
embed_content = msg.embeds[0].description
if embed_content == 'specific_text':
print('Specific embed detected')
await bot.process_commands(msg)
This ensures that commands are always processed, even if the message doesn’t contain an embed. Also, make sure you’ve set up the necessary intents for your bot, especially if you’re using discord.py 2.0+. This should resolve the issue and allow both event listening and command handling to work simultaneously.
hey, i’ve faced similar issues. try using a Cog structure to separate ur event listeners and commands. it’ll make things cleaner. also, make sure ur using the latest discord.py version (2.0+) cuz it handles concurrent events better. good luck with ur bot!
I’ve been through this exact situation with my own Discord bot. The key is to make sure you’re not blocking the event loop. Your code looks good, but you might want to consider using discord.Intents to explicitly define what events your bot should listen for. This can help with performance.
Here’s a tip from my experience: use bot.wait_for() for specific message listening instead of checking every message. It’s more efficient and won’t interfere with command processing.
Also, don’t forget to enable the message content intent if you’re using discord.py 2.0+. Without it, your bot won’t see message content outside of commands.
Lastly, if you’re dealing with a lot of concurrent events, consider using asyncio tasks to handle heavy processing separately from your main bot loop. It’s helped me keep my bot responsive even when dealing with complex operations.