0

I am creating a telegram bot which will send me current stock price of the Dow Jones. The process is working in this way: it takes a screen shot from Google, saves it, then cuts it and sends it as message. But what if someone 2 or more people will run this command at the same time? I do not want collisions. Do I need some threads or what? Can I do 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 some other easy ways to get the current price? For me a picture is a better way but if it's possible to get a price as integers. Yahoo finance for example does not show the current price of Dow Jones index

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
egorkh
  • 478
  • 8
  • 24

1 Answers1

0

If you want to avoid collisions the best way in my opinion is to cache the price index for a short time. Obviously, the price index doesn't change every second.

To implement the caching, you can set a timeout (let's say 1 minute) and a flag. Initialize them like this:

timeout = time.time() and flag = False. Note that time.time() returns current time.

Whenever a user requests for price index, first you check if more than 1 minute has passed the timeout:

if time.time() - timeout > 1 * 60:
    # you need to update the screenshot
else:
    # you can send the user the previously taken screenshot

The flag here is to prevent collision. If flag is True it means the system is taking a screenshot right now, and it can't be requested again until it's finished. Therefore, we complete out code like this:

if time.time() - timeout > 1 * 60:
    if flag is False:
        flag = True
        take_screenshot()
        flag = False
    while flag is True:
        time.sleep(1)
    send_screenshot()
else:
    send_screenshot()
Ali Hashemi
  • 3,158
  • 3
  • 34
  • 48