简体   繁体   English

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

[英](Python3)Passing an object to an imported module function

I am importing a module I created to a python file which I plan to run as main. 我将我创建的模块导入到计划作为main运行的python文件中。

In the module, I have a function, 在模块中,我有一个功能,

def coms(message, instRole):

where instRole is supposed to be an instance of a class 其中instRole应该是类的实例


In my main python file, I have an object, 在我的主要python文件中,我有一个对象,

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. 但是,永远不会调用函数coms。 I have put in print statements in coms to make sure it is called, and it is not. 我已经在coms中放入了print语句,以确保它被调用了,但事实并非如此。

Thank you for your help ahead of time 谢谢您的帮助

If you're trying to take advantage of 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. 如果您试图利用事件,则在bot看到消息时将执行代码,那么您需要定义一个协程 (使用async def语法的函数)并使用bot.event装饰器将其注册到您的机器人。 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,这是为discord bot实现特定功能的类。

cog.py: 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: 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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM