松弛事件:IndexError:列表索引超出范围

问题描述 投票:0回答:1

我试图从松弛中读取事件并返回匹配事件的响应。

问题是,当我匹配一个事件并将其恢复为松弛时,它会给我一个错误:

IndexError: list index out of range

代码片段:

def readSlack():
regVal = re.compile(r"(CHG\w+)")
while True:
    events = slack_client.rtm_read()
    for event in events:
        if (
                'channel' in event and
                'text' in event and
                event.get('type') == 'message'
        ):
            channel = event['channel']
            text = event['text']
            res = regVal.findall(text)  ### output of res, res = ['CHG1234567']
            change = res[0]
            incomingSlack(change, channel)
    time.sleep(1)

而我与松弛的关系终止了。当我尝试通过添加处理异常

res = regVal.findall(text)  ### output of res, res = ['CHG1234567']
            try:
                change = res[0]
            except IndexError:
                print("Index Error ")
            incomingSlack(change, channel)

这将在同一事件的无限循环中运行并向我的松弛频道发送垃圾邮件。

我在这做错了什么?

python regex list exception slack-api
1个回答
1
投票

怎么样:

res = regVal.findall(text)  ### output of res, res = ['CHG1234567']
if res:
    change = res[0]
    incomingSlack(change, channel)
© www.soinside.com 2019 - 2024. All rights reserved.