discord.py- How would I send a message to a random channel?

9

I'm trying to make a bot that will send a random message to a randomly selected channel when a user sends a specific message.

I have no idea how to approach this problem beyond getting all of the channel ids and manually adding them to a list, then randomly selecting from this list, but there are some very big problems with this approach and it just wouldn't work. I've tried looking through the documentation, but I haven't been able to figure out a way to do what I want.

In short: I need a way to automatically collect all of the channel ids in the discord server, add them to an empty list, then be able to send a message to a randomly selected channel in the list.

answered question

1 Answer

7

I don't see why there is a "big problem" with the way you described. Below is a short snippet that would do exactly what you described:

import random
client = discord.Client()
@client.event
async def on_ready():
    # assuming the bot is connected to only one guild
     guild = client.guilds[0]
     await random.choice(filter(guild.text_channels).send("message goes here")
client.run(token)

It can also be achieved with the commands extension with relatively little modification of the above snippet.

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories