运行 Telegram Bot 时无法中断循环

问题描述

我正在使用 pyTelegramBotAPI 创建一个 Telegram Bot,它发送正在进行的板球比赛的实时更新。我想在用户输入“/stop”命令时中断循环。我查阅了各种来源,也尝试了几种方法来实现相同的目标,但都徒劳无功。循环继续迭代。我最接近的是通过引发错误退出程序。此外,在循环内部时,getUpdates 方法始终返回一个空列表。我还在 GitHub 上为此编写了一个 issue

// display on cart & checkout pages
function filter_woocommerce_get_item_data( $item_data,$cart_item ) {   
    // Compare
    if ( $cart_item['data']->get_type() == 'variation' ) {
        // Get the variable product description
        $description = $cart_item['data']->get_description();
    } else {    
        // Get product excerpt
        $description = get_the_excerpt( $cart_item['product_id'] );
    }       
        
    // Isset & NOT empty
    if ( isset ( $description ) && ! empty( $description ) ) {
        $item_data[] = array(
            'key'     => __( 'Description','woocommerce' ),'value'   => $description,'display' => $description,);
    }
    
    return $item_data;
}
add_filter( 'woocommerce_get_item_data','filter_woocommerce_get_item_data',10,2 );

既然这不起作用,我心甘情愿地使用了这个错误方法

def loop(match_url):
    prev_info = ""
    flag = 1
    #continuously fetch data 
    while flag:
        response = requests.get(match_url)
        info = response.json()['score']
        #display only when the score updates 
        if str(info) != prev_info:
            prev_info = str(info)
            send_msg(info)
        else:
            pass
        send_msg(info)
        #this handler needs to be fixed 
        @bot.message_handler(commands=['stop','end'])
        def stop(message):
            #code to break the loop
            flag = 0
            return
            

这是完整的代码。我还添加了此代码的 GitHub link

while flag:
        response = requests.get(match_url)
        info = response.json()['score']
        if str(info) != prev_info:
            prev_info = str(info)
            send_msg(info)
        else:
            pass
        send_msg(info)
        @bot.message_handler(commands=['stop','end'])
        def stop(message):
            bot.polling.abort = True #an arbitrary function that raises error and exits the program

解决方法

您以错误的方式使用了 telebot(pyTelegramBotAPI) 包:

  1. 为什么在 send_msg 中已经存在 send_message 方法的情况下创建自己的函数 telebot
  2. 您在循环中重新声明了“停止”处理程序,这是错误的!

我给您的建议是学习如何正确使用 pyTelegramBotAPI

这是一个演示代码,可以解决您的问题:

import telebot
from time import sleep

bot = telebot.TeleBot(BOT_TOKEN)
flag = 1

@bot.message_handler(commands=['loop'])
def loop(msg):
    while flag:
        bot.send_message(msg.chat.id,"ping")
        sleep(1)

@bot.message_handler(commands=['stop','end'])
def stop(msg):
    global flag
    flag = 0
    bot.send_message(msg.chat.id,"stopped")


bot.polling(none_stop=True)

说明:

  • flag 声明为全局变量并将其设置为 1
  • “循环”处理程序,用于启动每秒向您发送“ping”消息的循环
  • “stop”处理程序将 flag 更改为 0,从而终止您的运行循环

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...