Discord Bot

資訊之芽 2022 Python 語法班
Author: Sean 韋詠祥

Note:
日期:2022-06-12
課程時間:14:00 - 15:20


什麼是 Chatbot

  • 陪你聊天、當你的工具人
  • 在 Discord、Telegram、Slack 可以自由開發
  • 如果是 Messenger、LINE 則需要審核、付費

什麼是 API

  • 還記得前幾週的爬蟲嗎?
  • 制式化的介面,對程式更友善

Discord Bot 可以怎麼玩

  • 身份組機器人
  • 音樂機器人
  • 歡迎訊息
  • 活躍度排名、小遊戲
  • 搜尋、訂閱

身份組 Bot


音樂 Bot


歡迎訊息


活躍度排名


小遊戲


訂閱


搜尋貓貓


團購訂餐


註冊開發者帳號



Developer Portal


新增 Application


邀請時用的暱稱


建立完成


新增一個 Bot


預設 Bot 名稱為 App 名稱


改名、加上頭貼


產生邀請網址


選擇 bot 類型


勾選需要的權限


點開網址


建立伺服器


選擇自訂


私人用途


取伺服器名稱


完成!


邀請 Bot 加入


選擇伺服器


授權加入


安裝 discord.py

pip3 install discord.py

Discord.py QuickStart

Note:
請各位自己搜尋,這裡刻意不提供超連結


實際執行

discord.errors.HTTPException: 401 Unauthorized

Traceback (most recent call last):
  File "bot.py", line 17, in <module>
    client.run('your token here')
  File "site-packages/discord/client.py"
    await self.login(*args, bot=bot)
discord.errors.LoginFailure: Improper token has been passed.
  • 跳出 HTTP 401 錯誤

取得 Discord Token


將 Token 貼進程式中

import discord client = discord.Client() @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith('!ping'): await message.channel.send('Nice to meet you!') client.run('OTgy....xzfU')

Note:
https://discordpy.readthedocs.io/en/stable/quickstart.html


成功!


補充解釋:format 語法

name = 'Sean'
time = '14:30'
# 基本用法
print('Hey ' + name + ', it\'s ' + time + ' now.')

# 格式化文字
print(f'Hey {name}, it\'s {time} now.')
# 用 'string'.format(...) 處理格式化
print('Hey {}, it\'s {} now.'.format(name, time))

# 如果想指定變數順序呢?
print('{1}: Hey {0}, how are you?'.format(name, time))
# 讓我們再看一次前面的例子
print('We have logged in as {0.user}'.format(client))

Discord 設定


啟用開發者模式


複製伺服器 ID


複製頻道 ID


Discord 小技巧


dotenv

  • 還記得上個月教的 git 版本控制嗎?
  • 要分享程式碼時怎麼辦
  • 如果把 Token 寫死,交作業時不方便

安裝 dotenv

pip3 install python-dotenv

使用方式

from os import getenv
from dotenv import load_dotenv

load_dotenv()
TOKEN = getenv('TOKEN')

完整程式碼

import discord from os import getenv from dotenv import load_dotenv # Load TOKEN from .env file load_dotenv() TOKEN = getenv('TOKEN') # Initial our bot client client = discord.Client() @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) @client.event async def on_message(message): if message.author == client.user: return # Ignore messages from myself, prevent loop # In this example, we use ! as command prefix if message.content.startswith('!ping'): await message.channel.send('Hey there!') # Must after all functions client.run(TOKEN)

更多玩法

  • XX Bot 正在玩 資訊之芽
  • XX Bot 正在聽 Podcast

玩遊戲

if message.content.startswith('$play'):
    await client.change_presence(
            status=discord.Status.dnd,
            activity=discord.Game(name="資訊之芽"))
    await message.channel.send('I like playing!')

看影片

if message.content.startswith('!watch'):
    await client.change_presence(
            status=discord.Status.idle,
            activity=discord.Activity(
                type=discord.ActivityType.watching,
                name="Apple 發表會"))

還有更多

  • Playing 正在玩
  • Streaming 正在直播
  • Listening 正在聽
  • Watching 正在看
  • Custom 正在
  • Competing 正在比

請參考 ActivityType


Thanks

投影片連結:https://hackmd.io/@Sean64/dc-bot


CC-BY 4.0

這份投影片以 創用 CC - 姓名標示 授權公眾使用,原始碼及講稿請見 此連結

休息時間

下一堂課內容:

  • Decorator、繼承、sync/async 等語法介紹
  • 自己寫實用小遊戲
  • 大作業講解
Select a repo