Search code examples
pythonreturntelethon

Function does not work when return is specified


I am trying to make a function that fetches the list of contacts of a user from telegram using the telethon library, after fetching the contacts it will extract the user id and the first name of each contact then it will compare the first name of the contact and the name entered by the user and if it is similar it will send a message that the user input. The function works as it sends the message successfully to the expected contact but when I use a return statement it does not work

async def sendUserMessage(self, response, message):
    client = TelegramClient('session', api_id, api_hash)
    await client.connect()
    result = await client(functions.contacts.GetContactsRequest(
        hash=0
    ))
    for user in result.users:
        try:
            s = SequenceMatcher(None, response, user.first_name)
            print(s.ratio())
            print(response)
            print(user.first_name)
            if s.ratio() > 0.75:
                print(response, user.id)
                receiver = InputPeerUser(user.id, 0)
                await client.send_message(receiver, message, parse_mode='html')
                return print("Sent a message successfully")
            else:
                return print("Could not send message")

        except Exception:
            pass
    await client.disconnect()

a = input("Who do you want to send the message to? ")
b = input("What do you wanna send? ")

async def main():
    await Methods().sendUserMessage(a, b)

asyncio.run(main())

Here a is the person I want the message to be sent to and b is the message. Any help would be appreciated

Update

I figured out the problem, Return statements break the loop before the conditions are met.

Is there any way to return a statement only once when the condition is met?

enter image description here

I used boolean flag but it still does not work, I am not sure if I used it the right way

async def sendUserMessage(self, response, message):
    isSent = False
    client = TelegramClient('session', api_id, api_hash)
    await client.connect()
    result = await client(functions.contacts.GetContactsRequest(
        hash=0
    ))
    for user in result.users:
        try:
            s = SequenceMatcher(None, response, user.first_name)
            if s.ratio() > 0.75:
                receiver = InputPeerUser(user.id, 0)
                await client.send_message(receiver, message, parse_mode='html')
                isSent = True
            else:
                isSent = False
        except Exception:
            pass
    await client.disconnect()
    if isSent:
        print("Message sent successfully")
    else:
        print("Message could not be sent") 

Solution

  • I was able to fix the problem by using a boolean flag instead of using print in the for loop

    async def sendUserMessage(self, response):
            isSent = False
            client = TelegramClient('session', api_id, api_hash)
            await client.connect()
            result = await client(functions.contacts.GetContactsRequest(
                hash=0
            ))
            for user in result.users:
                try:
                    s = SequenceMatcher(None, response, user.first_name)
                    if s.ratio() > 0.75 or distance.levenshtein(response, user.first_name) < 3:
                        speak("What do you wanna send?")
                        message = takeCommand()
                        isSent = True
                        receiver = InputPeerUser(user.id, 0)
                        await client.send_message(receiver, message, parse_mode='html')
                    else:
                        pass
                except Exception:
                    pass
            await client.disconnect()
            if isSent:
                speak("Message sent successfully")
            else:
                speak("Could not find that user in your contacts")