xia的小窩

一起來coding和碼字吧

0%

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

使用Auttaja

點擊Dashboard

選擇Assignable & Giveable Roles

在聊天室輸入 -assignrole 海豹 (海豹是我這邊設置的身分組)

使用Atias

選擇roles

在下方可以自定義

示意圖

使用自定義的Bot

身分組的部分請自己是先設定

使用reaction來查看表情符號

1
2
3
4
5
# cogs/reaction.py
# 略
@commands.Cog.listener()
async def on_reaction_add(self, reaction, user):
print(reaction)
  • 結果示意圖

再來使用on_raw_reaction_add()

1
2
3
4
5
6
7
8
9
10
@commands.Cog.listener()
async def on_raw_reaction_add(self, user_data):
if user_data.message_id == 你指定的留言:
if str(user_data.emoji) == "指定的符號":
# 取得伺服器
guild = self.bot.get_guild(user_data.guild_id)
# 指定身分組
role = guild.get_role(身分組ID)
await user_data.member.add_roles(role)
await user_data.member.send(f"你取得了{role}身分組")

on_raw_reaction_remove()的部分

1
2
3
4
5
6
7
8
9
@commands.Cog.listener()
async def on_raw_reaction_remove(self, user_data):
if user_data.message_id == 你指定的留言:
if str(user_data.emoji) == '指定的符號':
# 取得伺服器
guild = self, bot.get_guild(user_data.guild_id)
user = await guild.fetch_member(user_data.user_id)
await user.remove_roles(guild.get_role(身分組ID))
await user.send(f"已移除{role}身分組"")

示意圖

可以到審核日誌查看

備註

因為只有on_raw_reaction_add()能使用member,所以刪除可以拿user_id代替

discord.py 2.0部分更改

嗯,這裡也有地方要更改,直接上程式碼吧,不然感覺也沒啥好說的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from discord.ext import commands, tasks
from datetime import datetime, timezone, timedelta
import asyncio
from pathlib import Path
import os
import discord
import pytz
import datetime

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

@commands.Cog.listener()
async def on_raw_reaction_add(self, payload: discord.RawReactionActionEvent):
# 添加身分組的message_id
role_message_id = # your message id
# print(payload.emoji.id)
if payload.message_id != role_message_id:
return
if str(payload.emoji) == '\U0001F914':
guild = await self.bot.fetch_guild(payload.guild_id)
member = await guild.fetch_member(payload.user_id)
role = guild.get_role(role 身分組的id)
await member.add_roles(role)
await member.send(f"獲得 【{role}】 身分組成功!", delete_after = 10)

@commands.Cog.listener()
async def on_raw_reaction_remove(self, payload: discord.RawReactionActionEvent):
# 添加身分組的message_id
role_message_id = # your message id
# print(payload.emoji.id)
if payload.message_id != role_message_id:
return
if str(payload.emoji) == '\U0001F914':
guild = await self.bot.fetch_guild(payload.guild_id)
member = await guild.fetch_member(payload.user_id)
role = guild.get_role(role 身分組的id)
await member.remove_roles(role)
await member.send(f"移除 【{role}】 身分組成功!", delete_after = 10)


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

其他正常的就不用改了,\U0001F914這個可以換成你server的貼圖,找到後按右鍵就可以複製圖id,