Reputation: 13
This is supposed to send a message in the channel every 15 minutes. For some reason, it's not working. It doesn't show any error either. Can someone help me fix this?
import time
from discord.ext import commands
message = 'choose roles from <#728984187041742888>'
channel_id = 742227160944869437 # the channel id (right click on the channel to get it)
time_spacing = 15*60 # s : 15min
class auto(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def spamm(self, ctx):
while True:
time.sleep(time_spacing)
await ctx.get_channel(channel_id).send(message)
@commands.Cog.listener()
async def on_ready(self):
print(f'Sp4mm3r {self.bot.user} has connected to Discord!')
print('Sending message :', message, 'every', time_spacing, 'seconds')
def setup(bot):
bot.add_cog(auto(bot))
----------corrected version----------- figured the issue was that i didn't start the task, and time.sleep wasn't meant to be used there.
from discord.ext import tasks
from discord.ext import commands
time = 30*60
class Automessager(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.message = 'Choose roles from <#728984187041742888>'
self.channel1 = 725550664561983519
self.text.start()
@tasks.loop(seconds=time)
async def text(self):
try:
channel = self.bot.get_channel(self.channel1)
await channel.send(self.message)
except Exception as e:
print(e)
@commands.Cog.listener()
async def on_ready(self):
print(f'{self.bot.user} has connected to Discord!')
print(f'Sending message: {self.message} every {time} seconds')
def setup(bot):
bot.add_cog(Automessager(bot))
Upvotes: 0
Views: 2896
Reputation: 3994
There's two errors in your code:
get_channel()
is a commands.Bot
method, not a discord.Context
method.time.sleep()
to wait 15 minutes, it will freeze your entire cog.To make loops, you can use task.loop()
, instead of using cog listeners:
from discord.ext import task
from discord.ext import commands
class auto(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.message = 'Choose roles from <#728984187041742888>'
self.channel_id = 742227160944869437
self.minutes = 15
@task.loop(minutes=self.minutes)
async def spamm(self, ctx):
channel = self.bot.get_channel(self.channel_id)
await channel.send(self.message)
@commands.Cog.listener()
async def on_ready(self):
print(f'Sp4mm3r {self.bot.user} has connected to Discord!')
print(f'Sending message: {self.message} every {self.minutes} minutes')
def setup(bot):
bot.add_cog(auto(bot))
PS: I've set channel_id
, message
and minutes
as class variables. You also don't need to use time.sleep()
.
Upvotes: 1