【问题标题】:I've been developing my reaction roles feature in discord.py, it's not working我一直在 discord.py 中开发我的反应角色功能,它不起作用
【发布时间】:2021-10-28 20:23:31
【问题描述】:

我昨天发了一篇关于这个的帖子,给我的代码不起作用,每次我尝试在没有 He/Him 角色的服务器上运行命令时,它都会给我一条错误消息说我缺少权限

@bot.command(name='rolecreate', help='creates all the default roles')
@has_permissions(manage_messages=True, manage_roles=True)
async def rolecreate(ctx):
  Text= "React with :heart: to get the He/Him role!"
  Moji1 = await ctx.send(Text)
  reaction="❤️"
  await Moji1.add_reaction(reaction)
  @bot.listen() 
  async def on_reaction_add(reaction, member):
    if reaction.message.channel.id != 881380132789583892:
      return
    if reaction.emoji == "❤️":
                he_him = discord.utils.get(member.guild.roles, name="He/Him")     

    if not he_him:
      he_him = await member.guild.create_role(name="He/Him")

【问题讨论】:

  • 机器人是否有管理角色权限?没有它,您将无法创建角色
  • @Scuffedsimon 它的发生是由于 LeSauvage 所说的。在您的服务器设置中,将机器人角色放在您希望在用户做出反应时授予用户的角色之上,然后通过单击其角色授予机器人管理角色权限
  • 它在代码的顶部,第二行
  • @ChaoticNebula 该角色在服务器上不存在,并且每当我尝试使用它时,它都会给我一个缺少权限的错误,尽管机器人具有完整的管理员权限
  • 在 discord 开发者门户中,您是否在 OAuth2 设置中选择了“bot”范围,是否给了它必要的权限?如果不是这样,我建议在完成此操作后重新邀请机器人。

标签: python discord discord.py bots roles


【解决方案1】:

你好,这是我的反应角色,它工作得很好确保制作 json 文件和东西

import discord
from discord.ext import commands
import json
import atexit
import uuid
import datetime

x = datetime.datetime.now()

reaction_roles_data = {}

try:
    with open("reaction_roles.json") as file:
        reaction_roles_data = json.load(file)
except (FileNotFoundError, json.JSONDecodeError) as ex:
    with open("reaction_roles.json", "w") as file:
        json.dump({}, file)


@atexit.register
def store_reaction_roles():
    with open("reaction_roles.json", "w") as file:
        json.dump(reaction_roles_data, file)


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

    @commands.Cog.listener()
    async def on_ready(self):
        print(f"ReactionRoles ready.")

    @commands.Cog.listener()
    async def on_raw_reaction_add(self, payload: discord.RawReactionActionEvent):
        role, user = self.parse_reaction_payload(payload)
        if role is not None and user is not None:
            await user.add_roles(role, reason="ReactionRole")

    @commands.Cog.listener()
    async def on_raw_reaction_remove(self, payload: discord.RawReactionActionEvent):
        role, user = self.parse_reaction_payload(payload)
        if role is not None and user is not None:
            await user.remove_roles(role, reason="ReactionRole")

    @commands.has_permissions(manage_channels=True)
    @commands.cooldown(1, 5, BucketType.user)
    @commands.command()
    async def reaction(
        self,
        ctx,
        emote,
        role: discord.Role,
        channel: discord.TextChannel,
        title,
        message,
    ):
        commandd = "reaction"
        print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
        print(x)
        print(" ")
        embed = discord.Embed(title=title, description=message)
        msg = await channel.send(embed=embed)
        await msg.add_reaction(emote)
        self.add_reaction(ctx.guild.id, emote, role.id, channel.id, msg.id)

    @commands.has_permissions(manage_channels=True)
    @commands.cooldown(1, 5, BucketType.user)
    @commands.command()
    async def reaction_add(
        self, ctx, emote, role: discord.Role, channel: discord.TextChannel, message_id
    ):
        commandd = "reaction_add"
        print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
        print(x)
        print(" ")
        self.add_reaction(ctx.guild.id, emote, role.id, channel.id, message_id)
        await ctx.send('Please enter the command like this: .reaction add (emote)  (role (ping or id))  (channel (ping or id))  "(message title)" “(message)”')
    @commands.has_permissions(manage_channels=True)
    @commands.cooldown(1, 5, BucketType.user)
    @commands.command()
    async def reactions(self, ctx):
        commandd = "reactions"
        print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
        print(x)
        print(" ")
        guild_id = ctx.guild.id
        data = reaction_roles_data.get(str(guild_id), None)
        embed = discord.Embed(title="Reaction Roles")
        if data is None:
            embed.description = "There are no reaction roles set up right now."
        else:
            for index, rr in enumerate(data):
                emote = rr.get("emote")
                role_id = rr.get("roleID")
                role = ctx.guild.get_role(role_id)
                channel_id = rr.get("channelID")
                message_id = rr.get("messageID")
                embed.add_field(
                    name=index,
                    value=f"{emote} - @{role} - [message](https://www.discordapp.com/channels/{guild_id}/{channel_id}/{message_id})",
                    inline=False,
                )
        await ctx.send(embed=embed)

    @commands.has_permissions(manage_channels=True)
    @commands.cooldown(1, 5, BucketType.user)
    @commands.command()
    async def reaction_remove(self, ctx, index: int):
        commandd = "reaction_remove"
        print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
        print(x)
        print(" ")
        guild_id = ctx.guild.id
        data = reaction_roles_data.get(str(guild_id), None)
        embed = discord.Embed(title=f"Remove Reaction Role {index}")
        rr = None
        if data is None:
            embed.description = "Given Reaction Role was not found."
        else:
            embed.description = (
                "Do you wish to remove the reaction role below? Please react with ?️."
            )
            rr = data[index]
            emote = rr.get("emote")
            role_id = rr.get("roleID")
            role = ctx.guild.get_role(role_id)
            channel_id = rr.get("channelID")
            message_id = rr.get("messageID")
            _id = rr.get("id")
            embed.set_footer(text=_id)
            embed.add_field(
                name=index,
                value=f"{emote} - @{role} - [message](https://www.discordapp.com/channels/{guild_id}/{channel_id}/{message_id})",
                inline=False,
            )
        msg = await ctx.send(embed=embed)
        if rr is not None:
            await msg.add_reaction("?️")

            def check(reaction, user):
                return (
                    reaction.message.id == msg.id
                    and user == ctx.message.author
                    and str(reaction.emoji) == "?️"
                )

            reaction, user = await self.bot.wait_for("reaction_add", check=check)
            data.remove(rr)
            await ctx.send("removed reaction")
            reaction_roles_data[str(guild_id)] = data
            store_reaction_roles()

    def add_reaction(self, guild_id, emote, role_id, channel_id, message_id):
        if not str(guild_id) in reaction_roles_data and not message.author.bot:
            reaction_roles_data[str(guild_id)] = []
        reaction_roles_data[str(guild_id)].append(
            {
                "id": str(uuid.uuid4()),
                "emote": emote,
                "roleID": role_id,
                "channelID": channel_id,
                "messageID": message_id,
            }
        )
        store_reaction_roles()

    def parse_reaction_payload(self, payload: discord.RawReactionActionEvent):
        guild_id = payload.guild_id
        data = reaction_roles_data.get(str(guild_id), None)
        if data is not None:
            for rr in data:
                emote = rr.get("emote")
                if payload.message_id == rr.get("messageID"):
                    if payload.channel_id == rr.get("channelID"):
                        if str(payload.emoji) == emote:
                            guild = self.bot.get_guild(guild_id)
                            role = guild.get_role(rr.get("roleID"))
                            user = guild.get_member(payload.user_id)
                            return role, user
        return None, None

def setup(bot):
    bot.add_cog(ReactionRoles(bot))

-来自愤怒机器人的首席开发人员

【讨论】:

  • 对不起,我迟到了,但是这个代码的 TYSM !我不知道如何在我的 IDE 中制作一个 json 文件(replit)
猜你喜欢
  • 2021-04-28
  • 2021-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-26
  • 1970-01-01
  • 2023-01-30
相关资源
最近更新 更多