ErikN118
ErikN118

Reputation: 47

Send message to channel discord.py

I'm having trouble with sending a message to a specific channel, here's the code:

client = discord.Client()

@tasks.loop(seconds=10)
async def test2():
  channel = client.get_channel(836633672240332820)
  await channel.send('test')
  print('test')

test2.start()

I'm getting the following error:

Unhandled exception in internal background task 'test2'.
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/tasks/__init__.py", line 101, in _loop
    await self.coro(*args, **kwargs)
  File "main.py", line 297, in test2
    await channel.send('test')
AttributeError: 'NoneType' object has no attribute 'send'

Any1 able to help?

Upvotes: 1

Views: 3692

Answers (2)

ArtyTheDev
ArtyTheDev

Reputation: 36

You can just make a on_ready def and put test2.start() but that will just loop if you want send it one time put your code in the on_ready

@client.event
async def on_ready():
   test2.start()
@client.event
async def on_ready():
  channel = client.get_channel(836633672240332820)
  await channel.send("test")

Upvotes: 1

Łukasz Kwieciński
Łukasz Kwieciński

Reputation: 15728

You're getting that error because get_channel gets the channel object from the cache, in the first iteration of the loop, the cache is simply not done loading, you can use Client.wait_until_ready in the before_loop function:

client = discord.Client()

@tasks.loop(seconds=10)
async def test2():
    channel = client.get_channel(836633672240332820)
    await channel.send('test')

@test2.before_loop
async def before_test2():
    await client.wait_until_ready()

test2.start()

If the error persists, make sure you copied the correct channel ID.

References:

Upvotes: 1

Related Questions