D
D
d3Ka2021-05-31 12:59:34
Python
d3Ka, 2021-05-31 12:59:34

How to stop the execution of a command with a loop through another command or text in pytelegrambotAPI?

I need to stop looping a command in telebot with another command or certain text.
the code:

@bot.message_handler(commands=['soska'])
def daynney(message):
    while True:
        bot.send_message(message.chat.id, 'АРАБСКАЯ НОООЧЬ!')
        if message.text == 'sto':
            break
        sleep(1)
bot.polling()

But it doesn't stop the cycle

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
ya_ne_znau, 2021-05-31
@d3Ka

doesn't bother, because your handler is already working on the command message, which will contain the text from the command. In your example, you can try to register a handler for each message in the loop:

bot.register_next_step_handler(bot.send_message(chat_id, "123"), break_this)
and, accordingly, in the function break_this, implement loop interruption, for example, through flags. You can create a user base with a field responsible for stopping the loop.
from telebot import types

UserId = int  # тайпхинт

class User:
    def __init__(self, user_id: UserId):
        self.user_id = user_id  # неплохо бы property
        self.is_spamming = False  # везде

users: dict[UserId, User] = {}

def stop_spam(message: types.Message):
    users[message.from_user.id].is_spamming = False

@bot.message_handler(<>)
def spam(message: types.Message):
    user = users[message.from_user.id]
    user.is_spamming = True
    while user.is_spamming:
        bot.register_next_step_handler(bot.send_message(<>), stop_spam)  # как-то так

D
d3Ka, 2021-05-31
@d3Ka

Sorry for wasting time. I thought it would be easy and so I asked for help in the messages, I need with photos...
here is the code:

@bot.message_handler(commands=['sosiska'])
def daynneya(message):

    
    while (ba): 
        
        
        monitor = {
            "left": x,
            "top": y,
            "width": 1,
            "height": 1,
        }
        
        img = m.mss().grab(monitor)
        
        img_arr = np.array(img)
        sleep(1)

        monit = {
            "left": x,
            "top": y,
            "width": 1,
            "height": 1,
        }
       
        im = m.mss().grab(monit)
        
        im_arr = np.array(im)
        

        if np.array_equal(img_arr, im_arr) == False:
            snapshot = ImageGrab.grab(bbox=(10,10,1910,1070))
            save_path = "C:\\abeme\\imo.png"
            snapshot.save(save_path)
            photor1 = open('C:\\abeme\\imo.png', 'rb')
            bot.send_photo(message.chat.id, photo=photor1)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question