iT邦幫忙

2021 iThome 鐵人賽

DAY 13
0
自我挑戰組

Discord-bot,從0開始到做出一個機器人系列 第 13

歡迎與簡單的command

Print HI@Someone

  • 接下來,我們開始寫一些可以用的指令吧~~
    好比說,打招呼之類的,而這時候就需要用到函式的概念,再者,這是已算是一種指令
@bot.command()
async def hello(ctx):
    await ctx.send(f"!Hi <@{ctx.author.id}>")
  • 實際效果如下

參數

  • ctx是一種引數,且ctx是context(上下文的縮寫)

  • author是本人,今天我在上頭打了hello,機器人便會回覆加上@自己* 接著來看一下 author.id

  • 因為我要@自己,所以是用author,當然,你也可以指定某人就是了(id: int)

  • async跟await同一家族的(當然還有asyncio......之類的)

刪除留言

  • 這裡是官方的解釋

  • 我們使用purge來刪除留言

@bot.command()
async def clear(ctx, num:int):
    await ctx.channel.purge(limit = num+1)
  • 所以在這邊的指令是!clear+數字
  • 這邊理所當然可以用delete,但是個人認為purge比較方便......

歡迎成員與退出的部分

  • 這邊就直接上程式碼了
  • idchannel的型態是int,請注意。
@bot.event
async def on_member_join(member):
   await self.bot.get_channel(idchannel).send(f"{ member.name } has joined")

@bot.event
async def on_member_remove(member):
   await self.bot.get_channel(idchannel).send(f"{ member.name } has left")
  • idchannel要從這邊找

處理一下目前的資料夾

  • 在資料夾裡建立cogs、core等資料夾
  • cogs資料夾放指令、core資料夾放重要的東西
  • 我們回到bot的主幹上
# 剛剛我們寫到能使用bot、第一個指令
# 還有添加了json

bot = commands.Bot(command_prefix = '!', 
                   owner_ids = data['owner_id'],
                   intents = discord.Intents.all())
  • 這邊的owner_id是你自己(創作者)的ID

  • 之後,我們引用os函式庫

import os

# 只要是python檔案就會進行載入
for file in os.listdir("cogs"):
    if file.endswith(".py"):
        name = file[:-3]
        bot.load_extension(f"cogs.{name}")
  • 回到core資料夾
# core/any.py
import discord
from discord.ext import commands

# 這邊可以使用Cog功能繼承基本屬性
class Cog_Extension(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
  • 現在可以回去撰寫hello的檔案囉
# cogs/hello.py

from discord.ext import commands
import discord
from discord.ext.commands import bot
from core.any import Cog_Extension

class Hello(Cog_Extension):
    
    @commands.command()
    async def hello(self, ctx):
        await ctx.send(f"!Hi <@{ctx.author.id}>")
  • 最後需要啟動
def setup(bot):
    bot.add_cog(Hello(bot))

上一篇
使用bot.py建立起你的第一個機器人
下一篇
發送圖片與添加元素
系列文
Discord-bot,從0開始到做出一個機器人30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言