Ozymandias
Ozymandias

Reputation: 93

When running .render() (from requests_html) in an asyncio event loop, I get the error 'This event loop is already running'

I am building a Discord bot using discord.py which gets live football scores from ESPN. What I have so far is:

Bot.py:

import discord, asyncio
from Scores import GetScores

client = discord.Client()

@client.event
async def on_message(message):
    if message.content.startswith("!scores"):
        Output = GetScores(message.content)

# rest of code

Scores.py:

from requests_html import HTMLSession

def GetScores(Message):
    Link = "http://www.espn.co.uk/football/scoreboard"

    Session = HTMLSession()
    Response = Session.get(Link)
    Response.html.render()

# rest of code  

So when the '!scores' command is sent in Discord, Bot.py will run the event loop and calls the 'GetScores' function from Scores.py.

The problem is, when Response.html.render() is run, it gives me the 'This event loop is already running' error. Full error from that point:

    Response.html.render()
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\requests_html.py", line 572, in render
    self.session.browser  # Automatycally create a event loop and browser
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\requests_html.py", line 680, in browser
    self._browser = self.loop.run_until_complete(pyppeteer.launch(headless=True, args=['--no-sandbox']))
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\asyncio\base_events.py", line 454, in run_until_complete
    self.run_forever()
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\asyncio\base_events.py", line 408, in run_forever
    raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running  

From this GitHub issue I have found that the code is not designed to be run in an existing event loop. However, I am wondering if there is a workaround in asyncio to allow this to run in this situation. I would much prefer I found a workaround rather than another solution/module, since I wrote the entire thing using this method before testing it within the Discord event loop, and finding out it doesn't work.

Any help will be greatly appreciated, thanks!

Upvotes: 9

Views: 3134

Answers (1)

Joe N.
Joe N.

Reputation: 63

Using the async version of render (called arender) should work for this situation.

Upvotes: 0

Related Questions