[回顧上次內容](https://hackmd.io/@FWvDZu_3RYGpXa4M4SFqeg/H1hduUpEj) # Discord Bot-part3 一些常見功能(更長時間運行/發送圖片/嵌入訊息) ## 前提 如果想要新增功能,只要在這加`elif`即可。 ```python @bot.event async def on_message(message): if message.author == bot.user: return if message.content == '嗨': await message.channel.send('你好呀') elif message.content == '指令名稱': # 你要做的事 ``` ## 正題 ### 機器人活更久!? 先幫我下載[這個檔案](https://drive.google.com/file/d/1Cj4Iz1ha_dxHWyvwtJHuisLfT5gIkTX8/view?usp=share_link) 放在Files下  新增一行`import keep_alive`在最前面 接著加一行`keep_alive.keep_alive()`在run之前,如下圖  ### 傳送圖片 首先要先宣告一個 discord 模組中的 file 物件 \ 其中 pic 是自己命名的變數,File中參數後面是路徑 ```python pic = discord.File('/home/runner/Bot0/pic/test.jpg') # replit # '/home/runner/Bot0/pic/TK888.jpg' # '/home/runner/名稱/資料夾(可能無)/圖檔' await message.author.send(file=pic) ``` 新增指令範例 ```python @bot.event async def on_message(message): if message.author == bot.user: return if message.content == '嗨': await message.channel.send('你好呀') #-----------------新增內容----------------- elif message.content == '圖片': pic = discord.File('/home/runner/Bot0/pic/test.jpg') await message.channel.send(file=pic) #---------------------------------------- ``` 資料夾中檔案變list ```python import os os.listdir("/home/runner/Bot0/pic") # 上面是一個list 路徑:/home/runner/名稱/資料夾 ``` 結合 random ```python file_path = random.choice(os.listdir("/home/runner/Bot0/pic")) pic = discord.File(file_path) await message.channel.send(file=pic) ``` [官方api](https://discordpy.readthedocs.io/en/stable/api.html?#file) ### 嵌入訊息 長這樣  ```python embed = discord.Embed(color=0xadebff) embed.set_image(url=url) message = await message.channel.send(embed=embed) ``` [超實用的小工具](https://cog-creators.github.io/discord-embed-sandbox/) 最下面連結是標題的超連結  邊邊的顏色,調色超方便  第一個是縮圖,像上面那樣 再來是作者說明,最下面連結是點作者名的超連結  項目與內容,可以多個項目,按add field即可。 inline 點下去就是同一行,否則換行  大概長醬  最下面就會給你程式碼囉  [官方api](https://discordpy.readthedocs.io/en/stable/api.html?#embed) #### 圖片網址 [Imgur網站](https://imgur.com/) \ 因為網站不再提供圖床功能,[改用此工具](https://www.ifreesite.com/upload/) - 2024/12/28 更 讓你把圖片便網址的好東西  ###### tags: `Python` `DiscordBot`
×
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