Discord.py send message to specific channel

I would like to send a message in a specific text channel no matter on which server, so I cannot hard-code the ID of my channel.

This part of the code is working :

    @client.event
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))

But my problem is this part witch is in a Cog :

import discord, httplib2, random, string
from discord.ext import commands
from datetime import datetime
from discord.ext.commands import cooldown
from discord.utils import find
class Cog01(commands.Cog):

    def __int__(self, client):
        self.client = client



    @commands.Cog.listener()
    async def on_ready(self):
        print('Cog01 is loaded')

        fff = find(lambda x: x.name == 'general',  guild.text_channels)


def setup(client):
    client.add_cog(Cog01(client))

I got this error :

NameError: name 'guild' is not defined

I tried a lot of things, sometimes the error disappeared but it still didn't work.

I am sure it's possible, I lost a older version of my code that worked.

I've been searching for a solution for several hours but the solution might be really simple, I'm new to programming.

1 answer

  • answered 2020-07-10 12:01 Mr_Spaar

    commands.Bot has a guilds attribute that returns a list of every guild the client is connected to.
    Then every Guild object has a system_channel attribute. This is on this channel that messages like User has joined are sent.

    For instance, if you want to send a message on these channels when your bot is ready, you can do it this way:

    from discord.ext import commands
    
    class Cog01(commands.Cog):
        def __int__(self, client):
            self.client = client
    
        @commands.Cog.listener()
        async def on_ready(self):
            for guild in self.client.guilds:
                await guild.system_channel.send("I'm ready to go!")
    
    def setup(client):
        client.add_cog(Cog01(client))