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

2024-09-28 03:21:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从python代码的其他部分开始和停止while循环 而且效果不好。你知道吗

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

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)

Tags: textviewtruemessageifbotpostdo
1条回答
网友
1楼 · 发布于 2024-09-28 03:21:31

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)

相关问题 更多 >

    热门问题