<p>我找到了一个解决办法,虽然很难看,但很管用。在</p>
<pre><code>import re
packet_expression = re.compile(r'(@.+)? :([a-zA-Z0-9][\w]{2,23})!\2@\2.tmi.twitch.tv PRIVMSG #([a-zA-Z0-9][\w]{2,23}) :(.+)')
def parse_twitch(packet):
match = re.match(packet_expression, packet)
items = match.group(1)[1:].split(';')
tags = dict(item.split('=') for item in items)
emote_expression = re.compile(r'(\d+):((\d+-\d+,)*\d+-\d+)')
tags["emotes"] = [
(int(emotes[0]), (int(start), int(end)))
for emotes in re.findall(emote_expression, tags.get("emotes", ''))
for location in emotes[1].split(',')
for start, end in [location.split('-')]
]
message = match.group(4)
characters = list(message)
offset = 0
for emote in tags["emotes"]:
characters[emote[1][0]-offset : emote[1][1]-offset+1] = [{
"type": "emote",
"text": ''.join(characters[emote[1][0]-offset : emote[1][1]-offset+1]),
"id": emote[0]
}]
offset += emote[1][1] - emote[1][0]
index = 0
while any(isinstance(item, str) for item in characters):
if isinstance(characters[index], str) and isinstance(characters[index+1], str):
characters[index:index+2] = [characters[index] + characters[index+1]]
else:
if isinstance(characters[index], str):
characters[index] = {"type": "text", "text": characters[index]}
index += 1
return characters
</code></pre>