首页 > 解决方案 > 使用python从代码中的其他部分开始和停止while循环

问题描述

我正在尝试从我的 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)

标签: pythonpy-telegram-bot-api

解决方案


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)

while RunPosts:
    for post in posts:
        print("handling post", str(post)[:30])
        if not RunPosts:
            print("I was told to stop, so this is what I do")
            break
        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)

print("Loop has been ended")
bot.polling(none_stop=True)

推荐阅读