pythonfunctiondiscorddiscord.pyreplit

discord.py simplify code with function doesn´t work


I´m programming a discord bot, that allows admins to change the server nicknames of the other members. If the bot doesn´t have the permission to change the name (e.g. the onces from admins) it dms it to you. If this isn´t possible it sends a message in the same textchannel the admin wrote the change-nickname-command. It worked perfektly but now i want to simplify my code and put the thing in a function, but this doesn´t work.

async def dm(user_id, dm_content, server_content, channel):
    user = await bot.fetch_user(user_id)
    try:
        await user.send(dm_content)
    except discord.Forbidden:
        await channel.send(server_content)
    return


async def on_message(msg):
***something else (e.g. the if statement for the permission check)***
await dm(msg.author.id, "I dont´t have the permission to change this nickname!", "I dont´t have the permission to change this nickname! (I wasn´t able to dm you, please check your privacysettings)", msg.channel)

Error message: 'msg' is not defined how do i define msg or how do i get the function to work? thanks


Solution

  • Your function looks correct to me. Just make sure to use the actual arguments for the event or use proper definitions.

    The following code should get rid of the 'msg' is not defined error:

    @bot.event()
    async def on_message(msg: discord.Message):
    

    Make sure to always define the arguments used to avoid any possible errors.