theCarnage
theCarnage

Reputation: 23

How do I send a message to a specific discord channel while in a task loop?

import discord
from discord.ext import commands, tasks
from discord_webhook import DiscordWebhook

client = discord.Client()
bot = commands.Bot(command_prefix="$")

@tasks.loop(seconds=15.0)
async def getAlert():
   #do work here
   channel = bot.get_channel(channel_id_as_int)
   await channel.send("TESTING")

getAlert.start()
bot.run(token)

When I print "channel", I am getting "None" and the program crashes saying "AttributeError: 'NoneType' object has no attribute 'send' ".

My guess is that I am getting the channel before it is available, but I am unsure. Anybody know how I can get this to send a message to a specific channel?

Upvotes: 0

Views: 724

Answers (1)

Bagle
Bagle

Reputation: 2346

Your bot cannot get the channel straight away, especially if it's not in the bot's cache. Instead, I would recommend to get the server id, make the bot get the server from the id, then get the channel from that server. Do view the revised code below.

@tasks.loop(seconds=15.0)
async def getAlert():
   #do work here
   guild = bot.get_guild(server_id_as_int)
   channel = guild.get_channel(channel_id_as_int)
   await channel.send("TESTING")

(Edit: Including answer from comments so others may refer to this)

You should also ensure that your getAlert.start() is in an on_ready() event, as the bot needs to start and enter discord before it would be able to access any guilds or channels.

@bot.event
async def on_ready():
   getAlert.start()
   print("Ready!")

Helpful links:

Upvotes: 2

Related Questions