Ask coding questions

← Back to all posts
How do I randomize responses?
Carnelian (3)

Is there a way to give a bot a short list in the code so it can generate out one of a few responses? If someone types in p.h, the bot could respond with hi, hello, or hey. I've so far only seen tutorials that use APIs for random generation, but I don't need anything like that.

Comments
hotnewtop
AndrewMarkarian (15)

@Carnelian You can import a random and make a list.
ex:

Roles = ["Imposter", "Crewmate", "Crewmate", "Crewmate", "Crewmate", "Imposter", "Crewmate", "Crewmate", "Crewmate", "Crewmate"]

Then you can make the random. It can be stored in a variable for future use of the same random.
ex:

Roles = random.choice(Roles)

or

random.choice(Roles)

The make the code do anything you want.
ex:

if Role == ("Imposter"):
  print("Imposter")
  print(Name)
  print(random.choice(Character))
elif Role == ("Crewmate"):
  print("Crewmate")
  print("There are two imposters among us.")

Hope that helps!

tristans2 (0)
from random import choice

print(choice(responses))

all you need to do is put in a different list for the different types of responses and ur good

heyitsmarcus (342)

It looks like you have a myriad of conditions, some using startswith() and some just using in. I guess the first thing I would ask is why not just use the in nomenclature instead of using startswith that way you can have a consistent format. And then secondly, you should separate all of those responses into a function that you can call with particular content like I'm going to do below.

Ideally, you would store all responses in a database, JSON store, and anywhere else with persistent storage and remove all of the if statements and just retrieve the appropriate response based on the message content. But for now, just moving the logic out of the event into its own function will clean up that event a lot and separate things out nicely.

async def probeForResponse(message):
    if "What" in message.content:
        await message.add_reaction("Lacie:822228153685508156")
    #all of the other logic would be here

And then inside of the client event where a message is posted, call the probeForResponse function.

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    await probeForResponse(message)

Good luck to you, Carnelian!