Как заставить бота Discord отправлять случайную серию слов из списка, но не повторно? - PullRequest
2 голосов
/ 27 мая 2020

Я пытаюсь указать программу для своего Discord-бота. Хорошо, у меня есть список fun_facts ниже, и когда пользователь вводит команду !funfact, я хочу, чтобы мой бот отправлял случайный факт из списка, но не повторно. Таким образом, каждый раз, когда выполняется команда, использованные факты не повторяются и не отправляются снова.

Вот код: Мы будем благодарны за любую помощь по его улучшению.

@client.event
async def on_message(message):

    fun_facts = ["Banging your head against a wall for one hour burns 150 calories.",
                 "Snakes can help predict earthquakes.",
                 "7% of American adults believe that chocolate milk comes from brown cows.",
                 "If you lift a kangaroo’s tail off the ground it can’t hop.",
                 "Bananas are curved because they grow towards the sun."]

        if message.content.startswith("!funfact"):
            await message.channel.send(random.choice(fun_facts))

1 Ответ

2 голосов
/ 27 мая 2020

Попробуйте это, чтобы каждый раз использовать разные факты, пока список не будет исчерпан. Вы также получаете обновленный список каждый раз, когда ваш бот перезагружается.

all_fun_facts = ["Banging your head against a wall for one hour burns 150 calories.",
                 "Snakes can help predict earthquakes.",
                 "7% of American adults believe that chocolate milk comes from brown cows.",
                 "If you lift a kangaroo’s tail off the ground it can’t hop.",
                 "Bananas are curved because they grow towards the sun."]
fun_facts = all_fun_facts.copy()

@client.event
async def on_message(message):

        if message.content.startswith("!funfact"):
            try:
                fact = random.choice(fun_facts)
            except IndexError: # the list of fun facts is empty
                fun_facts = all_fun_facts.copy()
                fact = random.choice(fun_facts)
            await message.channel.send(fact)
            fun_facts.remove(fact)

Если вы хотите, чтобы список обновлялся только тогда, когда он пуст, попробуйте записать свой список в файл:

from fun_facts import all_fun_facts

fun_facts = all_fun_facts.copy()

@client.event
async def on_message(message):

        if message.content.startswith("!funfact"):
            try:
                fact = random.choice(fun_facts)
            except IndexError: # the list of fun facts is empty
                fun_facts = all_fun_facts.copy()
                fact = random.choice(fun_facts)
            await message.channel.send(fact)
            fun_facts.remove(fact)

Пример файловое хранилище (fun_facts.py)

__all__ = ['all_fun_facts']
all_fun_facts = ["Banging your head against a wall for one hour burns 150 calories.",
                 "Snakes can help predict earthquakes.",
                 "7% of American adults believe that chocolate milk comes from brown cows.",
                 "If you lift a kangaroo’s tail off the ground it can’t hop.",
                 "Bananas are curved because they grow towards the sun."]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...