I’m pretty new to working with Discord bots and Python in general. I have a basic setup with two separate Python files, and I’m trying to figure out how to send a message to a Discord channel from one file through my bot that’s defined in another file.
I have main_bot.py and external_script.py. What I want to do is call a function from external_script.py that will make my Discord bot send a message to a specific channel.
My bot runs perfectly fine on its own, but when I try to call the notify function from the external script, it doesn’t work properly. I think I’m missing something about how to properly communicate between these files. Can someone point me in the right direction?
Your bot isn’t running when you try to send messages from the external script. When you import main_bot, the bot client hasn’t started yet. Here’s what works: Create a separate function in main_bot.py for sending messages, then use threading. Run your bot in one thread and your external script in another. Alternatively, use asyncio to schedule the message sending task within the bot’s event loop - this worked well for me. Double-check that your bot has permissions for the target channel and you’re using the right channel ID with get_channel().
Your issue arises because Discord bot commands require a context object (ctx), which is not available in your external script. Instead of calling the command directly, consider defining a regular function in main_bot.py that utilizes client.get_channel() to send messages to a specific channel ID. To facilitate communication between your scripts, you may also explore using shared queues, webhooks, or file-based approaches. Remember, your bot must maintain an active connection to the Discord gateway for sending messages, so direct function calls between scripts won’t suffice. Alternatively, you could leverage discord.py’s webhook feature for straightforward messaging.
u can’t just call bot commands like that, they need the ctx obj. try setting up a queue for the bot to check for new msg or use webhooks for easier, direct messaging. it’s simpler and avoids all the command stuff!