欢迎与简单的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))

<<:  定时器爬虫练习

>>:  Day13:[解题技巧]Two pointers -  双指针

Day 12 Hooks 们以及作用域的差别!

该文章同步发布於:我的部落格 After Hooks 之前有介绍过 before hooks 的使...

Snapshot API测试

接下来照着永丰提供的github, 下一个要使用到的是快照-Snapshot的部分, 简单来说就是当...

权威认证(Authoritative accreditation)

-NIST SDLC 和 RMF -认证和认可 (C&A) -授权决定 认证(Certif...

iOS APP 开发 OC 第十四天,打包签名,你真的懂吗? 阅读笔记

iOS APP 开发 OC 第十四天,签证 tags: OC 30 day 资料来源:iOS 打包签...

Day 6 网路宝石:AWS VPC 架构 Routes & Security (下)

NACL vs SG 的安全设定介绍 当请求想进出在 Private Subnet 内的 EC2 ...