Here I have a code, but I want all of this code to run at same time without each waiting for other to finish before the other run.
from telegram import *
from telegram.ext import *
import telegram
IDs = [1111,2222,3333,4444]
def start(update,context) -> None:
while True:
for user in IDs:
context.bot.send_message(user,f"hello {user}")
Is there a way to send messages to all of these users at once without waiting for it to send to 1111, then 2222,3333 and 4444…?
2
Answers
With a huge caveat, yes. You can use asyncio if the calls to
send_message
can not block the process. This offers concurrency and not parallelism. It would look something like this:But that may not work in your case at all, if the call to
send_message
waits for a response before continuing.Here is a good answer to multiprocessing vs multithreading vs asyncio in Python 3
PTB comes with a built-in tool to run I/O bound tasks in a thread pool –
Dispatcher.run_async
. Note that this has nothing to do withasyncio
. Please see this wiki page for more details.Note that the recently published pre-release v20.0a0 introduces
asyncio
to PTB, so starting from v20.x, the answer given by @theherk will indeed by applicable.Disclaimer: I’m currently the maintainer of
python-telegram-bot
.