简体   繁体   中英

Writing a Discord Bot using Discord.py Rewrite

So currently I have a discord Bot, and I want to make it welcome any new users in #joining and give them the nickname "[0] Member Name". I'm not getting any errors but neither of these functions are working!

EDIT: Re-Wrote Some Code and I'm Now Getting This Error:

EDIT 2: Still Unable to Edit Nicknames, but when a User Leaves the Server I get these errors from the Function to check if the User is a Staff Member. I don't get errors from the message.author, but when the message author leaves, I start getting this error. I tried resetting the message.author when anyone leaves the server but this didn't help! I don't have any ideas on how to stop these errors!

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\Evan\Anaconda3\envs\testing\lib\site-packages\discord\client.py", line 270, in _run_event
    await coro(*args, **kwargs)
  File "C:/Users/Evan/PycharmProjects/Bot/bot.py", line 107, in on_message
    top_role = message.author.top_role
AttributeError: 'User' object has no attribute 'top_role'

My New Edited Code vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv

import discord
import asyncio
import time

# id = 630529690792230923
messages = joined = 0

client = discord.Client()


@client.event
async def on_ready():
    print(f'Logged in as: {client.user.name}')
    print(f"User ID: {client.user.id}")
    print('-----')


async def update_stats():
    await client.wait_until_ready()
    global messages, joined

    while not client.is_closed():
        try:
            with open("stats.txt", "a") as f:
                f.write(f"Time: {int(time.time())}, Messages: {messages}, Members Joined: {joined}\n"),
            messages = 0
            joined - 0

            await asyncio.sleep(3600)
        except Exception as e:
            print(e)
            await asyncio.sleep(3600)


@client.event
async def on_raw_reaction_add(payload):
    message_id = payload.message_id
    if message_id == 638155786559684608:
        guild_id = payload.guild_id
        guild = discord.utils.find(lambda g: g.id == guild_id, client.guilds)

        if payload.emoji.name == 'Test':
            role = discord.utils.get(guild.roles, name='new role')
        else:
            role = discord.utils.get(guild.roles, name=payload.emoji.name)

        if role is not None:
            member = discord.utils.find(lambda m: m.id == payload.user_id, guild.members)
            if member is not None:
                await member.add_roles(role)
                print("done")
            else:
                print("Member Not Found")


@client.event
async def on_raw_reaction_remove(payload):
    message_id = payload.message_id
    if message_id == 638155786559684608:
        guild_id = payload.guild_id
        guild = discord.utils.find(lambda g: g.id == guild_id, client.guilds)

        if payload.emoji.name == 'Test':
            role = discord.utils.get(guild.roles, name='new role')
        else:
            role = discord.utils.get(guild.roles, name=payload.emoji.name)

        if role is not None:
            member = discord.utils.find(lambda m: m.id == payload.user_id, guild.members)
            if member is not None:
                await member.remove_roles(role)
                print("done")


@client.event
async def on_member_join(member):
    global joined
    joined += 1
    rule_channel = member.guild.get_channel(channel_id=630530486858547223)
    newusermessage = f"""Welcome to CB:NL {member.mention}! Have a Great Time And Make Sure to Look At {rule_channel}"""
    channel = member.guild.get_channel(channel_id=630563931412496434)

    role = member.guild.get_role(role_id=630533613947060244)
    if member is not None:
        await member.add_roles(role)
        print("done")

    await member.edit(str([f"[0] {member.display_name}"]))

    await channel.send(newusermessage)


@client.event
async def on_member_remove(member):
    discord.message.author = member


@client.event
async def on_message(message):
    global messages
    messages += 1
    id = client.get_guild(630529690792230923)
    bad_words = ["test"]
    channels = ["bot-commands", "staff-general"]
    pn = 1
    author = message.author
    top_role = message.author.top_role
    staff_role = message.author.guild.get_role(role_id=630532857655328768)

    if top_role > staff_role:

        if message.content.startswith == "-clean":
            pass

        if str(message.channel) in channels:
            if message.content.find("-hello") != -1:
                await message.channel.send("Hi")

            elif message.content == "-status":
                await message.channel.send(f"""# of Members: {id.member_count}""")

    else:
        if message.author.bot is not 1:
            print(f"""{message.author} tried to do command {message.content}""")
            await message.channel.send(f"Error, {message.author.mention}. You Cannot Do That!")


client.loop.create_task(update_stats())

I'll respond in answer, because there are multiple mistakes in your code and it's hard to put into the comment. You can comment under this post if you get another error.


role = discord.utils.get(discord.Guild.roles, name="Member")

The error is where you retrieve the role by name Member. It's better to get the role by ID, you can do that using member.guild.get_role(630533613947060244) . The error is that discord.Guild.roles is not an iterable property.


nick = discord.utils.get(str(member.nick))

Not sure what is your intention there, you can use nick = member.nick to get a string with member's nickname.


To edit the nickname you should use:

await member.edit(nick=f"[0] {member.display_name}")

AttributeError: 'User' object has no attribute 'top_role'

You get this error because you want to access top_role attribute on instance of discord.User , but only discord.Member has this attribute defined. When someone leaves the server you get the User instance instead of the Member instance.

if isinstance(message.author, discord.Member):
  top_role = message.author.top_role
else:
  top_role = None   # top role not available, user has no roles

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM