Sean Wei
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
--- type: slidex tags: presentation title: Discord Bot - 資訊之芽 2022 Python 語法班 description: Sean 韋詠祥 / 2022-06-12 14:00 / 什麼是 Chatbot / Discord Bot 可以怎麼玩 / 新增 Application / 新增一個 Bot / 安裝 discord.py / 取得 Discord Token / 補充解釋:format 語法 / 用 'string'.format(...) 處理格式化 / 安裝 dotenv / 更多玩法 / 玩遊戲 / 看影片 --- # Discord Bot 資訊之芽 2022 Python 語法班 Author: Sean 韋詠祥 Note: 日期:2022-06-12 課程時間:14:00 - 15:20 ---- ## 什麼是 Chatbot - 陪你聊天、當你的工具人 - 在 Discord、Telegram、Slack 可以自由開發 - 如果是 Messenger、LINE 則需要審核、付費 ---- ## 什麼是 API - 還記得前幾週的爬蟲嗎? - 制式化的介面,對程式更友善 --- ## Discord Bot 可以怎麼玩 - 身份組機器人 - 音樂機器人 - 歡迎訊息 - 活躍度排名、小遊戲 - 搜尋、訂閱 ---- ## 身份組 Bot ![](https://i.imgur.com/dYipNNv.png) ---- ## 音樂 Bot ![](https://i.imgur.com/JsmoWgy.png) ---- ## 歡迎訊息 ![](https://i.imgur.com/03GQgBb.png) ---- ## 活躍度排名 ![](https://i.imgur.com/aRFpvEF.png) ---- ## 小遊戲 ![](https://i.imgur.com/xv5WCDP.png) ---- ## 訂閱 ![](https://i.imgur.com/zN1QIh7.png) ---- ## 搜尋貓貓 ![](https://i.imgur.com/6ZwE2W5.png) ---- ## 團購訂餐 ![](https://i.imgur.com/XGDEcm0.png) --- ## 註冊開發者帳號 ![](https://i.imgur.com/lfEOByP.png) ---- ## 從 footer 進入 ![](https://i.imgur.com/6eymZ9P.png) ---- ## Developer Portal ![](https://i.imgur.com/ka7x6ao.png) ---- ## 新增 Application ![](https://i.imgur.com/eZu9x1L.png) ---- ## 邀請時用的暱稱 ![](https://i.imgur.com/4DPP2B9.png) ---- ## 建立完成 ![](https://i.imgur.com/zvWwZPO.png) --- ## 新增一個 Bot ![](https://i.imgur.com/sP1A2yv.png) ---- ## 預設 Bot 名稱為 App 名稱 ![](https://i.imgur.com/Ghu0WvM.png) ---- ## 改名、加上頭貼 ![](https://i.imgur.com/I6WW2gx.png) ---- ## 產生邀請網址 ![](https://i.imgur.com/RlpSbdF.png) ---- ## 選擇 bot 類型 ![](https://i.imgur.com/iMgdh9Z.png) ---- ## 勾選需要的權限 ![](https://i.imgur.com/w2220ry.png) ---- ## 點開網址 ![](https://i.imgur.com/cpc3r6l.png) --- # 建立伺服器 ![](https://i.imgur.com/mhB7hxu.png) ---- ## 選擇自訂 ![](https://i.imgur.com/LKVZHOP.png) ---- ## 私人用途 ![](https://i.imgur.com/nYkp35j.png) ---- ## 取伺服器名稱 ![](https://i.imgur.com/szQiGO7.png) ---- ## 完成! ![](https://i.imgur.com/ejGByM6.png) ---- ## 邀請 Bot 加入 ![](https://i.imgur.com/cpc3r6l.png) ---- ## 選擇伺服器 ![](https://i.imgur.com/ZkJYyMA.png) ---- ## 授權加入 ![](https://i.imgur.com/HhyLn9E.png) --- ## 安裝 `discord.py` ```shell pip3 install discord.py ``` ---- ## `Discord.py` QuickStart ![](https://i.imgur.com/i07WqEA.png) 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 ![](https://i.imgur.com/I6WW2gx.png) ---- ## 將 Token 貼進程式中 ```python= 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') ``` <!-- .element class="expand-code" --> Note: https://discordpy.readthedocs.io/en/stable/quickstart.html ---- ## 成功! ![](https://i.imgur.com/BXOB5Kq.png) ---- ## 補充解釋:format 語法 ```python name = 'Sean' time = '14:30' ``` ```python # 基本用法 print('Hey ' + name + ', it\'s ' + time + ' now.') # 格式化文字 print(f'Hey {name}, it\'s {time} now.') ``` ```python # 用 'string'.format(...) 處理格式化 print('Hey {}, it\'s {} now.'.format(name, time)) # 如果想指定變數順序呢? print('{1}: Hey {0}, how are you?'.format(name, time)) ``` ```python # 讓我們再看一次前面的例子 print('We have logged in as {0.user}'.format(client)) ``` --- # Discord 設定 ![](https://i.imgur.com/XnpDxaJ.png) ---- ## 啟用開發者模式 ![](https://i.imgur.com/jOLQDy4.png) ---- ## 複製伺服器 ID ![](https://i.imgur.com/h4vWzH9.png) ---- ## 複製頻道 ID ![](https://i.imgur.com/ZbDgV9E.png) ---- ## Discord 小技巧 ![](https://i.imgur.com/gl7HI3b.png) --- ## dotenv - 還記得上個月教的 git 版本控制嗎? - 要分享程式碼時怎麼辦 - 如果把 Token 寫死,交作業時不方便 ---- ## 安裝 dotenv ```shell pip3 install python-dotenv ``` <br> ### 使用方式 ```python from os import getenv from dotenv import load_dotenv load_dotenv() TOKEN = getenv('TOKEN') ``` ---- ## 完整程式碼 ```python= 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 ---- ## 玩遊戲 ```python if message.content.startswith('$play'): await client.change_presence( status=discord.Status.dnd, activity=discord.Game(name="資訊之芽")) await message.channel.send('I like playing!') ``` ---- ## 看影片 ```python 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 正在比 <!-- .element class="closer-list" --> 請參考 [ActivityType](https://discord.com/developers/docs/game-sdk/activities#data-models-activitytype-enum) --- # Thanks 投影片連結:https://hackmd.io/@Sean64/dc-bot <!-- .element: class="r-fit-text" --> <br> [![CC-BY 4.0][CC-BY-img]][CC-BY-link] ###### 這份投影片以 [創用 CC - 姓名標示][CC-BY-link] 授權公眾使用,原始碼及講稿請見 [此連結](https://hackmd.io/@Sean64/dc-bot/edit)。 [CC-BY-img]: https://mirrors.creativecommons.org/presskit/buttons/88x31/png/by.png [CC-BY-link]: https://creativecommons.org/licenses/by/4.0/deed.zh_TW ---- ## 休息時間 下一堂課內容: - Decorator、繼承、sync/async 等語法介紹 - 自己寫實用小遊戲 - 大作業講解 <style> .present ul:not(.closer-list) li { margin-top: 36px; } .present ul li ul li { margin-top: 4px; } .markdown-body img { max-width: 500px; } .reveal pre.expand-code code { max-height: 800px; } </style>

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully