【问题标题】:Twitch chat logger crashes with websocket error in python3.7Twitch 聊天记录器在 python3.7 中因 websocket 错误而崩溃
【发布时间】:2019-12-20 17:20:35
【问题描述】:

所以,我今天尝试在 Python 3.7 中制作 Twitch Chat(IRC) 记录器。运行 python -m pip install pipenv pipenv --python 3.7 pipenv install setproctitle pipenv install twitchio pipenv run pip install --upgrade git+https://github.com/Gallopsled/pwntools.git@dev3 后,当我运行 logger.py 时出现此错误:

2019-12-20
Task exception was never retrieved
future: <Task finished coro=<WebsocketConnection.auth_seq() done, defined at /home/zoe/.local/share/virtualenvs/Twitch-Dev-B4hlqNxh/lib/python3.7/site-packages/twitchio/websocket.py:200> exception=KeyError('zoes17')>
Traceback (most recent call last):
  File "/home/zoe/.local/share/virtualenvs/Twitch-Dev-B4hlqNxh/lib/python3.7/site-packages/twitchio/websocket.py", line 280, in _join_channel
    await asyncio.wait_for(fut, timeout=10)
  File "/usr/lib/python3.7/asyncio/tasks.py", line 449, in wait_for
    raise futures.TimeoutError()
concurrent.futures._base.TimeoutError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/zoe/.local/share/virtualenvs/Twitch-Dev-B4hlqNxh/lib/python3.7/site-packages/twitchio/websocket.py", line 228, in auth_seq
    await self.join_channels(*channels)
  File "/home/zoe/.local/share/virtualenvs/Twitch-Dev-B4hlqNxh/lib/python3.7/site-packages/twitchio/websocket.py", line 271, in join_channels
    await asyncio.gather(*[self._join_channel(x) for x in channels])
  File "/home/zoe/.local/share/virtualenvs/Twitch-Dev-B4hlqNxh/lib/python3.7/site-packages/twitchio/websocket.py", line 282, in _join_channel
    self._pending_joins.pop(channel)
KeyError: 'zoes17'
^C/home/zoe/.local/share/virtualenvs/Twitch-Dev-B4hlqNxh/lib/python3.7/site-packages/twitchio/websocket.py:618: RuntimeWarning: coroutine 'WebSocketCommonProtocol.close' was never awaited
  self._websocket.close()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

这是来自 logger.py 的相关代码,它似乎已连接,但在 10 秒超时后崩溃。我在使用 .env 文件的 TMI_TOKEN 环境变量中使用 oauth:oathkeyFromTwitch 作为我的密码。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""Logger main class."""
import os   # for importing env vars for the bot to use
import sys  # for argument processing
from datetime import *
from pwnlib.term import text
from setproctitle import setproctitle
from twitchio.ext import commands

channel = ""
if len(sys.argv) > 1:
    channel = sys.argv[1]

bot = commands.Bot(
    # set up the bot
    irc_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'], channel]
)

@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)

    if 'hello' in ctx.content.lower():
        await ctx.channel.send(f"Hi, @{ctx.author.name}!")

if __name__ == "__main__":
    from commands import Handler as command_handler
    bot.run()

我的代码痴迷的大脑在这里缺少什么?

【问题讨论】:

    标签: python websocket virtualenv twitch


    【解决方案1】:

    initial_channels=[os.environ['CHANNEL'], channel] 需要成为:

    initial_channels=[os.environ['CHANNEL']]initial_channels=[channel]

    commands.Bot 的相关代码就这样实例化了:

    class Bot(Client):
        def __init__(self, irc_token: str, api_token: str=None, *, client_id: str=None, prefix: Union[list, tuple, str],
                     nick: str, loop: asyncio.BaseEventLoop=None, initial_channels: Union[list, tuple]=None,
                     webhook_server: bool=False, local_host: str=None, external_host: str=None, callback: str=None,
                     port: int=None, **attrs):
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-28
      • 2017-08-21
      • 2014-01-20
      相关资源
      最近更新 更多