(Python3)将对象传递给导入的模块函数

2024-06-26 14:06:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在将我创建的一个模块导入到一个python文件中,我计划将其作为main运行。你知道吗

在模块中,我有一个函数

def coms(message, instRole):

其中instRole应该是类的实例


在我的主python文件中,我有一个对象

instRole = Role()

我有一个功能:

def on_message(message):
    coms(message, instRole)

我在下一个电话里说:

on_message(m)

但是,从未调用coms函数。我已经在通讯中输入了打印语句,以确保它被调用,而不是被调用。你知道吗

提前谢谢你的帮助


Tags: 模块文件对象实例函数功能messagemain
1条回答
网友
1楼 · 发布于 2024-06-26 14:06:52

如果您试图利用事件,只要bot看到消息,代码就会被执行,那么您就必须定义一个协同路由(一个使用async def语法的函数)并使用bot.event修饰符将其注册到bot中。下面是一个基本示例:

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")

如果您希望另一个文件中的协程实际执行discord中的某个操作,最好将该文件设置为cog,它是一个实现discord bot的特定功能的类。你知道吗

你知道吗中心距地址:

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))

你知道吗主.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')

相关问题 更多 >