我正试图用https://github.com/python-telegram-bot/python-telegram-botPython中的库3。
我想让机器人从稍后更新的词典中向我发送信息。这是我现在的代码:
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"
注意:我不能没有多处理,因为它在我的代码中的其他地方使用
在函数test(update, context)
中,d
实际上没有定义(它存在于代码中,但在test
方法中不可见(。您需要显式使用d
作为全局变量,或者将其添加为函数test
(及其调用方(的参数。