Получение обновлений переменных внутри функции (бот Telegram, библиотека Python3, python -telegram-bot, многопроцессорная обработка) - PullRequest
0 голосов
/ 08 марта 2020

Я пытаюсь создать бот-телеграмму с библиотекой https://github.com/python-telegram-bot/python-telegram-bot в python3.

Я хочу, чтобы бот отправлял мне информацию из словаря, который будет обновляться позже. Теперь это мой код:


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 Ответ

0 голосов
/ 25 апреля 2020

В функции test(update, context), d действительно не определено (присутствует в коде, но не видно из метода test). Вам необходимо явно использовать d в качестве глобальной переменной или добавить ее в качестве параметра функции test (и она вызывает).

...