Discord Bot 可以怎麼玩
(credit to Sean)
- 身份組機器人
- 音樂機器人
- 歡迎訊息
- 活躍度排名、小遊戲
- 搜尋、訂閱
身份組 Bot

音樂 Bot

歡迎訊息

活躍度排名

小遊戲

訂閱

搜尋貓貓

團購訂餐

新增機器人到自己的伺服器
- 建立 application & bot
- 建立伺服器
- 把 bot 邀請進去
步驟截圖請見去年簡報
$ python3 -m pip install discord.py
建立 Discord Bot
| import discord |
| |
| intents = discord.Intents.default() |
| intents.message_content = True |
| |
| client = discord.Client(intents=intents) |
| |
| @client.event |
| async def on_ready(): |
| print(f"We have logged in as {client.user}") |
| |
| @client.event |
| async def on_message(message): |
| if message.author == client.user: |
| return |
| if message.content.startswith("$hello"): |
| await message.channel.send(f"hello, {message.author}") |
| |
| client.run("TOKEN") |
建立指令
| import discord |
| from discord.ext import commands |
| |
| intents = discord.Intents.default() |
| intents.message_content = True |
| |
| client = discord.Client(intents=intents) |
| bot = commands.Bot(command_prefix="!", intents=intents) |
| |
| @bot.command() |
| async def ping(ctx): |
| await ctx.send("pong") |
| |
| bot.run("TOKEN") |
補充 - Decorator
| @bot.command() |
| async def ping(ctx): |
| await ctx.send("pong") |
補充 - Decorator
- Python 的語法糖
- 把你宣告的函式包進一個已經寫好的函式裡
補充 - Decorator
| import time |
| from functools import wraps |
| |
| def timeit(func): |
| @wraps(func) |
| def wrapper(*args, **kwargs): |
| start = time.time() |
| res = func(*args, **kwargs) |
| end = time.time() |
| print('Time spent in %s is %f seconds.' % (func.__name__, end - start)) |
| return res |
| return wrapper |
| |
| def fib(n): |
| if n <= 2: |
| return 1 |
| return fib(n - 1) + fib(n - 2) |
| |
| @timeit |
| def run(): |
| print(fib(40)) |
| |
| if __name__ == '__main__': |
| run() |
補充 - async
- 遇到耗時間但你不用做事的事情的時候,可以把 CPU 拿去做其他事情以避免浪費
- e.g., 網路傳輸、資料庫讀寫、…
補充 - async
| import time |
| import asyncio |
| |
| async def do_something2(i): |
| print(f"第 {i} 次開始") |
| await asyncio.sleep(2) |
| print(f"第 {i} 次結束") |
| |
| if __name__ == "__main__": |
| start = time.time() |
| loop = asyncio.get_event_loop() |
| tasks = [loop.create_task(do_something2(i + 1)) for i in range(5)] |
| loop.run_until_complete(asyncio.wait(tasks)) |
| loop.close() |
| print(f"time: {time.time() - start} (s)") |
補充 - Token
- Token 很重要
- 不能寫在檔案裡面讓大家看光光
- 要寫到其他地方
補充 - Token
$ set token=TOKEN
$ export token=TOKEN
補充 - Token
- 然後在 python 裡面讀出來
- 給 discord bot 去跑
| import os |
| TOKEN = os.getenv("token") |
| |
| ... |
| |
| client.run(TOKEN) |
Discord Bot siriuskoan
{"metaMigratedAt":"2023-06-18T03:44:48.007Z","metaMigratedFrom":"YAML","title":"Discord Bot","breaks":true,"contributors":"[{\"id\":\"a2dd0460-a150-40b3-8024-44d3b3f2e06b\",\"add\":3336,\"del\":29}]"}