使用python从代码中的其他部分循环时启动和停止

使用python从代码中的其他部分循环时启动和停止,python,py-telegram-bot-api,Python,Py Telegram Bot Api,我试图从python代码的其他部分开始和停止一个while循环 而且效果不好 我正在使用pyTelegramBotAPI将一些帖子发布到我的机器人上,但它似乎不起作用: RunPosts = True @bot.message_handler(commands=['do','dontdo']) def KillOrLive(message: telebot.types.Message): if message.text == '/do': RunPosts = True

我试图从python代码的其他部分开始和停止一个while循环 而且效果不好

我正在使用pyTelegramBotAPI将一些帖子发布到我的机器人上,但它似乎不起作用:

RunPosts = True

@bot.message_handler(commands=['do','dontdo'])
def KillOrLive(message: telebot.types.Message):
    if message.text == '/do':
        RunPosts = True
        print('OK')
    elif message.text == '/dontdo':
        RunPosts = False



while RunPosts == True:
    for post in posts:
        btn = telebot.types.InlineKeyboardMarkup()
        view = telebot.types.InlineKeyboardButton("Get Product", url="t.me/{}".format(post.username))
        btn.row(view)
        if post.kind == 'photo':
            bot.send_photo(admins[0],post.file_id,post.caption,reply_markup=btn)
            time.sleep(2)

bot.polling(none_stop=True)
KillOrLive()正在创建名为RunPosts的局部变量,但不会更改全局变量

只要加一行就行了

    global RunPosts
行后:

def KillOrLive(message: telebot.types.Message):
您可能还需要更改以下代码

while RunPosts == True:
    for post in posts:
        btn = telebot.types.InlineKeyboardMarkup()
        view = telebot.types.InlineKeyboardButton("Get Product", url="t.me/{}".format(post.username))
        btn.row(view)
        if post.kind == 'photo':
            bot.send_photo(admins[0],post.file_id,post.caption,reply_markup=btn)
            time.sleep(2)

如果你一遇到一个帖子就想停下来,这会告诉你停下来

请再添加一次打印以更好地调试:

我建议更换:

bot.polling(none_stop=True)


我已经试过了,但它仍然不起作用:/这就是为什么我问我不知道问题出在哪里,我建议您更正代码(在问题中添加全局),如果没有全局,它肯定不起作用。有了全局,它应该只是添加了你说的全局,但是它仍然不工作,相同的属性打印OK,但是循环没有运行,我不明白。这不是你想要的吗?(循环停止运行)也许您可以发布打印输出,并告诉哪里出了问题(此时您可能会期望另一个打印)在
KillOrLive
内部,您必须使用
global RunPosts
通知函数必须将
True/False
分配给外部/全局变量
RunPosts
。当前函数创建局部变量
RunPosts
,它与全局变量
RunPosts
无关,全局变量
RunPosts
循环中使用。@furas我已经按照gelonida说的做了,。但它仍然不起作用我还建议在elif案例中添加一个打印(“不确定”),并在问题代码中KillOrLive()的开头添加一个打印(“调用回调”),请同时发布这些打印的输出。到目前为止,我们(因为我们无法运行您的脚本)甚至不知道是否调用了回调。当我发送“/do”命令时,它将打印到终端“OK”,但循环没有启动这是输出“回调被调用OK”
bot.polling(none_stop=True)
print("Loop has been ended")
bot.polling(none_stop=True)