gpt4 book ai didi

Python Not - 将参数传递给命令处理程序

转载 作者:行者123 更新时间:2023-11-28 18:20:15 25 4
gpt4 key购买 nike

我正在玩 Python Telegram Bot,我想将通过先前计算获得的参数传递给我的处理程序,例如:

def my_handler(bot, update, param):
print(param)

def main():
res = some_function()
updater.dispatcher.add_handler(CommandHandler('cmd', my_handler))

如何将参数传递给处理程序?

最佳答案

在版本 12 的 python-telegram-bot 中,参数作为列表位于属性 CallbackContext.args 中。这是一个通用示例:

def my_handler(update, context):
print(context.args)

def main():
res = some_function()
updater.dispatcher.add_handler(CommandHandler('cmd', my_handler))

一个简单的例子是将两个整数相加:

import logging
from config import tgtoken
from telegram.ext import Updater, CommandHandler

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)

logger = logging.getLogger(__name__)

def error(update, context):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, context.error)

def sum(update, context):
try:
number1 = int(context.args[0])
number2 = int(context.args[1])
result = number1+number2
update.message.reply_text('The sum is: '+str(result))
except (IndexError, ValueError):
update.message.reply_text('There are not enough numbers')

def main():
updater = Updater(tgtoken, use_context=True)
dp = updater.dispatcher
dp.add_handler(CommandHandler("sum", sum))
dp.add_error_handler(error)
updater.start_polling()
updater.idle()

if __name__ == '__main__':
main()

如果您发送/sum 1 2,您的机器人将回答The sum is: 3

关于Python Not - 将参数传递给命令处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45537938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com