[英]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.我正在尝试将 Python Twitch 机器人( https://github.com/TwitchIO/TwitchIO )集成到 Tkinter GUI 中。 Here is the bot I subclassed from
twitch.io.ext.commands.bot
这是我从
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这是 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.因此,当按下开始按钮时,机器人会自行启动并连接到 Twitch。 However, the GUI is stuck after
loop.run_until_complete(bot.start())
in the on_start()
it never returns.但是,GUI 在 on_start() 中的
on_start()
loop.run_until_complete(bot.start())
之后卡住了,它永远不会返回。 How am I able to run the bot concurrently to the GUI?我如何能够将机器人同时运行到 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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.