Answer the question
In order to leave comments, you need to log in
How to kill streams that I myself created?
Hello.
The thing is.
There is a telegram bot.
When sending a command to the bot, for example, /check 192.168.0.1, it creates a thread with the name "sender id + address" (in our example, the address will be 192.168.0.1).
In this thread, a loop is endlessly executed in which the address is pinged and the results are sent back to the one who created this thread.
After some time, some of the threads need to be nailed, and some should be left.
Accordingly, I send a command for example / kill 192.168.0.1
and how can I now kill a thread with the name "sender id + address"
how to get all active threads, I understand:
for i in range(threading.active_count()):
print(threading.enumerate()[i])
import threading, random, time, telebot
bot = telebot.TeleBot('276349923:AAGq2JkAib-OwGo-SrW1lHbh4CTPVFmY0ns')
@bot.message_handler(commands=['cr'])
def handle_text(message):
param = str(random.randint(1, 1000))
threadname = str(message.from_user.id) + " " + param
th = threading.Thread(target=inffync, name=threadname, args=[param])
th.start()
@bot.message_handler(commands=['list'])
def handle_text(message):
for i in range(threading.active_count()):
print(threading.enumerate()[i])
@bot.message_handler(commands=['kill'])
def handle_text(message):
print("Хочу убивать потоки созданные " + str(message.from_user.id))
def inffync(p):
while True:
print(str(random.randint(1, 1000)) + " " + p)
time.sleep(5)
bot.polling(none_stop=True, interval=0)
Answer the question
In order to leave comments, you need to log in
The loop checks for a flag (exit condition) initially set to False but reset to True by the /kill command handler. It is convenient to use dict to assign exit flags to individual threads.
Accordingly, I send the command
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question