D
D
dddaaammmeee2022-02-06 20:38:46
Python
dddaaammmeee, 2022-02-06 20:38:46

How to regenerate it after displaying a random list?

As it is now:
Text is being generated, output to the user at the request of the bot. But the next time the user requests a click, the text does not update.
How can I make it so that each click of the button (User Request) updates the text generator and displays a new one?

import telebot
from telebot import types
import numpy as np

text = open('text.txt', encoding='utf-8').read()

foundation = text.split()

def make_pairs(foundation):
    for i in range(len(foundation) - 1):
        yield (foundation[i], foundation[i + 1])

pairs = make_pairs(foundation)

words = {}

for word_1, word_2 in pairs:
    if word_1 in words.keys():
        words[word_1].append(word_2)
    else:
        words[word_1] = [word_2]

first_word = np.random.choice(foundation)

while first_word.islower():
    first_word = np.random.choice(foundation)

chain = [first_word]

n_words = 100

for i in range(n_words):
    chain.append(np.random.choice(words[chain[-1]]))

print(' '.join(chain))

TOKEN = 'Здесь должен быть токен'

bot = telebot.TeleBot(TOKEN)
 
@bot.message_handler(commands=['start'])
def welcome(message):
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    item1 = types.KeyboardButton('Кнопка')
 
    markup.add(item1)
 
    bot.send_message(message.chat.id, 'Привет <3'.format(message.from_user, bot.get_me()),
        parse_mode='html', reply_markup=markup)

@bot.message_handler(content_types=['text'])
def bot_message(message):
    if message.chat.type == 'private':
        if message.text == 'Кнопка':
            bot.send_message(message.chat.id,(' '.join(chain)))
     
bot.polling(none_stop=True, interval=0)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2022-02-07
@Vindicar

Очевидно, внести код генерации случайного текста внутрь обработчика.
Снаружи можно оставить только неизменные части - например, всё что до работы с random.choice().
К слову, а накой огурец ты подключаешь сюда numpy? Чем тебя встроенный random не устроил?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question