skip to Main Content

The issue is that the third function never seems to respond.
I haven’t been able to find a reason why this happens in the telegram documentation.
Please let me know if you have this issue or seen it and know the solution.
Even a post that references an issue like this would work.
Thank you so much for the assistance.

from email import message
import os
import re
import html
import json
import telebot
import requests
import http.client
from pytube import *
from dotenv import load_dotenv

load_dotenv()

# Creating hiding, and using API Keys
API_KEY = os.getenv("API_KEY")
RAPID_KEY = os.getenv("RAPID_API")
bot = telebot.TeleBot(API_KEY)

@bot.message_handler(commands="start")

# Creating a help message for guidance on how to use bot.
def help(message):

    # Trying to send help message, if unable to send, throw an error message for the user.
    try:
        bot.send_message(message.chat.id, "Use "Youtube" and the video name to search for a video.n")
    except:
        bot.send_message(message.chat.id, "There was an error fetching help, the bot may be offline.n")
 
# Checking data and seeing if the word "YouTube" was used in order to start the search
def data_validation(message):
    query = message.text.split() 
    if("youtube" not in query[0].lower()):  # Set flag false if regular text
        return False
    else:
        return True

@bot.message_handler(func=data_validation)

# Searching for youtube videos
# using RAPID API
def search(message):
    query = message.text.split()
    
    # Check if data is valid, and change variable to be lowercase for easy use.
    if(data_validation(message) == True and query[0].lower() == "youtube"):
        try:
            if(data_validation(message) == True and query[1].lower() != "-d"):
    
                # Removing the word "YouTube" and sending the results to the YouTube search engine.
                for item in query[:]:
                    if(item.lower() == "youtube"):
                        query.remove(item)
                        search_query = ' '.join(query)
                    else:
                        pass #If it's not term we're looking to convert, ignore it.

                # RAPID API for Youtube
                try:

                    url = "https://youtube-search-results.p.rapidapi.com/youtube-search/"
                    querystring = {"q":search_query}

                    headers = {
                        "X-RapidAPI-Key": RAPID_KEY,
                        "X-RapidAPI-Host": "youtube-search-results.p.rapidapi.com"
                    }

                    response = requests.request("GET", url, headers=headers, params=querystring) # Grabbing response information from URL
                    request = json.loads(response.text) # Parsing json string for python use
                    
                    # Testing to see if the RAPID API service responds and is online.
                    if(response.status_code == 503):

                        # If the service is not online, let the user know.
                        bot.send_message(message.chat.id, f"The RAPID API service appears to be offline try back later.n") 

                    if(response.status_code == 429):

                        # If the service has reached max quota for the day, let the user know.
                        bot.send_message(message.chat.id, f"Max quota reached, try back in 24 hours.n")

                    # Grabbing first link from json text and sending direct url and title.
                    first_link = str((request["items"][0]["url"]))

                    bot.send_message(message.chat.id, f"{first_link}n") # Sending first link that was queried.

                # If there are no results found for the requested video, sending an error message to alert the user.
                except:
                    bot.send_message(message.chat.id, "Unable to load video.n")
        except:
                pass #ignoring if not the phrase we're looking for.

def test(message):
    string = message.text.split()
    print(string)

    if(string[0] == "test" and data_validation(message) == True):
        print("This is a test and i should be printed")   
        bot.send_message(message.chat.id, "Test message")

# Stay alive function for bot pinging / communication
bot.infinity_polling(1440)

2

Answers


  1. Chosen as BEST ANSWER

    I found that using "if name == 'main':" and keeping all the functions in "main():" as a function handler everything ran smoothly. I'm still trying to figure out why this works.


  2. The first problem in your code is your first line

    from email import message

    You import the message from email and also pass a parameter to the data_validation function with the same name, then return False in the data_validation function. If you return false, the function never will be executed.

    first give an alias to first line you imported

    Try This

    
    from email import message as msg
    import os
    import re
    import html
    import json
    import telebot
    import requests
    import http.client
    from pytube import *
    from dotenv import load_dotenv
    
    load_dotenv()
    
    # Creating hiding, and using API Keys
    API_KEY = os.getenv("API_KEY")
    RAPID_KEY = os.getenv("RAPID_API")
    bot = telebot.TeleBot(API_KEY)
    
    
    # Creating a help message for guidance on how to use bot.
    @bot.message_handler(commands=["start"])
    def help(message):
    
        # Trying to send help message, if unable to send, throw an error message for the user.
        try:
            bot.send_message(message.chat.id, "Use "Youtube" and the video name to search for a video.n")
        except:
            bot.send_message(message.chat.id, "There was an error fetching help, the bot may be offline.n")
    
    # Checking data and seeing if the word "YouTube" was used in order to start the search
    def data_validation(message):
        query = message.text.split() 
        print(query)
        if("youtube" not in query[0].lower()):  # Set flag false if regular text
            return False # if you return false, the function never will be executed
        else:
            return True
    
    
    # Searching for youtube videos
    # using RAPID API
    @bot.message_handler(func=data_validation)
    def search(message):
        query = message.text.split()
        print(query) # if function executed you see the query result
        # Check if data is valid, and change variable to be lowercase for easy use.
        if(data_validation(message) == True and query[0].lower() == "youtube"):
            try:
                if(data_validation(message) == True and query[1].lower() != "-d"):
    
                    # Removing the word "YouTube" and sending the results to the YouTube search engine.
                    for item in query[:]:
                        if(item.lower() == "youtube"):
                            query.remove(item)
                            search_query = ' '.join(query)
                        else:
                            pass #If it's not term we're looking to convert, ignore it.
    
                    # RAPID API for Youtube
                    try:
    
                        url = "https://youtube-search-results.p.rapidapi.com/youtube-search/"
                        querystring = {"q":search_query}
    
                        headers = {
                            "X-RapidAPI-Key": RAPID_KEY,
                            "X-RapidAPI-Host": "youtube-search-results.p.rapidapi.com"
                        }
    
                        response = requests.request("GET", url, headers=headers, params=querystring) # Grabbing response information from URL
                        request = json.loads(response.text) # Parsing json string for python use
    
                        # Testing to see if the RAPID API service responds and is online.
                        if(response.status_code == 503):
    
                            # If the service is not online, let the user know.
                            bot.send_message(message.chat.id, f"The RAPID API service appears to be offline try back later.n") 
    
                        if(response.status_code == 429):
    
                            # If the service has reached max quota for the day, let the user know.
                            bot.send_message(message.chat.id, f"Max quota reached, try back in 24 hours.n")
    
                        # Grabbing first link from json text and sending direct url and title.
                        first_link = str((request["items"][0]["url"]))
    
                        bot.send_message(message.chat.id, f"{first_link}n") # Sending first link that was queried.
    
                    # If there are no results found for the requested video, sending an error message to alert the user.
                    except:
                        bot.send_message(message.chat.id, "Unable to load video.n")
            except:
                    pass #ignoring if not the phrase we're looking for.
    
    def test(message):
        string = message.text.split()
        print(string)
    
        if(string[0] == "test" and data_validation(message) == True):
            print("This is a test and i should be printed")
            bot.send_message(message.chat.id, "Test message")
    
    # Stay alive function for bot pinging / communication
    bot.infinity_polling(1440)
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search