在函数内获取变量更新(Telegram bot、Python3、python-telegram-bot 库、多处理)
Posted
技术标签:
【中文标题】在函数内获取变量更新(Telegram bot、Python3、python-telegram-bot 库、多处理)【英文标题】:Getting variables updates inside a function (Telegram bot, Python3, python-telegram-bot library, multiprocessing) 【发布时间】:2020-06-20 06:16:16 【问题描述】:我正在尝试用 python3 中的https://github.com/python-telegram-bot/python-telegram-bot 库制作一个电报机器人。
我想让机器人从稍后会更新的字典中向我发送信息。这是我现在的代码:
from secret import botToken
import logging
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from multiprocessing import Process, Manager
def f(dicts):
dicts['runNumber'] = 1
def runUp(dicts):
dicts['runNumber'] += 1
############################# Telegram Bot part #################################
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
def botStart(update, context):
"""Send a message when the command /start is issued."""
update.message.reply_text("Hey ! do /help or /test ")
def test(update, context):
"""Send a message when the command /test is issued."""
runUp(d)
update.message.reply_text("run number is now : 0".format(d['runNumber']))
def help(update, context):
"""Send a message when the command /help is issued."""
update.message.reply_text("HELP !!")
def echo(update, context):
"""Send a message when message without command is issued."""
update.message.reply_text("echo")
def error(update, context):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, context.error)
def main():
"""Start the bot."""
updater = Updater(botToken, use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", botStart))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("test", test))
# on noncommand i.e message - answer in telegram
dp.add_handler(MessageHandler(Filters.text, echo))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
#################################################################################
if __name__ == '__main__':
manager = Manager()
d = manager.dict()
p1 = Process(target=f, args=(d,))
p1.start()
p1.join()
p2 = Process(target=main)
p2.start()
但每次我运行 /test 命令时,我都会从 python 窗口中的日志记录中获得此反馈:
... caused error "name 'd' is not defined"
注意:我不能没有多处理,因为它在我的代码中的其他地方使用
【问题讨论】:
【参考方案1】:在函数test(update, context)
中,d
确实没有定义(它存在于代码中,但在test
方法中不可见)。您需要显式使用d
作为全局变量或将其添加为函数test
(及其调用者)的参数。
【讨论】:
您可以使用bold
或其他方式来增强您的文本格式。检查editing-help以上是关于在函数内获取变量更新(Telegram bot、Python3、python-telegram-bot 库、多处理)的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 Telegram Bot API 获取 Telegram 频道用户列表