In this tutorial, we’ll build a fun bot that plays ASCII art videos (Bad Apple) on Poe using Django.
Overview
The Poe platform allows developers to create bots that users can interact with in the app. Poe provides a specification that bots need to implement to communicate properly.
Here, I use Django to handle the HTTP requests from Poe server and stream back ASCII art video (specifically, Bad Apple) frames rendered from a source video file. The key ideas are:
- Use the
StreamingHttpResponse
to send back server-sent events - Read the ASCII art video frames from a text file and send them back one by one
- Use the
replace_response
event to update the displayed frames
Project Setup
First, install the dependencies:
|
Decouple reads config values from a .env file. Sse-starlette helps generate server-sent events.
Then, you need a Django project. Run:
|
Then create an app:
|
Implementing the Bot Logic
In views.py
, we’ll handle the API requests:
|
The key points:
query_event_stream
handles creation of response events- Use a generator function to lazily yield events
StreamingHttpResponse
streams the events
Next, we open the video file and yield the frames:
|
The video file contains the pre-rendered ASCII frames. We sleep briefly between frames to maintain the video FPS. The replace_response
event swaps the displayed frame.
Finally, send the done
event to end streaming:
|
Creating the Video File
The video file contains the ASCII art frames. Use the following script to convert a video file to ASCII art frames:
https://github.com/richardhyy/badapple-poe-bot/blob/main/tools/video2ascii.py
Example usage:
|
Put the video file in the resources
folder.
Your project structure should look like this:
|
Configuring Django
In settings.py
:
|
Add the bot’s URL to urls.py
:
|
Full Code
The full code is available at this repo.
It also features the following improvements to code in this tutorial:
- Access Key authentication
- Use python-decouple to read config values from a .env file
- Introduction message
Deploying the Bot
You can deploy the bot to any Django-compatible hosting.
Once deployed, you can add the bot to Poe by creating a server bot with URL https://your_server_ip/chat/poe
.
The bot will now respond to requests from Poe!