Skip to main content

Fortune Teller Bot ( แม่หมอสายมู )

Fortune Teller Bot คืออะไร? 

Fortune Teller Bot คือ บอททำนายดวง หลักการคือพิมพ์คำสั่งเพื่อใช้งาน Bot เช่น !ft fortune เพื่อให้บอททำนายดวงของเราออกมา หรือคำสั่ง !ft color ที่บอทจะส่งตารางของสีมงคงประจำวันกลับมาให้เรา โดยในการสร้างบอทเริ่มจาก

1.Start Discord Bot

ขั้นแรกจะเป็นการสร้างโครงสร้างพื้นฐานของ Bot ขึ้นโดยเขียนโค้ดตามด้านล่างนี้

import discord
from discord.ext import commands
import random
#เรียกใช้งาน library ที่จำเป็น

TOKEN = 'YOUR_DISCORD_BOT_TOKEN'
client = commands.Bot(command_prefix = '!ft ',intents=discord.Intents.all())

fortune_lines = ["The spirits are very happy today! They will do their best to shower everyone with good fortune.",
           "The spirits are in good humor today. I think you'll have a little extra luck.",
           "The spirits feel neutral today. The day is in your hands.",
           "This is rare. The spirits feel absolutely neutral today.",
           "The spirits are somewhat annoyed today. Luck will not be on your side."
           "The spirits are very displeased today. They will do their best to make your life difficult."]

@client.event
async def on_ready():
    print("The bot ready to forecast!!")
    print("---------------------------")

@client.command()
async def hello(ctx):
    await ctx.send("Hello, Are you ready to know your fortune today ? :raised_back_of_hand:")

@client.command()
async def fortune(ctx):
    await ctx.send(random.choice(fortune_lines))

@client.command()
async def color(ctx):
    await ctx.send('Color of fortune in 2024 by doctor Kai',file=discord.File('fortune color.png'))

client.run(TOKEN) #ใส่ TOKEN ที่นี่

table-shirt-colour-2567.png

ซึ่งจากโค้ดด้านบน น้องๆจะได้ลองใช้การส่งข้อความร่วมกับ Array โดยสร้างคำสั่งเพื่อสุ่มส่งข้อความจากใน Array และ การส่งรูปภาพด้วย Discord bot 


2.Read from text file

import discord
from discord.ext import commands
import random
#import requests
#เรียกใช้งาน library ที่จำเป็น

TOKEN = 'YOUR_DISCORD_BOT_TOKEN'
client = commands.Bot(command_prefix = '!ft ',intents=discord.Intents.all())

fortune_file = open("fortune.txt", "r")
fortune_lines = fortune_file.read().split('\n')
#อ่านไฟล์ และ เก็บไว้เป็น Array

@client.event
async def on_ready():
    print("The bot ready to forecast!!")
    print("---------------------------")

@client.command()
async def hello(ctx):
    await ctx.send("Hello, Are you ready to know your fortune today ? :raised_back_of_hand:")

@client.command()
async def fortune(ctx):
    await ctx.send(random.choice(fortune_lines))

@client.command()
async def color(ctx):
    await ctx.send('Color of fortune in 2024 by doctor Kai',file=discord.File('fortune color.png'))

client.run(TOKEN) #ใส่ TOKEN ที่นี่

จากโค้ดด้านบนน้องๆจะเห็นว่า Array หายไปแล้ว เพราะตอนนี้เราได้ย้ายคำทำนาย เข้าไปในไฟล์แทนเพื่อลดปริมาณ code ในโปรแกรมของเรา โดยใช้คำสั่ง open() เพื่อเข้าไปเปิดอ่านไฟล์นั้น และดึงมาเป็น Array ของเราแทน โดยไฟล์ข้อความคำทำนายน้องๆสามารถใช้ fortune.txt ที่พี่ๆมีให้หรือจะลองเขียนและแก้ไขเป็นคำทำนายในแบบของเราก็ได้

A journey of a thousand miles begins with a single step.
Your creativity will bring you joy and success.
Embrace change, for it brings new opportunities.
Love and laughter will fill your days.
Believe in yourself, and others will too.
Your kindness will make a difference in someone's life.
Good things come to those who wait patiently.
Take risks – great things never come from comfort zones.
Your hard work will pay off in unexpected ways.
Happiness is found within; seek it there.
Trust your instincts; they will guide you well.
Unexpected fortune is coming your way.
Challenges are opportunities in disguise.
Share your gifts with the world, and it will reward you.
Stay positive, and positivity will surround you.
Be open to new experiences; they will broaden your horizons.
Your determination will lead you to success.
A new friendship will bring you joy.
Seize the day; opportunities won't wait for you.
Your resilience will carry you through tough times.
Listen to your heart; it knows the truth.
Your smile will brighten someone's day.
Patience is a virtue; good things take time.
Stay focused on your goals; success is within reach.
Your generosity will be repaid in unexpected ways.
Trust in the process; everything happens for a reason.
Keep an open mind; it will lead to new discoveries.
Take time for self-care; it's essential for your well-being.
The best is yet to come; stay hopeful.
Your positive energy will attract success.
Treasure your loved ones; they are your greatest wealth.
Embrace simplicity; it brings clarity and peace.
Your determination will overcome any obstacle.
Show gratitude; it invites abundance into your life.
Dream big; your dreams are within reach.
Take a leap of faith; it will lead to great adventures.
Your intuition will guide you to the right path.
Be adaptable; it's the key to survival and growth.
A new opportunity will present itself soon.
Be kind to yourself; self-love is important.
Your positive attitude will attract positive outcomes.
Trust in your abilities; you are capable of greatness.
Find joy in the little things; they matter the most.
Stay curious; it leads to continuous learning.
Your resilience will overcome any challenge.
Keep an optimistic outlook; it brightens your path.
Embrace change; it leads to personal growth.
Your determination will lead to success.
Take time to relax and recharge your energy.
Believe in miracles; they happen every day.
Your past does not define your future; you hold the power to change.
A kind gesture will have a ripple effect.
Trust the timing of your life; everything happens when it should.
Your efforts will be recognized and rewarded.
Stay true to yourself; authenticity is your strength.
Embrace uncertainty; it leads to new possibilities.
Your courage will lead to great achievements.
Let go of what no longer serves you; make room for new blessings.
Your inner wisdom will guide you in challenging times.
Keep a positive mindset; it shapes your reality.
Your patience will lead to success in due time.
Opportunities are everywhere; keep your eyes open.
Trust in the universe; it has a plan for you.
Your kindness will create a ripple of goodwill.
Stay committed to your goals; persistence pays off.
Embrace challenges; they make you stronger.
Believe in the power of your dreams; they're achievable.
Your determination will overcome any setback.
Keep an open heart; love will find its way to you.
Celebrate your successes, big or small.
Your perseverance will bring you closer to your goals.
Trust your instincts; they lead you in the right direction.
Stay true to your values; they define who you are.
Your resilience will lead to triumph.
Embrace the unknown; it holds endless possibilities.
Believe in your abilities; you're capable of amazing things.
Keep an open mind; it leads to growth and understanding.
Your positivity will attract positive outcomes.
Trust in your inner strength; it will guide you.
Stay focused on your goals; they are within reach.
Your compassion will touch someone's heart.
Seize the moment; it's yours to make the best of.
Your determination will pave the way to success.
Embrace change; it brings growth and evolution.
Believe in the power of your dreams; they're your guiding stars.
Your resilience will overcome any adversity.
Keep faith in yourself; you're stronger than you think.
Trust in the process; everything will fall into place.
Your kindness will create a ripple effect of goodness.
Stay persistent; it leads to accomplishment.
Believe in your abilities; they will take you far.
Embrace challenges; they build character.
Your patience will be rewarded in due time.
Keep a positive attitude; it attracts positive outcomes.
Trust in your intuition; it's your inner compass.
Stay open to possibilities; they're endless.
Your perseverance will lead to triumph.
Embrace each day with gratitude; it brings abundance.
Believe in your dreams; they're the roadmap to your success.
Your determination will overcome any obstacle in your path.


3.Integration with IOT

ในส่วนนี้จะความท้าทายมากขึ้นโดยจะเป็นการทำงานระหว่าง Discord Bot ร่วมกับ IOT เพื่อสั่งอุปกรณ์ IOT ผ่าน API

import discord
from discord.ext import commands
import random
import requests
import time
#เรียกใช้งาน library ที่จำเป็น

TOKEN = 'YOUR_DISCORD_BOT_TOKEN'
client = commands.Bot(command_prefix = '!ft ',intents=discord.Intents.all())

fortune_file = open("fortune.txt", "r")
fortune_lines = fortune_file.read().split('\n')
#อ่านไฟล์ และ เก็บไว้เป็น Array

todayF = random.choice(fortune_lines)
iot_ip = "http://172.20.10.2"

@client.event
async def on_ready():
    print("The bot ready to forecast!!")
    print("---------------------------")

@client.command()
async def hello(ctx):
    await ctx.send("Hello, Are you ready to know your fortune today ? :raised_back_of_hand:")

@client.command()
async def fortune(ctx):
    # call light&sound api
    for i in range(5):
        try:
            requests.get(iot_ip + "/on?red=1&blue=0&green=0")
            requests.get(iot_ip + "/play?hz=261&duration=0.1")
            time.sleep(0.1)
            requests.get(iot_ip + "/on?red=0&blue=0&green=1")
            requests.get(iot_ip + "/play?hz=293&duration=0.1")
            time.sleep(0.1)
            requests.get(iot_ip + "/on?red=0&blue=1&green=0")
            requests.get(iot_ip + "/play?hz=329&duration=0.1")
            time.sleep(0.1)
        except:
            print("Failed to call IOT API!")
    try:
        requests.get(iot_ip + "/play?hz=350&duration=0.5")
    except:
        print("Failed to call IOT API!")
    await ctx.send(random.choice(fortune_lines))

@client.command()
async def color(ctx):
    await ctx.send('Color of fortune in 2024 by doctor Kai',file=discord.File('fortune color.png'))

client.run(TOKEN) #ใส่ TOKEN ที่นี่

โดยใช้ try and except เพื่อจัดการในกรณีหากมีการทำงานที่ไม่ถูกต้องขณะเรียกใช้ API ตัว Bot จะส่งข้อความกลับมาที่ Terminal ว่า "Failed to call IOT API!"