Skip to main content

Pub bot ( ดีเจ )

Pub bot คืออะไร?

เป็นบอทที่จะเปลี่ยนแสงของ LED และเล่นเสียงตามตัวอักษรที่เราใส่เข้าไป โดยมี 3 สีประกอบด้วย Red, Green, Blue และความถี่เสียงตามสีนั้นๆ เช่น !yo RGB จะทำการเปิดไฟตามลำดับ แดง เขียว และ น้ำเงิน

1. Create structure

from time import sleep
import discord
import requests
from discord.ext import commands

TOKEN = "MTE5Mzc2MjIxMzYxNDM0MjI5NQ.GIA8dH.cKXYVEq0EULsWe5EkgAnxDhQKEFgYq_w-lSRjs"YOUR_DISCORD_BOT_TOKEN"

client = commands.Bot(command_prefix="!", intents=discord.Intents.all())
color_dict = {
  "R": "red",
  "G": "green",
  "B": "blue"
}

frequency_dict = {
  "R": 261,
  "G": 293,
  "B": 329
}
iot_ip = "http://172.20.10.2"

@client.event
async def on_ready():
    print("Ready to be DJ?")


@client.command()
async def yo(ctx, letters):
    if letters == "off":
        try:
          lightoff = requests.get(iot_ip + "/off")
        except:
            print("Failed to call IOT API!")
    for letter in letters:
        try:
            # call light api
            if color_dict[letter] == "red":
                print("red triggered")
            elif color_dict[letter] == "green":
                print("green triggered")
            elif color_dict[letter] == "blue":
                print("blue triggered")
            # call sound api
            print(frequency_dict[letter])
            sleep(0.1)
        except:
            print("Failed to call IOT API!")
    await ctx.send("Let's them cook")
        

# put token here naja
client.run(TOKEN)

2. Implement API from IOT workshop

from time import sleep
import discord
import requests
from discord.ext import commands

TOKEN = "MTE5Mzc2MjIxMzYxNDM0MjI5NQ.GIA8dH.cKXYVEq0EULsWe5EkgAnxDhQKEFgYq_w-lSRjs"YOUR_DISCORD_BOT_TOKEN"

client = commands.Bot(command_prefix="!", intents=discord.Intents.all())
color_dict = {
  "R": "red",
  "G": "green",
  "B": "blue"
}

frequency_dict = {
  "R": 261,
  "G": 293,
  "B": 329
}
iot_ip = "http://172.20.10.2"

@client.event
async def on_ready():
    print("Ready to be DJ?")


@client.command()
async def yo(ctx, letters):
    if letters == "off":
        try:
          lightoff = requests.get(iot_ip + "/off")
        except:
            print("Failed to call IOT API!")
    for letter in letters:
        try:
            # call light api
            if color_dict[letter] == "red":
                requests.get(iot_ip + "/on?red=1&blue=0&green=0")
            elif color_dict[letter] == "green":
                requests.get(iot_ip + "/on?red=0&blue=0&green=1")
            elif color_dict[letter] == "blue":
                requests.get(iot_ip + "/on?red=0&blue=1&green=0")
            # call sound api
            print(frequency_dict[letter])
            requests.get(iot_ip + "/play?hz=" + str(frequency_dict[letter]) + "&duration=0.1")
            sleep(0.1)
        except:
            print("Failed to call IOT API!")
    await ctx.send("Let's them cook")
        

# put token here naja
client.run(TOKEN)