1

我正在尝试将 Twitch API 包(twitchio)与网络服务器(sanic)结合起来,目的是为本地运行的游戏提供聊天命令到 python 脚本。我不必使用 Sanic 或 twitchio,但这些是我为我的项目找到的最佳结果。

我明白为什么到目前为止我所拥有的东西不起作用,但我完全不知道如何解决这个问题。到目前为止,我发现的大多数答案都涉及您编写的使用 asyncio 的脚本,而不是使用事件循环的包。

我只能让网络服务器或聊天机器人运行。我不能让它们同时运行。

这是我第一次尝试使用 Python,因此非常感谢任何指导。

#!/usr/bin/python

import os

from twitchio.ext import commands
from sanic import Sanic
from sanic.response import json

app = Sanic(name='localserver')

bot = commands.Bot(
    token=os.environ['TMI_TOKEN'],
    client_id=os.environ['CLIENT_ID'],
    nick=os.environ['BOT_NICK'],
    prefix=os.environ['BOT_PREFIX'],
    initial_channels=[os.environ['CHANNEL']]
)

@app.route("/")
async def query(request):
    return json(comcache)

@bot.event
async def event_ready():
    'Called once when the bot goes online.'
    print(f"{os.environ['BOT_NICK']} is online!")
    ws = bot._ws  # this is only needed to send messages within event_ready
    await ws.send_privmsg(os.environ['CHANNEL'], f"/me has landed!")

@bot.event
async def event_message(ctx):
    'Runs every time a message is sent in chat.'
    # make sure the bot ignores itself and the streamer
    if ctx.author.name.lower() == os.environ['BOT_NICK'].lower():
        return
    await bot.handle_commands(ctx)
    # await ctx.channel.send(ctx.content)
    if 'hello' in ctx.content.lower():
        await ctx.channel.send(f"Hi, @{ctx.author.name}!")

@bot.command(name='test')
async def test(ctx):
    await ctx.send('test passed!')
 
if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8080)
    bot.run()
4

0 回答 0