简体   繁体   中英

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

I have this working code:

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

I wish to have a separate file for each function and have a main.py where I import them.

So I head to create a f1.py with just this:

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

Then import it into a main.py with

from f1 import hello
hello()

Obviously, this is not working (missing arguments). How do I do it correctly?

For more informations, here is a good source for import own modules:

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

Your main.py and f1.py are fine, but on updater.dispatcher of your main.py something is missing. Try this:

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

Try this and let me know if it worked for you!

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.

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