如何为功能创建单独的文件,然后导入它们?

How to create separate files for functions, then import them?

我有这个工作代码:

from telegram import Update
from telegram.ext import Updater, CommandHandler, CallbackContext

updater = Updater('token')

def hello(update: Update, context: CallbackContext) -> None:
    update.message.reply_text('Hello!')

updater.dispatcher.add_handler(CommandHandler('hello', hello))

updater.start_polling()
updater.idle()

我希望每个函数都有一个单独的文件,并有一个 main.py,我可以在其中导入它们。

所以我开始用这个创建一个 f1.py

def hello(update: Update, context: CallbackContext) -> None:
    update.message.reply_text('Hello!')

然后用

导入到main.py
from f1 import hello
hello()

显然,这是行不通的(缺少参数)。我该如何正确操作?

有关更多信息,这里是导入自己的模块的好资源:

https://docs.python.org/3/tutorial/modules.html

您的 main.pyf1.py 都很好,但是 main.pyupdater.dispatcher 缺少某些东西。试试这个:

from telegram import Update
from telegram.ext import Updater, CommandHandler, CallbackContext

#On my bots I prefer to import the entire module than a function from a module,
#because I usually have users.py (all functions for users), clients.py (all 
#functions for clients), devs.py (all functions for developer's team) and so on
import f1

updater = Updater('token')

#Calling a function from a module must have a callback, as shown bellow
updater.dispatcher.add_handler(CommandHandler('hello', callback = f1.hello))

updater.start_polling()
updater.idle()

试试这个,让我知道它是否适合你!