在Python中,如何使用regex过滤Twitch API的WHISPER命令中的用户和消息?

2024-05-20 21:00:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我在主聊天中对PRIVMSG有很好的效果,但是Twitch的耳语命令让我有点发疯-它包含了大量的额外信息。在

作为一个例子,对于privsgmg,我可以这样做:

 CHAT_MSG=re.compile(r"^:\w+!\w+@\w+\.tmi\.twitch\.tv PRIVMSG #\w+ :")

但是,WHISPER返回以下信息:

^{pr2}$

当PRIVMSG返回此值时:

teonnyn!teonnyn@teonnyn.tmi.twitch.tv PRIVMSG #blastweb :Hello Bot

PRIVMSG-公共连接,使用它来解析来自public的聊天:

        username = re.search(r"\w+", channelResponse).group(0)
        message = CHAT_MSG.sub("", channelResponse)
        print(username + ": " + message)

在WHISPER中同样只返回完整的API信息的“badges+”块。 最好的方法是解析出所有的额外信息,然后只获取WHISPER的用户名和消息?在

我最终只想达到:teonnyn: Hello Bot


Tags: re信息messagehellobotchatusernamemsg
2条回答

以下正则表达式返回两个匹配项-用户名和消息:

user-type=\s+:(\w+)!.*:([\S\s]+)

REGEX DEMO


正在工作IDEONE DEMO

>>> import re
>>> s = "badges: @badges=;color=;display-name=;emotes=;message-id=34;thread-id=5575526_123681740;turbo=0;user-id=5575526;user-type= :teonnyn!teonnyn@teonnyn.tmi.twitch.tv WHISPER blastweb :Hello Bot"
>>> re.findall(r'user-type=\s+:(\w+)!.*:([\S\s]+)', s)
[('teonnyn', 'Hello Bot')]

您的字符串是有分隔符的,请尝试使用它作为您的优势:

>>> bits = s.split(':')
>>> bits[2],bits[3]
('teonnyn!teonnyn@teonnyn.tmi.twitch.tv WHISPER blastweb ', 'Hello Bot')

相关问题 更多 >