I have a problem: I can’t send message in a @tasks.loop() function.
When I try to get the channel object with self.client.get_channel(channlid)
, it return me a Nonetype variable.
My code :
JavaScript
x
27
27
1
import nextcord
2
from nextcord.ext import commands
3
from nextcord.ext import tasks
4
from datetime import date, datetime
5
6
channlid = 934533675083792465
7
global channel
8
def setup(client):
9
client.add_cog(Blagues(client))
10
11
class Blagues(commands.Cog):
12
def __init__(self, client):
13
self.client = client
14
self.index = 0
15
self.blaguedujour.start()
16
17
@tasks.loop(seconds=1)
18
async def blaguedujour(self):
19
channel = self.client.get_channel(channlid)
20
channel.send("a")
21
22
23
24
@commands.command()
25
async def test(self, ctx):
26
await ctx.send("test")
27
my error:
JavaScript
1
9
1
PS C:Usersbaron_btjit4i> & C:/Users/baron_btjit4i/AppData/Local/Programs/Python/Python39/python.exe c:/Users/baron_btjit4i/Desktop/Autrebot/main.py
2
Unhandled exception in internal background task 'blaguedujour'.
3
Traceback (most recent call last):
4
File "C:Usersbaron_btjit4iAppDataLocalProgramsPythonPython39libsite-packagesnextcordexttasks__init__.py", line 168, in _loop
5
await self.coro(*args, **kwargs)
6
File "c:Usersbaron_btjit4iDesktopAutrebotCogsblagues.py", line 20, in blaguedujour
7
channel.send("a")
8
AttributeError: 'NoneType' object has no attribute 'send'
9
Can you help me ?
Advertisement
Answer
Problem
You’re calling client.get_channel
before the client is ready. So, the client cannot find the channel you’re looking for, and channel
becomes None
.
This happens because you are starting blaguedujour
in the initialization of your Blagues
class.
Solution
Explanation
Instead of starting the task in __init__
, you should start in when the client is ready, in on_ready
. This can be accomplished by adding a commands.Cog.listener()
in your Blagues
cog.
Code
JavaScript
1
19
19
1
class Blagues(commands.Cog):
2
def __init__(self, client):
3
self.client = client
4
self.index = 0
5
6
@tasks.loop(seconds=1)
7
async def blaguedujour(self):
8
channel = self.client.get_channel(channlid)
9
channel.send("a")
10
11
@commands.Cog.listener()
12
async def on_ready():
13
self.blaguedujour.start()
14
15
16
@commands.command()
17
async def test(self, ctx):
18
await ctx.send("test")
19
Aside
channel.send()
is a coroutine: it must be awaited. Use await channel.send("a")
instead.