如何读取消息内容并检查其是否与正则表达式匹配

2024-05-26 11:12:35 发布

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

我希望它检查消息的内容,如果它与正则表达式匹配r"\A[0-9A-Z]{3}-[0-9A-Z]{3}-[0-9A-Z]{3}-[0-9A-Z]{3}\Z",则将与正则表达式匹配的部分存储在变量中。如果正则表达式不匹配,则完全忽略消息

这是我现在的代码,我想我需要稍微更改一下if函数。另外,由于某些原因,如何关闭函数puttingGetMessages()不起作用

def GetMessages(channelID):
    headers = {
        'authorization': token,
    }
    
    r = requests.get(f'https://discord.com/api/v9/channels/{channelID}/messages?limit=50', headers=headers)
    jsonn = json.loads(r.text)

    global message

    if jsonn[0] != message:
        message = jsonn[0]
        print(message['content'])


    else:
        time.sleep(0.01)

while True:

    GetMessages(int(id))

Tags: 函数代码token消息内容messageifdef
1条回答
网友
1楼 · 发布于 2024-05-26 11:12:35
import re

def GetMessages(channelID):
    headers = {
        'authorization': token,
    }
    
    r = requests.get(f'https://discord.com/api/v9/channels/{channelID}/messages?limit=50', headers=headers)
    jsonn = json.loads(r.text)

    global message, messages_lst
    # I am considering only the 1st item in the list, because if the list has more than 1 value, it must be sub-strings of the 1st item in the list,
    # And if the 1st item is just a string of trailing spaces, it gets cancelled by strip function, so it converts strings of spaces into '' (empty string)
    if re.findall(r'\A([0-Z]{3}-){4}\Z', jsonn[0])[0].strip() not in ['', None]: # shrinked the regex a little bit
        message = jsonn[0]
        messages_lst.append(message['content']) # To store valid messages in a list

    else:
        time.sleep(.1) # .1 is small enough and mostly used than 0.01

id = str('your-channel-id-goes-here')
message = ''
messages_lst = []
while True:
    GetMessages(id)

请告诉我,如果它不工作

相关问题 更多 >