Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

discord.py - Programming a Discord bot in Python- How do I make it automatically send messages?

I want to make my bot automatically send an image to a channel every ten minutes. Here's my code:

def job():
  channel = client.get_channel(803842308139253760)
  channel.send(file=discord.File(random.choice('image1', 'image2', 'image3))

schedule.every(10).minutes.do(job)

while True:
  schedule.run_pending()
  time.sleep(1)

I know that the schedule works. But for some reason, it can't send the message. I get this error: AttributeError: 'NoneType' object has no attribute 'send'. I'm new to programming, so any insight would be greatly appreciated!

question from:https://stackoverflow.com/questions/65923898/programming-a-discord-bot-in-python-how-do-i-make-it-automatically-send-message

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're getting that error because the channel variable is None (a NoneType doesn't have any attributes/methods) because the channel it's not in the internal cache, you're blocking the whole thread so it never loads. I'm guessing I could fix your code but is a really bad solution to background tasks. Fortunately discord.py comes with a built-in extension for doing such things, here an example:

from discord.ext import tasks

@tasks.loop(minutes=10) # You can either pass seconds, minutes or hours
async def send_image(channel: discord.TextChannel):
    image = discord.File("path here")
    await channel.send(file=image)


# Starting the task (you can also do it on the `on_ready` event so it starts when the bot is running)
@client.command()
async def start(ctx):
    channel = client.get_channel(ID_HERE)
    send_image.start(channel)


# Using the `on_ready` event
@client.event
async def on_ready():
    await client.wait_until_ready() # Waiting till the internal cache is done loading

    channel = client.get_channel(ID_HERE)
    send_image.start(channel)


@client.command()
async def stop(ctx):
    send_image.stop()

Reference:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...