Cr3
Cr3

Reputation: 159

How to edit an embed within a while loop using Discord.py?

Within a while loop that will execute 100 times, I want to edit a discord embed to be continually updating over the interval with new data. However, I can only achieve this by making a new embed every time, rather than just updating one.

Here is what I have currently:

    url = f'https://someapirequest'
    count = 0
    real_embed = discord.Embed(colour=0xFF8300)
    user_msg = await ctx.send(embed=real_embed)
    while not client.is_closed():
        try:
            msg = await client.wait_for("message",timeout=10)
            try: await msg.delete()
            except Exception: pass
            try:
                count+=1
                response = requests.get(url,headers={'User-agent': 'Mozilla/5.0'})
                data = json.loads(response.text)
                pj = parse_json(data)
                price = pj['data1']
                volume = pj['data2']
                marketRange = pj['data3']
                high = pj['data4']
                low = pj['data5']
                update_embed = discord.Embed(colour=0xFF8300,title=f"{symbol} Realtime Data:",description=f'Price: ${price} Volume: {volume} Range: {marketRange} High: ${high} Low: ${low} Count: {str(count)}')
                await user_msg.edit(embed=update_embed)
                if count == 100: break 
            except Exception: print("Error")   
        except asyncio.TimeoutError: 
            print("Stopped")

I noticed that when testing it with print statements, nothing is run after declaring the user_msg variable equal to await ctx.send(embed = real_embed), why is that the case? Or is there another way to edit one embed?

Upvotes: 0

Views: 154

Answers (1)

TimG233
TimG233

Reputation: 636

This is because you need to declare title or description for your embed in order to send it. (at least one of them). So, basically the real_embed is an invalid one to send in this circumstance since it only declares colour.
Also, editing message continuously without a cooldown is dangerous. It can let your bot getting rate-limited easily by discord if there are a lot of qualified messages to process.
Last suggestion, requests library is a good library but it is blocking since you want the async version. Consider changing requests library to aiohttp. See documentation here

Upvotes: 1

Related Questions