C
C
crinnyx2021-03-11 18:34:29
Python
crinnyx, 2021-03-11 18:34:29

Endless loop in simple Telegram Bot?

import telebot 
import random

bot = telebot.TeleBot('TOKEN')

print("Bot started")

@bot.message_handler(commands=['start'])
def start_message(message):
    bot.send_message(message.chat.id, '/random')

chars = '1234567890'
number = 10
length = 6

for n in range(number):
    password = ''
    for i in range(length):
        password += random.choice(chars)

@bot.message_handler(content_types=['text'])
def send_text(message):
    if message.text.lower() == '/random':
    	bot.send_message(message.chat.id, 'Your code: ' + password)

bot.polling()


In general, I need him to endlessly generate these codes, and not constantly the same one, as he does now. I don’t know how to make random an infinite loop so that it generates and sends new ones with each command written.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MinTnt, 2021-03-11
@crinnyx

Redo the code a bit, since at the moment it generates random code only once.
In the function itself, add before

bot.send_message(message.chat.id, 'Your code: ' + password)

line
password = ''.join([str(random.randint(0, 9)) for x in range(length)])

And this text
for n in range(number):
    password = ''
    for i in range(length):
        password += random.choice(chars)

Temporarily remove

M
Maxim Siomin, 2021-03-11
@MaxSiominDev

import telebot 
import random

bot = telebot.TeleBot('TOKEN')

print("Bot started")

@bot.message_handler(commands=['start'])
def start_message(message):
    bot.send_message(message.chat.id, '/random')

chars = '1234567890'
number = 10
length = 6

def password():
    for n in range(number):
        password = ''
        for i in range(length):
            password += random.choice(chars)
        return password
        

@bot.message_handler(content_types=['text'])
def send_text(message):
    if message.text.lower() == '/random':
    	bot.send_message(message.chat.id, 'Your code: ' + password())

bot.polling()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question