简体   繁体   中英

RuntimeError: This event loop is already running aiogram

I want to make telegram bot to download TikTok videos. I need to download TikTok video using its URL. And after I send a message with link, it raises this error. How can I solve it? Is there any other way to download TikTok video, My code is below.

ERROR: 
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 415, in _process_polling_updates
    for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 235, in process_updates
    return await asyncio.gather(*tasks)
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\handler.py", line 116, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 256, in process_update
    return await self.message_handlers.notify(update.message)
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\aiogram\dispatcher\handler.py", line 116, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "C:\Users\User\Desktop\scripts\saveassbot\bot.py", line 28, in text
    with TikTokApi() as api:
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\TikTokApi\tiktok.py", line 159, in __init__
    self._initialize(
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\TikTokApi\tiktok.py", line 205, in _initialize
    self._browser = asyncio.get_event_loop().run_until_complete(
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 618, in run_until_complete
    self._check_running()
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 578, in _check_running
    raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running

Code:
    # -*- coding: utf-8 -*-
    from aiogram import Bot, Dispatcher, executor, types
    import logging
    import main
    import config
    from TikTokApi import TikTokApi
    
    logging.basicConfig(level=logging.INFO)
    bot = Bot(token=config.token)
    dp = Dispatcher(bot)
    
    
    @dp.message_handler(commands=['start'])
    async def send_welcome(message: types.Message):
        # if(not BotDB.user_exists(message.from_user.id)):
        #    BotDB.add_user(message.from_user.id, message.from_user.username)
        await bot.send_message(message.from_user.id,
                               f'hello',
                               parse_mode="Markdown")
    
    
    @dp.message_handler(content_types=['text'])
    async def text(message: types.Message):
        if message.text.startswith('https://vt.tiktok.com'):
            video_url = message.text
            with TikTokApi() as api:
                video = api.video(url=f"{video_url}")
    
                # Bytes of the TikTok video
                video_data = video.bytes()
    
                with open(f"{message.from_user.id}", "wb") as out_file:
                    out_file.write(video_data)
    
    
    if __name__ == "__main__":
        executor.start_polling(dp, skip_updates=True)

By the looks of it , the TikTokApi library is broken in the sense it can't be constructed if there's already an asyncio loop running (and there is, when you use aiogram ).

You could see if "misusing" the API by initializing it at the start of your program, before you enter the aiogram loop, works:

# ...
dp = Dispatcher(bot)
tiktok_api = TikTokApi()
# ...
async def text(message: types.Message):
   # ...
   video = tiktok_api.video(...)

but I wouldn't count on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM