D
D
Danya  2020-08-24 22:45:40
Python
Danya  , 2020-08-24 22:45:40

TelebramBOT how to run two functions at the same time?

How to run two functions at the same time?

@bot.message_handler(content_types=['text'])
def timer(message):	   ### Эту и следующую нужно вместе запустить 
  msg = bot.send_message(chat_id=message.chat.id, text='START')
  time.sleep(1)
  msg_id = msg.message_id
  time_s = 5
  for t in range(time_s, 0, -1):
    bot.edit_message_text(chat_id=message.chat.id,  message_id=msg_id, text=f'Wait...{t}  секунд')
    time.sleep(1)
  bot.edit_message_text(chat_id=message.chat.id, message_id=msg_id, text='END')

def voice(message):
  CHUNK = 1024
  FORMAT = pyaudio.paInt16
  CHANNELS = 2
  RATE = 44100
  RECORD_SECONDS = 5
  WAVE_OUTPUT_FILENAME = "output.wav"

  p = pyaudio.PyAudio()

  stream = p.open(format=FORMAT,
                  channels=CHANNELS,
                  rate=RATE,
                  input=True,
                  frames_per_buffer=CHUNK)

  print("* recording")


  frames = []
  for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):

    data = stream.read(CHUNK)
    frames.append(data)


  
  send_notification(message)
  print("* done recording")

  stream.stop_stream()
  stream.close()
  p.terminate()

  wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
  wf.setnchannels(CHANNELS)
  wf.setsampwidth(p.get_sample_size(FORMAT))
  wf.setframerate(RATE)
  wf.writeframes(b''.join(frames))
  wf.close()
  bot.send_audio(message.chat.id, open('output.wav', 'rb'))
  time.sleep(1)
  os.remove('output.wav')


I tried:
from multiprocessing import Process
def func1(message):
     time.sleep(5)
     bot.send_message(message.chat.id, '1 - Функция.')

def func2(message):
      time.sleep(5)
      bot.send_message(message.chat.id, '2 - Функция.')

if __name__=='__main__':
     p1 = Process(target = func1)
     p1.start()
     p2 = Process(target = func2)
     p2.start()


But in if__name__ you need to specify the message arguments, when I specify the error 'message is not defiend'.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2020-08-25
@MrBrainop

Here is an example of running a counter and timer parallel thread based on the code above:

# -*- coding: utf-8 -*-
import telebot
from time import sleep
from threading import Thread

bot = telebot.TeleBot(token_test)


@bot.message_handler(commands=['start'])
def thread_main(message):
    Thread(target=timer, args=(message,)).start()
    Thread(target=counter, args=(message,)).start()


def timer(message):
    msg = bot.send_message(chat_id=message.chat.id, text='Timer start')
    sleep(1)
    msg_id = msg.message_id
    time_s = 15
    for t in range(time_s, 0, -1):
        bot.edit_message_text(chat_id=message.chat.id,  message_id=msg_id, text=f'Timer - {t}')
        sleep(1)
    bot.edit_message_text(chat_id=message.chat.id, message_id=msg_id, text='Timer End')


def counter(message):
    msg = bot.send_message(chat_id=message.chat.id, text='Count start')
    sleep(1)
    msg_id = msg.message_id
    count = 15
    for c in range(count):
        bot.edit_message_text(chat_id=message.chat.id,  message_id=msg_id, text=f'Count - {c}')
        sleep(1)
    bot.edit_message_text(chat_id=message.chat.id, message_id=msg_id, text='Count End')


if __name__ == "__main__":
    try:
        bot.polling(none_stop=True)
    except Exception as e:
        print(e)

Links to understanding given above.

D
Darvel, 2020-08-25
@Darnil

There are 2 ways to do multithreading:
Create threads https://geekbrains.ru/posts/python_threading_part1 Examples of how to unlock the GIL are described here
Or the multiprocessing function https://docs.python.org/3.5/library/multiprocessin...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question