Search code examples
pythondiscord.pyopenai-api

How do i get discord username outside of command?


So, i have this code it's basically chatgpt bot, yuh. I need to have discord username at the end of system message, but i dont really know where should i put it. Because, typing something like {message.author.name} outside of async def wont work, i guess?



def get_messages(sender, recipient, message):

    sender = sender.lower()

    sender_role = "assistant" if sender == "assistant" else "user"

    role = recipient.lower() if sender == "assistant" else sender

    user = get_user(role)

    personality = user['personality'] if user else config["global_personality"]

    bot_context=config["system_context"]

    system_role={"role": "system", "content": f"{bot_context}"}

    

    prefix=f'Имя человека, который с тобой общается - {message.author.name}' if sender_role == 'assistant' else f"{personality}"

    add_message({"role": sender_role, "content": f"{prefix}, {message}"})

    return [

      system_role,

      *[{"role": obj['role'], "content": obj['content']} for obj in history]

    ]

async def generate_response(message):

    try:

        if message.author == bot.user:

            return

        def call_openai_api():

            logger.info('Звоню на Апишник')

            return openai.ChatCompletion.create(

                model=config["model"],

                messages=get_messages('assistant', message.author.name, message.content),

temperature = 0.7

            )

        await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="a " + message.author.name))

        async with message.channel.typing():

            logger.info(message.author.name + ": " + message.content)

            response = await bot.loop.run_in_executor(None, call_openai_api)

            content = response['choices'][0]['message']['content']

            await message.reply(content)

            get_messages('assistant', message.author.name, content)

            logger.info("Assistant: " + content)

            logger.info("Токены: " + str(response["usage"]["total_tokens"]))

        await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=config["presence"]))

    except Exception as e:

        message.reply(config["error_message"])

        await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=config["presence"]))

        logging.error(f"Ошибка генерации: {e}", exc_info=True)

I tried putting it outside fo the async def, but that doesn't work. I just need discord username ath the end lf the system prompt


Solution

  • import discord
    
    class MyClient(discord.Client):
        async def on_message(self, message):
            if message.author == self.user:
                return
    
            if message.content.startswith('$hello'):
                await message.channel.send('Hello World!')
    

    {message.author.name}

    https://discordpy.readthedocs.io/en/stable/ext/commands/api.html?highlight=bot%20event#discord.ext.commands.Bot.event