asyncio get_event_loop method is being deprecated; use new_event_loop / get_running_loop and asyncio.run instead

Major version change because it may not be backward-compatible
This commit is contained in:
2022-10-12 13:24:40 +02:00
parent e254dbf42a
commit 76ea65a660
5 changed files with 21 additions and 18 deletions

View File

@@ -11,7 +11,7 @@ __author__ = "Davide Testa"
__email__ = "davide@davte.it" __email__ = "davide@davte.it"
__credits__ = ["Marco Origlia", "Nick Lee @Nickoala"] __credits__ = ["Marco Origlia", "Nick Lee @Nickoala"]
__license__ = "GNU General Public License v3.0" __license__ = "GNU General Public License v3.0"
__version__ = "2.7.6" __version__ = "2.8.0"
__maintainer__ = "Davide Testa" __maintainer__ = "Davide Testa"
__contact__ = "t.me/davte" __contact__ = "t.me/davte"

View File

@@ -82,7 +82,6 @@ class TelegramBot:
All mirrored methods are camelCase. All mirrored methods are camelCase.
""" """
loop = asyncio.get_event_loop()
app = aiohttp.web.Application() app = aiohttp.web.Application()
sessions_timeouts = { sessions_timeouts = {
'getUpdates': dict( 'getUpdates': dict(
@@ -226,7 +225,6 @@ class TelegramBot:
if api_method in cls.sessions_timeouts: if api_method in cls.sessions_timeouts:
if api_method not in self.sessions: if api_method not in self.sessions:
self.sessions[api_method] = aiohttp.ClientSession( self.sessions[api_method] = aiohttp.ClientSession(
loop=cls.loop,
timeout=aiohttp.ClientTimeout( timeout=aiohttp.ClientTimeout(
total=cls.sessions_timeouts[api_method]['timeout'] total=cls.sessions_timeouts[api_method]['timeout']
) )
@@ -235,7 +233,6 @@ class TelegramBot:
session_must_be_closed = cls.sessions_timeouts[api_method]['close'] session_must_be_closed = cls.sessions_timeouts[api_method]['close']
else: else:
session = aiohttp.ClientSession( session = aiohttp.ClientSession(
loop=cls.loop,
timeout=aiohttp.ClientTimeout(total=None) timeout=aiohttp.ClientTimeout(total=None)
) )
session_must_be_closed = True session_must_be_closed = True

View File

@@ -102,18 +102,14 @@ class TelegramApiMethod(object):
return parameters return parameters
async def print_api_methods(loop=None, async def print_api_methods(filename=None,
filename=None,
print_all=False, print_all=False,
output_file=None, output_file=None,
input_file=None): input_file=None):
"""Get information from Telegram bot API web page.""" """Get information from Telegram bot API web page."""
if loop is None:
loop = asyncio.get_event_loop()
implemented_methods = dir(TelegramBot) implemented_methods = dir(TelegramBot)
if input_file is None or not os.path.isfile(input_file): if input_file is None or not os.path.isfile(input_file):
async with aiohttp.ClientSession( async with aiohttp.ClientSession(
loop=loop,
timeout=aiohttp.ClientTimeout( timeout=aiohttp.ClientTimeout(
total=100 total=100
) )
@@ -267,10 +263,8 @@ def main():
print_all = cli_arguments['all'] print_all = cli_arguments['all']
output_file = cli_arguments['out'] output_file = cli_arguments['out']
input_file = cli_arguments['in'] input_file = cli_arguments['in']
loop = asyncio.get_event_loop() asyncio.run(
loop.run_until_complete( print_api_methods(filename=filename,
print_api_methods(loop=loop,
filename=filename,
print_all=print_all, print_all=print_all,
output_file=output_file, output_file=output_file,
input_file=input_file) input_file=input_file)

View File

@@ -75,6 +75,7 @@ class Bot(TelegramBot, ObjectWithDatabase, MultiLanguageObject):
bots = [] bots = []
_path = '.' _path = '.'
runner = None runner = None
server = None
# TODO: find a way to choose port automatically by default # TODO: find a way to choose port automatically by default
# Setting port to 0 does not work unfortunately # Setting port to 0 does not work unfortunately
local_host = 'localhost' local_host = 'localhost'
@@ -3105,6 +3106,10 @@ class Bot(TelegramBot, ObjectWithDatabase, MultiLanguageObject):
if not session.closed: if not session.closed:
await session.close() await session.close()
async def send_one_message(self, *args, **kwargs):
await self.send_message(*args, **kwargs)
await self.close_sessions()
async def set_webhook(self, url=None, certificate=None, async def set_webhook(self, url=None, certificate=None,
max_connections=None, allowed_updates=None): max_connections=None, allowed_updates=None):
"""Set a webhook if token is valid.""" """Set a webhook if token is valid."""
@@ -3429,7 +3434,8 @@ class Bot(TelegramBot, ObjectWithDatabase, MultiLanguageObject):
""" """
logging.info(message) logging.info(message)
cls.final_state = final_state cls.final_state = final_state
cls.loop.stop() loop = asyncio.get_running_loop()
loop.stop()
return return
@classmethod @classmethod
@@ -3446,7 +3452,9 @@ class Bot(TelegramBot, ObjectWithDatabase, MultiLanguageObject):
if port is not None: if port is not None:
cls.port = port cls.port = port
try: try:
cls.loop.run_until_complete( loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
asyncio.run(
asyncio.gather( asyncio.gather(
*[ *[
preliminary_task preliminary_task
@@ -3461,13 +3469,15 @@ class Bot(TelegramBot, ObjectWithDatabase, MultiLanguageObject):
bot.setup() bot.setup()
asyncio.ensure_future(cls.start_app()) asyncio.ensure_future(cls.start_app())
try: try:
cls.loop.run_forever() loop = asyncio.get_running_loop()
loop.run_forever()
except KeyboardInterrupt: except KeyboardInterrupt:
logging.info("Stopped by KeyboardInterrupt") logging.info("Stopped by KeyboardInterrupt")
except Exception as e: except Exception as e:
logging.error(f"{e}", exc_info=True) logging.error(f"{e}", exc_info=True)
finally: finally:
cls.loop.run_until_complete(cls.stop_app()) loop = asyncio.get_running_loop()
loop.run_until_complete(cls.stop_app())
return cls.final_state return cls.final_state
def set_role_class(self, role): def set_role_class(self, role):

View File

@@ -503,7 +503,9 @@ async def async_wrapper(coroutine, *args1, **kwargs1):
) )
await my_coroutine(a=1, b=5) await my_coroutine(a=1, b=5)
asyncio.get_event_loop().run_until_complete(main()) loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
asyncio.run(main())
``` ```
""" """
async def wrapped_coroutine(*args2, bot=None, update=None, user_record=None, **kwargs2): async def wrapped_coroutine(*args2, bot=None, update=None, user_record=None, **kwargs2):