I am importing a module I created to a python file which I plan to run as main.
In the module, I have a function,
def coms(message, instRole):
where instRole
is supposed to be an instance of a class
In my main python file, I have an object,
instRole = Role()
And I have a function:
def on_message(message):
coms(message, instRole)
which I call on the next line:
on_message(m)
However, The function coms is never called. I have put in print statements in coms to make sure it is called, and it is not.
Thank you for your help ahead of time
If you're trying to take advantage of discord.py events, where your code would be executed whenever a message is seen by the bot, you have you define a coroutine (a function that uses the async def
syntax) and use the bot.event
decorator to register it with your bot. Below is a basic example:
from discord.utils import get
from discord.ext import commands
from other_file import coms
bot = commands.Bot(command_prefix='!')
@bot.event
async def on_message(message):
instRole = get(message.server.roles, id="123") # Get the role with its id
await coms(message, instRole)
bot.run("TOKEN")
If you want the coroutine in the other file to actually do something in discord, it's best to make that file a cog, which is a class that implements a specific functionality for a discord bot.
cog.py:
from discord.ext import commands
class Cog():
def __init__(self, bot):
self.bot = bot
# Note no decorator
async def on_message(self, message):
await self.coms(message, instRole)
async def coms(self, message, role):
... # use self.bot instead of bot
def setup(bot):
bot.add_cog(Cog(bot))
main.py:
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
cogs = ['cog']
if __name__ == "__main__":
for cog in cogs:
try:
bot.load_extension(cog)
except Exception:
print('Failed to load cog {}\n{}'.format(extension, exc))
bot.run('token')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.