March 16, 2024 at 22:12
I have a really simple one for you all today, but it has had a fairly significant impact on our lives. It’s beneficial for a beginner Python developer to know, but I can already hear anyone familiar with the language laughing at me right now.
You see, my kids are siblings. They argue. When my son doesn’t get his way, he’ll find a loophole or negotiate until he’s blue in the face, then walk away if there’s no hope. My daughter, on the other hand, will switch to 100% silent mode and walk away if someone doesn’t offer her the win. You know, typical kid nonsense.
Python has surprisingly helped calm these issues since I’ve convinced my kids that the computer is an impartial, unfeeling robot monster. So, no matter what the robot picks, it’s not because it doesn’t want you to win. It’s because it doesn’t care which kid it eats first. It’s important as a parent to instill a healthy respect and fear for technology. How else will we stand a chance in the AI wars of 2027?
So, here’s how it’s done. Import the necessary libraries Python needs to run the code below.
movies.py
import random
from urllib import request
import json
# Function that sends whatever text you want to your Slack channel.
def send_message_to_slack(text):
post = {"text": "{0}".format(text)}
try:
json_data = json.dumps(post)
req = request.Request("https://hooks.slack.com/services/APIKEY/",data=json_data.encode('ascii'),headers={'Content-Type': 'application/json'})
resp = request.urlopen(req)
except Exception as em:
print("EXCEPTION: " + str(em))
# Grabs your movies.txt file - which is just a text file that has a list of movies.
with open('/folder/movies.txt', 'r') as file:
movies = [line.strip() for line in file]
# Tell Python to choose a random one and send the name of it to Slack. Easy peasy.
choice = random.choice(movies)
send_message_to_slack("🍿 MovieBot 🎞️\nTonight's Movie: " + choice)
Set this script to run at certain times or run it manually. Enjoy the movie. Knock it off the list. Simple.