Accessing Pattern Match Groups with Telethon

41 views Asked by At

I'm working on a telegram bot with telethon to retrieve info from a customers database when queried with a /select command. I have a regex which works when tested to match strings following the select command, but I am unsure how to access that capture group so it can be supplied to the SQL query.

I'm attempting to use match.group() to access the results of a capture group but am getting nowhere, and I'm wondering if telethon's pattern feature works in exactly the same way as re:

def create_message_select_query(ans):
    text = ""
    for i in ans:
        id = i[0]
        lname = i[1]
        fname = i[2]
        customer_number = i[3]
        text += "<b>"+ str(id) +"</b> | " + "<b>"+ str(fname) +"</b> | " + "<b>"+ str(lname)+"</b> | " + "<b>"+ str(customer_number)+"</b>\n"
    message = "Retrieved customers:\n\n"+text
    return message

@client.on(events.NewMessage(pattern="(?i)(/search)(.+)"))
async def select(event):
    try:
        # Get the sender of the message
        sender = await event.get_sender()
        SENDER = sender.id
        # Execute the query and get all (*) the rows
        crsr.execute("SELECT * FROM customers WHERE lname =" + match.group(1) + ")
        res = crsr.fetchall() # fetch all the results

        # If there is at least 1 row selected, print a message with the list of all the customers
        
        if(res):
            testo_messaggio = create_message_select_query(res) 
            await client.send_message(SENDER, testo_messaggio, parse_mode='html')
        # Otherwise, print the following:
        else:
            text = "No matching students found ☹."
            await client.send_message(SENDER, text, parse_mode='html')

    except Exception as e: 
        print(e)
        await client.send_message(SENDER, "<b>Conversation Terminated✔️</b>", parse_mode='html')
        return
0

There are 0 answers