프로필사진

Go, Vantage point

가까운 곳을 걷지 않고 서는 먼 곳을 갈 수 없다.


Github | https://github.com/overnew/

Blog | https://everenew.tistory.com/





티스토리 뷰

반응형

 

 

 

일단 봇은 생성되어 있는 상태로 가정하고 기술하겠다.

 

 

 

 

1. 1:1 Channel 생성

 

슬랙에서는 1대 1 대화인 DM도 하나의 채널로 간주된다.

따라서 봇이 유저와 채널을 생성해서 메시지를 post 해야 한다.

 

 

이를 위해 conversations_open() 함수를 사용해 주자.

app.client.conversations_open("Either channel or users must be provided")

https://api.slack.com/methods/conversations.open#markdown

 

conversations.open API method

Opens or resumes a direct message or multi-person direct message.

api.slack.com

 

 

이 함수를 사용하기 위해서는 채널을 열 대상을 선택하기 위해 users 파라미터를 넘겨주어야 한다.

 

 

특정 user를 타깃 하기 위해서  봇이 있는 채널에 "갠톡줘"라고 보낸 유저의 id를 message 데이터에서 꺼내주자.

 

@app.message(re.compile("갠톡줘"))
def dm(message):
    print(message['user'])
    
    conversations_response = app.client.conversations_open(users=message['user'])
    channel_id = conversations_response['channel']['id']

 

 

 

정상적인 반환값은 아래와 같지만 봇이 채널을 생성하는 등의 권한이 없다면 에러 메시지가 출력된다.

 

정상 반환값

 

권한이 없다면 친절하게 어떤 것이 더 필요한지 needed로 안내해 준다.

The server responded with: {'ok': False, 'error': 'missing_scope',
'needed': 'channels:write,groups:write,mpim:writ e,im:write',
'provided': 'app_mentions:read,calls:write,channels:history,channels:read,chat:write,groups:history,im:history,im:read,mpim:history,workflow.steps:execute,channels:join'}) Traceback (most recent call last):

 

 

 

Slack App의 OAuth & Permissions로 이동하여 필요한 권한들을 몽땅 추가해 주자.

 

 

이제 새로 생성된 Channel_id 반환값이 오게 된다.

(이미 채널이 열린 유저라며 이미 열려있는 채널의 id를 반환해 준다.)

 

 

 

 

 

 

 

2. 채널에 Message 보내기

 

 

Channel_id를 알고 있다면 chat.postMessage() 함수를 통해서 바로 보내줄 수 있다.

 

 

https://api.slack.com/methods/chat.postMessage/code

 

chat.postMessage API method

Sends a message to a channel.

api.slack.com

 

 

channel_id = "구한 channel_id"

result = client.chat_postMessage(
     channel=channel_id, 
     text="Hello world"
)

 

 

 

 

 

 

전체 코드

 

 

 

 

 

반응형
댓글
반응형
인기글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함