N
N
nik_neznay2020-10-30 18:56:11
Python
nik_neznay, 2020-10-30 18:56:11

How to move random string to variable every second in python?

I am writing a python discord bot that displays a random line from a .txt file in response to a command. How can I loop a random string input into a variable?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Nevzorov, 2020-10-30
@nik_neznay

The answer proposed by Sergey will most likely not work in the context of discord.py, as it will block the event loop every second. An asyncio solution is needed here.
In general, discord.py has a built-in tool for tasks: discord.ext.tasks

random_strings = ["abc", "bcd", "etc"]  # список строк, из файла/откуда угодно. Для чтения больших файлов может пригодиться https://github.com/Tinche/aiofiles
@tasks.loop(seconds=1)
async def update_text():
    text_variable = random.choice(random_strings)  # если список большой, возможно может понадобиться run_in_executor, но я в этом не уверен

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question