I create a bot telegram that sends the current price of the Dow Jones stock. The process works in such a way that it takes a screen from Google, and then compresses it and sends it as a message. But what if 2 or more users run this command at the same time? How to avoid collisions? Do I need streams? Can I make this process faster?

@bot.message_handler(func = lambda message: '📲Dow Jones'in message.text) def repeat_all_messages222(message): url='https://www.google.com/search?q=dow+jones+current+price&oq=dow+jones+current+price&aqs=chrome..69i57&sourceid=chrome&ie=UTF-8' adr='/home/weblanss/mysite/dowJones/ss.png' bot.send_message(message.chat.id,'please wait your request is being processed') size=(120 ,190,760, 640 ) ecran(url,size,adr) w2=open(adr,'rb') bot.send_photo(message.chat.id,w2) def ecran (url,size,adr): display = Display(visible=0, size=(800, 600)) display.start() browser = webdriver.Firefox() browser.implicitly_wait(15) browser.get(url) browser.implicitly_wait(15) browser.save_screenshot(adr) browser.quit() img = Image.open(adr) crop_rectangle = size cropped_img = img.crop(crop_rectangle) cropped_img.save(adr) display.stop() 

I am using pythonanywhere server. python 3.5 or maybe there are other easy ways to get the current price? For me, the image is a good option because It is with a schedule, but I can get the price as integers. The Yahoo API, for example, does not show the current price of the Dow Jones index. Tell me what other options are there.

  • In my opinion, it is preferable to transmit the number, since it can be processed on the client side if necessary (carry out calculations, build a graph). Plus less traffic consumption than the picture. If suddenly you do not find the necessary API, then I would pull it from any reliable site (for example, rbc) using parsing html. - matrix
  • one
    make one screen once a second (for example) and send it in response to all requests received during this second - Anatol

1 answer 1

Maybe you really should use the API instead of the screenshot? As I see, the procedure is as follows:

  1. In a separate thread (here is the simplest example of performing a task after a certain period of time ) we receive data through the API you have chosen.
  2. We keep this data in memory (just keep it in a variable, Python does the rest for you) updating this data every second.
  3. We return all the data from the variable. If you really need beauty and you still prefer to return the picture to the user, you can generate your own image (with your design).

Detailed comparison of various financial APIs (English)