xia的小窩

一起來coding和碼字吧

0%

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

接下來,我們開始寫一些可以用的指令吧~~

好比說,打招呼之類的,而這時候就需要用到函式的概念,再者,這是已算是一種指令

1
2
3
@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來刪除留言

1
2
3
@bot.command()
async def clear(ctx, num:int):
await ctx.channel.purge(limit = num+1)

所以在這邊的指令是!clear+數字
這邊理所當然可以用delete,但是個人認為purge比較方便……

歡迎成員與退出的部分

這邊就直接上程式碼了
idchannel的型態是int,請注意。

1
2
3
4
5
6
7
@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的主幹上

1
2
3
4
5
6
# 剛剛我們寫到能使用bot、第一個指令
# 還有添加了json

bot = commands.Bot(command_prefix = '!',
owner_ids = data['owner_id'],
intents = discord.Intents.all())

這邊的owner_id是你自己(創作者)的ID

之後,我們引用os函式庫

1
2
3
4
5
6
7
import os

# 只要是python檔案就會進行載入
for file in os.listdir("cogs"):
if file.endswith(".py"):
name = file[:-3]
bot.load_extension(f"cogs.{name}")

回到core資料夾

1
2
3
4
5
6
7
8
# core/any.py
import discord
from discord.ext import commands

# 這邊可以使用Cog功能繼承基本屬性
class Cog_Extension(commands.Cog):
def __init__(self, bot):
self.bot = bot

現在可以回去撰寫hello的檔案囉

1
2
3
4
5
6
7
8
9
10
11
12
# 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}>")

最後需要啟動

1
2
def setup(bot):
bot.add_cog(Hello(bot))

2.0部分更改

cogs一樣是核心,不過我習慣是把@commands.command放在cmds這個資料夾。

這裡示範一個cmds/hello.py,這邊已經不用再引用Cog_Extension了,直接抓過來就可了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from discord.ext import commands
import discord

class hello(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot

@commands.command()
async def hello(self, ctx, to: discord.User = commands.parameter(
default = lambda ctx: ctx.author
)):
await ctx.send(f'Hello {to.mention} :wave:')

async def setup(bot: commands.Bot):
await bot.add_cog(hello(bot))

on_member_join這裡也有小改

1
2
3
4
5
6
7
8
9
10
11
12
13
@commands.Cog.listener()
async def on_member_join(self, member):
guild = member.guild
# 如果歡迎頻道有指定的話
if guild.system_channel is not None:
embed = discord.Embed(
title = f"歡迎!",
description = f"{member.mention}"
)
embed.set_image(
url = self.member.avatar_url
)
await guild.system_channel.send(embed = embed)