7

I want my bot to send a message when going online in the on_ready event. The line work in (on_message) but I haven't been able to make it send something in the (on_ready)

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))
    await message.channel.send('The bot is online ')
Sébastien
  • 71
  • 1
  • 1
  • 2
  • Welcome to stackoverflow! Nothing seems wrong with the code you've posted. Could you include more context, or post an error message that you're getting? – Erty Seidohl Jan 26 '20 at 05:50
  • @ErtySeidohl Each time I run the code I get this error. **File "D:/code/python/discord test/discordtest.py", line 12, in on_ready await message.channel.send('The bot is online ') NameError: name 'message' is not defined.** I try to change `message.channel.send('The bot is online ')` to `client .channel.send('The bot is online ')` since `client = discord.Client()` but it doesn't work either. – Sébastien Jan 26 '20 at 16:17
  • @ErtySeidohl With `client .channel.send('The bot is online ')` I get this error. **File "D:/code/python/discord test/discordtest.py", line 11, in on_ready await client.channel.send('The bot is online ') AttributeError: 'Client' object has no attribute 'channel'** – Sébastien Jan 26 '20 at 16:19

3 Answers3

11

You don't have a channel selected to send a message to. First, you need to select a channel, then you can send a message to that channel.

channel = client.get_channel(12324234183172)
await channel.send('hello')

You can get the channel ID by iterating over the list of channels in the connected server:

text_channel_list = []
for server in Client.servers:
    for channel in server.channels:
        if channel.type == 'Text':
            text_channel_list.append(channel)

From How to get all text channels using discord.py?

From How do I send a message to a specific channel? in the discord python FAQ.

Erty Seidohl
  • 4,487
  • 3
  • 33
  • 45
4

the discord.py doesn't seem to take a variable as channel

@client.event
async def on_ready():
   await client.get_channel("enter channel id here").send("bot is online")

I just tried it, and it works perfectly

0

copy your user_id and paste without quotes

    @client.event
    async def on_ready():
        print("The bot is ready")
        print("------------------------")
        user = await client.fetch_user("User id")
        await user.send("hello")