我正在使用python-telegram-bot开发一个机器人。我在重复其中的某些部分。什么是不重复的最佳做法?
这是我的两个功能的示例。
def logo_design(update, context):
global keyboard
query = update.callback_query
keyboard[0][0] = InlineKeyboardButton(
f'{emojize(":white_check_mark:", use_aliases=True)} Logo Design', callback_data='6')
bot = context.bot
reply_markup = InlineKeyboardMarkup(keyboard)
bot.edit_message_text(
chat_id=query.message.chat_id,
message_id=query.message.message_id,
text="Please choose one of our services\n",
reply_markup=reply_markup
)
def mob_development(update, context):
global keyboard
query = update.callback_query
keyboard[1][0] = InlineKeyboardButton(
f'{emojize(":white_check_mark: Mobile Development", use_aliases=True)} ', callback_data='0')
bot = context.bot
reply_markup = InlineKeyboardMarkup(keyboard)
bot.edit_message_text(
chat_id=query.message.chat_id,
message_id=query.message.message_id,
text="Please choose one of our services\n",
reply_markup=reply_markup
)
return SECOND
您可以看到,我在函数中重复了大多数代码行。我想阻止它。
type
,它将选择要使用的键盘。然后您的代码将是。 # I have re-factored the formatting the code
def function_name(update, context, type):
global keyboard
query = update.callback_query
if type == 0:
keyboard[0][0] = InlineKeyboardButton(
f'{emojize(":white_check_mark:", use_aliases=True)} Logo Design',
callback_data='6')
else:
keyboard[1][0] = InlineKeyboardButton(
f'{emojize(":white_check_mark: Mobile Development", use_aliases=True)} ', callback_data='0')
bot = context.bot
reply_markup = InlineKeyboardMarkup(keyboard)
bot.edit_message_text(
chat_id=query.message.chat_id,
message_id=query.message.message_id,
text="Please choose one of our services\n",
reply_markup=reply_markup
)