简体   繁体   中英

Running asyncio bot concurrently to Tkinter GUI

I'm trying to integrate a Python Twitch bot ( https://github.com/TwitchIO/TwitchIO ) into a Tkinter GUI. Here is the bot I subclassed from twitch.io.ext.commands.bot

import os

from twitchio.ext import commands
from dotenv import load_dotenv
from os.path import join, dirname

class Bot(commands.Bot):

    def __init__(self):

        dir_path = os.path.dirname(os.path.realpath(__file__))
        dotenv_path = join(dir_path, '.env')
        load_dotenv(dotenv_path)

        TMI_TOKEN = os.environ.get('TMI_TOKEN')
        CLIENT_ID = os.environ.get('CLIENT_ID')
        BOT_NICK = os.environ.get('BOT_NICK')
        BOT_PREFIX = os.environ.get('BOT_PREFIX')
        CHANNEL = os.environ.get('CHANNEL')

        super().__init__(irc_token=TMI_TOKEN,
                         client_id=CLIENT_ID,
                         nick=BOT_NICK,
                         prefix=BOT_PREFIX,
                         initial_channels=[CHANNEL])


    async def start(self):
        await self._ws._connect()

        try:
            await self._ws._listen()
        except KeyboardInterrupt:
            pass
        finally:
            self._ws.teardown()


    async def stop(self):
        self._ws.teardown()


    async def event_ready(self):
        print("ready")


    async def event_message(self, message):
        print(message.content)
        await self.handle_commands(message)


    @commands.command(name='test')
    async def my_command(self, ctx):
        await ctx.send(f'Hello {ctx.author.name}!')

Here is the Tkinter GUI

try:
    import Tkinter as Tk
except ModuleNotFoundError:
    import tkinter as Tk

import asyncio

from bot import Bot

bot = Bot()
loop = asyncio.get_event_loop()

def on_start():
    print("start")
    loop.run_until_complete(bot.start())

def on_stop():
    print("stop")
    loop.run_until_complete(bot.stop())

if __name__ == '__main__':
    root = Tk.Tk()
    frame = Tk.Frame(root)

    start_button = Tk.Button(frame.master, text="start", command = on_start)
    start_button.pack()

    stop_button = Tk.Button(frame.master, text="stop", command = on_stop)
    stop_button.pack()

    root.mainloop()

So when the start button is pressed the bot starts itself and connects to Twitch. However, the GUI is stuck after loop.run_until_complete(bot.start()) in the on_start() it never returns. How am I able to run the bot concurrently to the GUI?

You can try running the event loop in a different thread and submit tasks to it in a thread-safe manner. For example:

loop = asyncio.get_event_loop()
threading.Thread(daemon=True, target=loop.run_forever).start()

# ... in the GUI:

def on_start():
    print("start")
    asyncio.run_coroutine_threadsafe(loop, bot.start())

def on_stop():
    print("stop")
    asyncio.run_coroutine_threadsafe(loop, bot.stop())

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