# 利用 Discord.py 寫出屬於你的 Discord Bot :::info 這份講義蠻特別的,它整合了很多外部資源。這些外部資源主要是有關 Discord.py API 文件的說明,我希望我能做到的是: 和你一起把一份小專案寫出來,一些語法或知識我才會以我的簡報進行講解。 [專案連結](https://github.com/richardlaiis/Astolfo-discord-bot) ::: ## 環境與先備措施 ## 上線 ```python= import discord from discord.ext import commands import json with open('./setting.json', 'r', encoding='utf8') as jsonFile: info = json.load(jsonFile) intents = discord.Intents.all() bot = commands.Bot(command_prefix='.', intents = intents) @bot.event async def on_ready(): print('Bot is online.') @bot.command() async def ping(ctx): await ctx.send(f'{bot.latency} (s)') bot.run(info['TOKEN']) ``` ### What is Json? + JavaScript Object Notation (JSON) + 用來呈現 Javascript 裡面的物件 + 格式有點像 key-value pair ### What is CSV file? + Comma Seperated Values + CSV檔案由任意數目的記錄組成,記錄間以某種換行符(通常為逗號)分隔 ### What is XML file? + [不錯的介紹](https://ithelp.ithome.com.tw/m/articles/10073956) ## 基礎指令 1. 試著寫寫看一些自創的指令吧! 2. 但...這樣一個檔案程式碼容易太長,來設定 [Cogs](https://hackmd.io/@smallshawn95/python_discord_bot_cog) 吧! ### 檔案讀寫 [簡報在這](https://slides.com/laiyuchi1130/python-file-basic/) ### f-string (格式化字串) f-string 的使用可以讓字串與表達式(Expression,即具有"值"的式子)的組合更加方便,執行效率也比起 `.format()` 略快(用法請見[這裡](https://www.w3schools.com/python/ref_string_format.asp))。 ```python= # Example 1 name = "Alice" age = 30 greeting = f"Hello, my name is {name} and I am {age} years old." print(greeting) # 會輸出 Hello, my name is Alice and I am 30 years old. ``` ```python= a = 5 b = 10 result = f"The sum of {a} and {b} is {a + b}." print(result) ``` 此外,f-string 也可以用來指定輸出格式(EX: 對齊、小數點位數): ```python= from math import pi print(f"The value of pi is {pi:.5f}") # 會輸出 3.14159 ``` 也可以用於多行字符串: ```python= name = "Alice" age = 30 multi_line_greeting = f""" Hello, My name is {name}. I am {age} years old. """ print(multi_line_greeting) ``` ### async / await `async`關鍵字用於定義一個異步函數。異步函數是可以被異步調用的函數,並且會返回一個協程對象。協程對象可以被用於等待其完成,通常與`await`一起使用。 + [好文章1](https://ithelp.ithome.com.tw/articles/10262385) + [好文章2](https://myapollo.com.tw/blog/begin-to-asyncio/) ```python= import asyncio # 定義一個協程函數 async def fetch_data(): print("Fetching data...") await asyncio.sleep(2) # 模擬耗時操作 print("Data fetched.") return "data" # 定義另一個協程函數 async def process_data(): data = await fetch_data() # 等待 fetch_data 完成 print(f"Processing {data}...") await asyncio.sleep(1) # 模擬處理時間 print("Data processed.") # 使用 asyncio 來運行協程 asyncio.run(process_data()) ``` ## 補充: slash commands https://hackmd.io/@smallshawn95/python_discord_bot_slash