How I got tickets to a quickly sold out Brandon Sanderson lecture with 40 lines of Python code
Tags: python
Published: 2019-11-28 18:49:42

In short — when the tickets became available, my phone received this notification:
![Finished](https://thepracticaldev.s3.amazonaws.com/i/476y76vik9vde1lml2x3.png)

# The background story

Several months ago, the local Fantasy & Science Fiction organization invited Brandon Sanderson, who is my favorite Fantasy author of all times, to be the guest of honor at the annual “Icon” festival (a fantasy & Sci-Fi festival)

As soon as I heard it, I knew I had to be there for one of his lectures. I’ve read almost every major book he wrote, and his worlds inspired me without end. I actually read all of his major books in several months.
A week ago, finally, they released the official schedule for the festival, and in it — Sanderson’s lectures. But, to my surprise, they didn’t release the tickets for sale yet. Instead, the schedule had a “Closed sale, tickets will be available in a few days” headline.
Since I’m familiar with the regular lecture halls from earlier years, I knew that they are pretty small, and if I want to get a ticket to one of his lectures, I would have to be pretty quick.
As the word spread on social media, and talks over the Sci-Fi and Fantasy groups intensified, I felt that the chances of getting a ticket were going down by the minute. I couldn’t let this opportunity escape.

I shared my dread with a friend, who offered me a cool idea (I’m not even sure he was 100% serious)
He said — “Hey, why don’t you write something to help you? You only need to see when the tickets are available and notify yourself. It can’t be that hard.”

And he was right. It wasn’t hard.


# The design
So I sat down to write a python script, that notifies me when tickets are available. The basic idea was this: As soon as the script finds a change in the ticket site, it needs to send a push notification directly to my phone.
That was the only way I knew I would see the tickets in time since my phone was always with me, and so the chances of me getting notified are pretty high.
I also decided that a check every 10 minutes should be enough, I thought to myself — the tickets won’t be sold out that quickly (spoiler: I was only half correct, one of the workshops was sold out in two minutes)

The code itself is pretty straightforward, but I thought I should share it, in case there are other programmers out there that have no idea how easy it is to do something like this and make their lives a bit easier.


# Preparations

Programming language: Python
Requirements: Only one package from PyPI— “notify-run”
It’s a great python package, you can find its Github page here.
You can get notify-run by going to your python environment (I’m assuming you’re using virtual-env) and run:
```bash
pip install notify-run
```

When it’s done, you’ll have to register a channel. This channel will allow your code to send notifications directly to your phone, via your phone’s web browser. So, after installing notify-run, you need to run:
```bash
notify-run register
```
_Windows users: If you’ve used a virtual-env to install notify-run, you can find your notify-run executable at the venv “Scripts” folder (venv\Scripts), along with ‘pip’, ‘python’, and ‘easy_install’._

This cool package creates a channel for you. After you run that command, you’ll get a QR code and a link to connect your phone to the newly created channel

![QR](https://thepracticaldev.s3.amazonaws.com/i/stl6rq9kvxq09p2zqtjs.png)

Your local environment is ready. Now you only need to write the code.

# The code

The code itself, as I said, is pretty simple. I was not too worried about performance since I decided that it should run every 10 minutes. The site itself was static, no code was generated after the request was made, so it made it even easier. My only real challenge was getting myself notified, the rest was pretty easy. I’ll present the code and then explain it.

```python
from urllib.request import urlopen
from notify_run import Notify
import re
from time import sleep
def notify_me(url):
    # The notify-run object
    notify = Notify()
    data = (urlopen(url)).readlines()

    # A simple counter, to notify every 2 hours it's still alive
    count = 0
    # A first message, to check for the health of the channel.
    notify.send('Starting notification process')
    found = False
    # try/finally so I would get notified if the script stopped
    # for any reason.
    try:
        # A simple while, with a 2 hour health check.
        while not found:
            found = True
            for line in data:
                x = re.search('Closed sale', str(line))
                if x:
                    found = False
                    break
            sleep(600)
            count += 600
            if count >= 7200:
                # Notify me that the code is still running
                notify.send('Alive, waiting for a change in the site.')
                count = 0
            data = (urlopen(url)).readlines()
    finally:
        # If we got here,I should buy the tickets,
        # or something went wrong. Either way, I should check
        notify.send('The site has changed! check it!')
```

The function has 2 parts — The first one, is a preparation part, the second is the main loop, which notifies its health status every 2 hours.
The first line is simple — define the notify object. This object allows us the communicate with the notify-run channel we registered to earlier.
Then, we use the urllib.requests package to open the page and get it. We then read the lines of that object, and insert them into data.
The first interesting call is the notify.send('Starting') call. Here, we send the first notification to the channel.

In this part, your phone should look like this:
![starting](https://thepracticaldev.s3.amazonaws.com/i/y9v4kmmb1yse9behbint.png)

The next part is a simple while loop. Every 10 minutes (600 seconds), download the site, traverse it using the regular expression package (re), and check for the exact words ‘Closed sale’. If you find them — it means the site did not change yet, so no tickets are available.
So every 2 hours, you would see this notification:
![alive](https://thepracticaldev.s3.amazonaws.com/i/gf0oscoqlmeus5pndigj.png)

But if ‘re’ can’t match those words — This means the site has changed, and the while loop should now break, and you would see this notification on your phone:
![Finished](https://thepracticaldev.s3.amazonaws.com/i/476y76vik9vde1lml2x3.png)

That’s it! you’ve done it. Now you can create your own scripts to help automate ticket buying for shows and movies you want.

If you have any questions, feel free to send me a message!