Home > Blockchain >  How to pass a returned value from method to another one Python
How to pass a returned value from method to another one Python

Time:06-04

I have two methods. The first one is to extract a username from a TikTok URL, and the second one is to determine whether the TikTok live is currently live or ended. The first method will take the URL as '*https://www.tiktok.com/@farahmodel/live*' for example. And it will return farahmodel as username.

I want to pass the return value to the second method. Any thoughts please?

Using the following code:

from TikTokLive import TikTokLiveClient
from TikTokLive.types.events import *
import sys


class TikTok:
    """
    This class is to determine whether a TikTok live video is (live now) or (ended) one.
    """

    @staticmethod
    def url_analysis(url):
        """
        This method will extract the username from the source URL.
        """
        username = ''
        if '/live' in url:
            for part in url.split('/'):
                if '@' in part:
                    username = part
        username = username.replace('@', '')
        return username

    @staticmethod
    def is_live(username):
        """
        This method will check the live room ID if it is valid or not.
        Example of a valid room ID '7099710600141474562'.
        Many events can be used, for example: counting views, comments, likes, etc.
        """
        client: TikTokLiveClient = TikTokLiveClient(unique_id=username)

        @client.on("connect")
        async def on_connect(_: ConnectEvent):
            if client.room_id != 0:
                print('LIVE is running now.')
                sys.exit()

        if __name__ == '__main__':
            try:
                client.run()
                client.stop()
            except Exception as error:
                print(f'Cannot connect due to {type(error).__name__} or Live is ended by the host.')


# Pass the URL.
TikTok.url_analysis(url='https://www.tiktok.com/@farahmodel/live')
TikTok.is_live(username='')  # I want to pass the returned 'username' of url_analysis method.

CodePudding user response:

Assign the return value to a local variable (e.g. username), then pass it as the argument into the is_live() method call:

username = TikTok.url_analysis(url='https://www.tiktok.com/@farahmodel/live')
TikTok.is_live(username=username)

Looks like you're learning coding basics, I'd suggest reviewing lessons/tutorials about assigning variables and calling functions/methods.

  • Related