Home > Mobile >  Python execute functions simultaneously
Python execute functions simultaneously

Time:08-01

I know that this question has been asked multiple times, however I couldn't solve the issue by going over the answers. I need help. I wrote this telegram bot in Python in order to practice, and everything works ok, however yesterday I tried to implement an "uptime" timer, I wrote the function and on its own if works, however when I call it in the main file it will override everything else and the bot will not work. Furthermore, I tried to implement threading and multithreading and pretty much everything I could find online, however it still did not work. I think that I'm doing something wrong. I'm providing you with the code that I have, but I have removed the threading section from it.

Timer function

import time
import os
import Responses


def cls():
    os.system('cls' if os.name == 'nt' else 'clear')


def uptime():
    days = 0
    hours = 0
    minutes = 0
    seconds = 0

    while True:
        time.sleep(1)
        seconds  = 1

        if seconds > 59:
            seconds = 0
            minutes  = 1

        if minutes > 59:
            minutes = 0
            hours  = 1

        if hours > 23:
            hours = 0
            days  = 1

        cls()
        print(f"{Responses.bot_name} has started...")
        print(f"Uptime {days}d:{hours}h:{minutes}m:{seconds}s")

Main Bot file

import os
import telebot
import Gif
import Responses as R
import Weather
from dotenv import load_dotenv
import timer


load_dotenv()

bot_name = R.bot_name

TELEGRAM_KEY = os.getenv('TELEGRAM_KEY')
bot = telebot.TeleBot(TELEGRAM_KEY, parse_mode=None)

print(f"{bot_name} Started...")


@bot.message_handler(commands=['start'])
def greet(message):
    photo = open(r"Bot Demo.png", 'rb')
    bot.send_message(message.chat.id, f"Hi {message.chat.first_name}, my name is <b>{bot_name}</b>!", parse_mode='html')
    bot.send_photo(message.chat.id, photo, caption="This is me! \nI can send Pictures!")
    bot.send_message(message.chat.id, "Use <i>/help</i> to find out what else I can do!", parse_mode='html')


@bot.message_handler(commands=['help'])
def help(message):
    bot.send_message(message.chat.id, "Hi I'm a <b>DEMO</b> Bot!"
                                      "\nYou can greet me and I'll <b>respond</b>."
                                      "\nYou can ask me about the <b>time</b> and the <b>date</b>."
                                      "\nYou can ask me to tell you a <b>joke</b>."
                                      "\nYou can ask for a <b>gif</b> and you will receive a random gif from the API."
                                      "\nYou can use <i>/weather</i> to get the <b>Weather</b>."
                                      "\nYou can use <i>/gif</i> to get a <b>GIF</b> from a specific category."
                                      "\nYou can also use <i>/info</i> to get more <b>information</b> about my creator.", parse_mode='html')


@bot.message_handler(commands=['info'])
def info(message):
    bot.send_message(message.chat.id, "Hi, my name is Kaloian Kozlev and I am the creator of this bot."
                                      "\nIf you need a Bot for your social media, "
                                      "you can contact me on [email protected]")


@bot.message_handler(commands=['gif'])
def gif(message):
    sent = bot.send_message(message.chat.id, "If you want a specific GIF "
                                             "\nenter <search_term>"
                                             "\nexample: cat")
    bot.register_next_step_handler(sent, condition)


def condition(message):
    q = str(message.text).lower()
    bot.send_video(message.chat.id, Gif.search_gif(q), caption=f"Here is a picture of a random {q}")


@bot.message_handler(commands=['weather'])
def weather(message):
    sent = bot.send_message(message.chat.id, "Enter City name:")
    bot.register_next_step_handler(sent, city)


def city(message):
    q = str(message.text).lower()
    bot.send_message(message.chat.id, Weather.get_weather(q))


@bot.message_handler()
def handle_message(message):
    text = str(message.text).lower()
    response = R.sample_responses(text)
    bot.send_message(message.chat.id, response)
    if "gif" in text:
        bot.send_video(message.chat.id, Gif.get_gif(), caption="I'm using an API to get this GIF")

timer.uptime()
bot.polling()

CodePudding user response:

Maybe try out threading or multiprocessing if you haven't already.

Threading Example - from this site

import threading

def function_1():
   print("Inside The Function 1")

def function_2():
   print("Inside The Function 2")

# Create a new thread
Thread1 = threading.Thread(target=function_1)

# Create another new thread
Thread2 = threading.Thread(target=function_2)

# Start the thread
Thread1.start()

# Start the thread
Thread2.start()

# Wait for the threads to finish
Thread1.join()
Thread2.join()

print(“Done!”)

CodePudding user response:

This is a wild guess, because you didn't show your threading code. A common mistake when using the threading module, is executing your function in the call, rather than just passing the name. Perhaps you did this:

threading.Thread(target=myfunction())

Instead of this:

threading.Thread(target=myfunction)

It's a common error.

  • Related