SFX & Derp Wars (a Dope Wars clone) [Live Coding Recap]
Tags: python, beginners, livecoding, twitch
Published: 2019-11-08 22:37:58

## Streamed: 11/05 on Twitch

🔴 **Watch** ⇒ [Twitch VOD](https://www.twitch.tv/videos/504545690) (replay)

The  first goal of the night was getting a random soundbite to play during streams when certain “trigger” words are said. 

> **Example:** Someone in chat says “wow” in a sentence and a random clip of Owen Wilson sayin “wow” plays. 

Then we started work on a clone of Dope Wars (which we named Derp Wars).

## Wait... Dope Wars?? What!?

In what might have amounted to the best/worst idea I've ever had, chat & I started working on a clone of Dope Wars (aka [Drugwars](https://en.wikipedia.org/wiki/Drugwars)). Dubbed Derp Wars by viewers, the plan is to use the game in educational content. **Expect a full tutorial** on DEV as well as a YT post coming up in the next week or so! :D

**Language(s) Used:**  [Python](http://bit.ly/nb9kPython)
**Tech & lib(s) used:** [VSCode](http://bit.ly/vscodenb9k), [TwitchIO](https://github.com/TwitchIO/TwitchIO)
**Project Repository** [⭐ **DeepThonk**](http://bit.ly/DeepThonkRepo)

> 👇 Code & notes from stream down below! :D

## During the stream we...
✔ continued working on the random sfx feature we started last stream
✔ realized we need `Honk The Planet` t-shirts
✔ made a note to get the `Big Dict() Energy` t-shirts done too
✔ created a class for interfacing with the server
✔ got random sfx working and CELEBRATED 🎉 (wow)
✔ freaked out because we thought the streamdeck broke
✔ started working on Derp Wars
✔ got a basic MVP working!
✔ raided [@HighGai](https://www.twitch.tv/highgai), a rad Japanese/English streamer

## Here's some code we wrote during the stream...

In the bot app, we listen for `message events`. When a message event comes through, we _tokenize™_ the content, check to see if a trigger word was said, then emit a websocket event to the server to play the sound if it does.

```python
# in events.py
randos = server_interface.get_randos() # get sfx trigger words from server

@bot.listen("event_message")
async def rando_sfx(ctx):
    'listens for certain words then triggers a sfx from them'
   
    # make sure bot ignores itself
    author = ctx.author.name.lower()
    if author == twitch_bot_nick.lower():
        return

    # listen for trigger words in messages
    for word in randos:
        if word.lower() in ctx.content.lower().split(' '):
            # emit ws event to call the sfx from teh server
            await emit_rando_sfx(word.lower())
            log.debug(f"WE HEARD A WORD!! ({word})")  # it's bird
``` 

The function that emits the ws is pretty simple. It just talks to the Flask server that hosts the browser source that queues and plays the audio.

```python
# in server_interface.py
async def emit_rando_sfx(word):
    'tell teh server a rando sfx word was said'
    await sio.emit(event='rando', data=word)
```

When the server receives the ws, it's all like "Aiight, I'll let the page know." Then it *finger guns into infinity*. 👈😎👈

```python
# in server.py (the Flask app)
@socketio.on('rando')
def sfx_event(word, methods=['GET', 'POST']):
    'Recievs SFX requests from bot app & triggers SFX on the Browser Source'
    
    word_said = str(word)  # i'm tellin ya, it's bird.

    # choose a random file in directory
    random_file = random.choice(os.listdir(f'static/sfx/randos/{word_said}/'))

    # emit play rando sfx to the webpage thingy
    socketio.emit('rando triggered', [word_said, random_file])
    log.debug(f"RANDO Triggered => {word_said}")
```

From that point, the web page just listens for the websocket and queues up the audio to play.

```javascript
// in sfx.js
socket.on( 'rando triggered', msg => {
    addToQueue(`/static/sfx/randos/${msg[0]}/${msg[1]}`);
  })
```

There are a few tweaks we need to make to the code to make it flawless. For instance, since we’re tokenizing/splitting with spaces, this code won’t work with trigger words next to punctuation of any kind. We’ll tackle those issues on an upcoming stream. :)

## Live Coding Schedule

That pretty much wraps things up for this stream. If you have any questions about the code, Python, or any of the tech used in general - swing by during a live stream and say hello!

💜 **Follow on [Twitch](http://bit.ly/nb9kTwitch)**

I stream Python coding & _lame jokes™_ on [Twitch](https://twitch.tv/ninjabunny9000) every Tuesday, Thursday, & Saturday around 7pm PST.

**For the most up to date schedule**, check my pinned post on [Twitter](https://www.twitter.com/ninjabunny9000).