달나라 노트

Python Discord : message 작성자 정보 불러오기, message author, discord 사람 태그하기 (Python Discord API) 본문

Python/Python ETC

Python Discord : message 작성자 정보 불러오기, message author, discord 사람 태그하기 (Python Discord API)

CosmosProject 2022. 2. 21. 23:10
728x90
반응형

 

 

 

Python discord API를 사용할 때 어떤 메세지의 작성자를 불러오는 방법이 있습니다.

 

 

 

 

 

먼저 discord.ext.commands를 사용하는 경우입니다.

from discord.ext import commands

discord_token = 'token_string'


client = commands.Bot(command_prefix='/')


@client.event
async def on_ready():
    print('{} logged in.'.format(client))
    print('Bot: {}'.format(client.user))
    print('Bot name: {}'.format(client.user.name))
    print('Bot ID: {}'.format(client.user.id))


@client.command(name='작성자')
async def author_test(ctx):
    author = ctx.message.author
    author_id = ctx.message.author.id
    author_name = ctx.message.author.name
    message_contents = ctx.message.content

    str_result = '''
author = {author}
author ID = {author_id}
author name = {author_name}
message contents = {message_contents}
<@{author_id}>
    '''.format(author=author,
               author_id=author_id,
               author_name=author_name,
               message_contents=message_contents)

    await ctx.send(str_result)


client.run(discord_token)

명령어를 통해 /작성자 라는 명령어를 discord에 입력하면 그 명령어를 보낸 작성자 정보를 return해주는 discord bot code입니다.

 

 

 

 

async def author_test(ctx):
    author = ctx.message.author
    author_id = ctx.message.author.id
    author_name = ctx.message.author.name
    message_contents = ctx.message.content

가장 중요한건 이 부분입니다.

discord.ext.commands를 사용할 때 모든 코루틴 함수가 첫 번째 인자로 받는 ctx(context 객체)는 discord와 소통하기 위한 많은 정보를 포함하고있습니다.

그 중 하나가 바로 명령어를 입력한 작성자 정보입니다.

 

작성자는 ctx.message.author~~ 로 알 수 있습니다.

 

val_message_contents = ctx.message.content

그리고 참고용으로 이 부분도 써놨는데 ctx.message.content는 메세지의 내용을 담고있습니다.

제가 위 명령어를 호출할 때 /작성자 라는 명령어를 discord에 입력했으니 ctx.message.content/작성자 라는 텍스트를 그대로 담고있을겁니다.

 

 

 

 

각 값들에 대한 결과는 아래와 같습니다.

async def author_test(ctx):
    author = ctx.message.author            # test_id#5613
    author_id = ctx.message.author.id      # 68406436219813598413
    author_name = ctx.message.author.name  # test_id
    message_contents = ctx.message.content # /작성자

 

여기서 author.id는 discord API에서 사용자를 구분할 때 사용합니다.

따라서 이렇게 명령어를 입력한 작성자의 author.id를 알면 많은 것을 할 수 있습니다.

 

위 예시를 다시 봅시다.

 

 

 

 

 

from discord.ext import commands

discord_token = 'token_string'


client = commands.Bot(command_prefix='/')


@client.event
async def on_ready():
    print('{} logged in.'.format(client))
    print('Bot: {}'.format(client.user))
    print('Bot name: {}'.format(client.user.name))
    print('Bot ID: {}'.format(client.user.id))


@client.command(name='작성자')
async def author_test(ctx):
    author = ctx.message.author
    author_id = ctx.message.author.id
    author_name = ctx.message.author.name
    message_contents = ctx.message.content

    str_result = '''
author = {author}
author ID = {author_id}
author name = {author_name}
message contents = {message_contents}
<@{author_id}>
    '''.format(author=author,
               author_id=author_id,
               author_name=author_name,
               message_contents=message_contents)

    await ctx.send(str_result)


client.run(discord_token)

author_test 함수를 보면 ctx.message.author 로부터 작성자 정보를 불러낸 후,

그것을 str_result에 입력을 해서 그 결과를 discord에 보냅니다.

 

str_result를 보면 <@{author_id}> 라는 부분이 있습니다.

discord에서는 @를 입력한 후 채널에 있는 누군가의 id를 입력하면 태그가 되며 상대방에게 알림이 갑니다.

 

우리가 discord 채팅창에서 직접 사용할 때에는 그냥 @를 적은 후 상대방의 discord id를 적으면 태그 목록이 뜨면서 태그가 됩니다.

하지만 실제 이 태그는 <@author_id>의 형식으로 이뤄져있으며 예를들면 아래와 같습니다.

<@103765028374105>

 

따라서 명령어를 입력한 작성자 ID(ctx.message.author.id)를 얻어와서 그 작성자를 discord bot이 태그하여 알림을 주도록 할 수 있는 것이죠.

 

 

 

 

 

 

 

 

 

 

다음은 discord.ext.commands가 아니라 일반 discord 모듈을 사용하는 경우 author를 불러오는 예시입니다.

 

import discord


discord_token = 'token_string'


client = discord.Client()

@client.event
async def on_ready():
    print('{} logged in.'.format(client))
    print('Bot: {}'.format(client.user))
    print('Bot name: {}'.format(client.user.name))
    print('Bot ID: {}'.format(client.user.id))

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    elif message.content.startswith('hello'):
        author = message.author
        author_id = message.author.id
        author_name = message.author.name
        message_contents = message.content

        str_result = '''
author = {author}
author ID = {author_id}
author name = {author_name}
message contents = {message_contents}
<@{author_id}>
            '''.format(author=author,
                       author_id=author_id,
                       author_name=author_name,
                       message_contents=message_contents)

        await message.channel.send(str_result)

client.run(discord_token)

맥락은 처음에 봤던 예시와 거의 동일합니다.

 

 

 

 

 

 

728x90
반응형
Comments