0
votes

I have an array I want to send a handful of messages in a for loop with discord.py. I am trying to use the on_ready() command but having a problem with it only sending the first message. I'm fairly new to both async and discord bots. There must be a simpler solution here...

client = discord.Client()
links = []
for x in y:
    # do some things
    links.append(stuff)

@client.event
async def on_ready():
    channel = client.get_channel(12345678910)
    for link in links:
        await channel.send(link)


client.run(DISCORD_TOKEN)

Thanks for any help in advance!

2
Can you provide an example of what your array looks like? - Jawad
They are just a bunch of URL strings. ['google.com', 'amazon.com', 'facebook.com'] - Mojo713
And you want them to be sent to channel when the bot is ready? - Jawad
Correct, just want to dump them into the channel one by one - Mojo713

2 Answers

0
votes

Instead of adding your code under the on_ready() event you could create a loop that runs 1 time once the bot is ready then stops. To create a loop use discord.ext.tasks.

from discord.ext.tasks import loop

@loop(count=1)
async def send_links():
    channel = client.get_channel(730064641857683581)
    links = ['link1', 'link2', 'link3', 'link4']
    for link in links:
        await channel.send(link)


@send_links.before_loop
async def before_send_links():
    await client.wait_until_ready()  # Wait until bot is ready.

@send_links.after_loop
async def after_send_links():
    await client.logout()  # Make the bot log out.


send_links.start()
client.run(DISCORD_TOKEN)
0
votes

At first, client = discord.Client() is absolutely not good for defining client. You should define the client with

client = commands.Bot(command_prefix='command's prefix here'). Then if you want to make it a command, you can do this:

@client.command()
async def send_link(ctx):
    for link in links:
        await ctx.send(link)

But that's not good because it'll send so many messages, so I'd rather to use embeds:

async def send_link(ctx):
    embed = discord.Embed()
    for link in links:
        embed.add_field(name=" ", value=link, inline=False)
    await ctx.send(embed=embed)

You shouldn't make it in on_message because that's meaningless. And in the code, you did channel = client.get_channel(1234667890). That's also a problem, you have to change it with a real channel id.