# discord bot 的修飾器 ## start coding 1. 需要引用的module ```python= from discord.ext import commands import discord ``` 2. 機器人的前置聲明 ```python= bot = commands.Bot(command_prefix = "!") #前面要有!才會被當作是要給bot看的 ``` 3. 啟動機器人 ```python= bot.run("你之前紀錄的token") ``` ## event 1. on_ready ```python= @bot.event async def on_ready(): print("Bot in ready") activity = discord.Game("努力獲取資訊中") await bot.change_presence(status = discord.Status.online, activity = activity) ``` * 在啟動機器人時,這個程式會被啟動 * 在第5行的程式碼中,能夠變更機器人顯示的狀態 ### discord.Status有以下的狀態 * dnd : 勿擾 * idle : 閒置 * offline : 下線 * online : 上線 * invisible : 不可見 2. on_message ```python= @bot.event async def on_message(message): if message.author == bot.user: #不要管bot的訊息,避免進入無限迴圈 return if message.author != bot.user: #重複使用者傳送的東西 await message.channel.send(message.content) ``` * 當有人傳送訊息時會啟動這個程式 ### 這邊只大概列出幾個功能,更詳細的可以查看[官網](https://discordpy.readthedocs.io/en/stable/api.html?highlight=event#event-reference) --- ## command 1. 基本用法 ```python= @bot.command() async def hello(message): await message.channel.send("hello") ``` * 當使用者輸入!hello時,bot會回傳hello 2. 回傳資料 ```python= @bot.command() async def test(message, arg): await message.channel.send(arg) ``` * 當使用者輸入!test {data}時,bot會回傳data的值 * arg會記錄使用者傳送的值 ### 這邊只大概列出幾個功能,更詳細的可以查看[官網](https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html) ###### tags: `discord` `discord bot`
×
Sign in
Email
Password
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