0
votes

I want my Discord bot to send a certain message, For example: "Hello" when he joins a new server. The bot should search for the top channel to write to and then send the message there. i saw this, but this isn't helpful to me

async def on_guild_join(guild):
    general = find(lambda x: x.name == 'general',  guild.text_channels)
    if general and general.permissions_for(guild.me).send_messages:
        await general.send('Hello {}!'.format(guild.name))```
1
The code you posted should find the channel named "general" and write a message in it. What is not working with it? Do you get any errors?chluebi
I know, but I don't want to search for a channel with the name general, I want to find the top channel in which the bot can writeLordGaming

1 Answers

1
votes

The code you used is actually very helpful, as it contains all of the building blocks you need:

  • The on_guild_join event
  • The list of all channels in order from top to bottom (according to the official reference). If you want to get the "top channel" you can therefore just use guild.text_channels[0]
  • checking the permissions of said channel
async def on_guild_join(guild):
    general = guild.text_channels[0]
    if general and general.permissions_for(guild.me).send_messages:
        await general.send('Hello {}!'.format(guild.name))
    else:
        # raise an error

Now one problem you might encounter is the fact that if the top channel is something like an announcement channel, you might not have permissions to message in it. So logically you would want to try the next channel and if that doesn't work, the next etc. You can do this in a normal for loop:

async def on_guild_join(guild):
    for general in guild.text_channels:
        if general and general.permissions_for(guild.me).send_messages:
            await general.send('Hello {}!'.format(guild.name))
            return
    print('I could not send a message in any channel!')

So in actuality, the piece of code you said was "not useful" was actually the key to doing the thing you want. Next time please be concise and say what of it is not useful instead of just saying "This whole thing is not useful because it does not do the thing I want".