LoginSignup
1
0

python-slack-sdkの`files_upload_v2`メソッドの`initial_comment`に、`<url|text>`形式の文字列を渡してもリンクにならない

Last updated at Posted at 2023-05-09

環境

  • Python 3.11.2
  • slack-sdk 3.20.1
  • 確認した日: 2023/05/09

やりたいこと

Slack APIを使って、テキストにリンクを付けたいです。

試したこと

以下の形式にすれば、リンクになるようです。

<http://www.example.com|This message *is* a link>

chat.postMessagefiles.upload APIで、メッセージがリンク形式になるかを確認しました。

chat.postMessage APIのtextフィールド

text:
The formatted text of the message to be published. If blocks are included, this will become the fallback text used in notifications.

In [155]: client=WebClient(os.environ["SLACK_TOKEN"])
In [157]: message=f"<https://qiita.com/|QIITA>"
In [158]: client.chat_postMessage(channel="CDKRW33RA", text=message)
Out[158]: <slack_sdk.web.slack_response.SlackResponse at 0x7f65c8a149d0>

image.png

テキストはリンクになりました。

files.upload APIのinitial_commentフィールド

In [171]: client.files_upload_v2(channel=channel_id, file="README.md", initial_comment=message)
Out[171]: <slack_sdk.web.slack_response.SlackResponse at 0x7f65c8d43250>

image.png

テキストはリンクにならず、そのままの文字列が表示されました。

client.files_upload_v2メソッドの中で何か変換処理をかけているかもしれないと思い、HTTPリクエストのログを確認しましたが、そのままの文字列を渡していました。

DEBUG    : 2023-05-09 01:09:25,805 : slack_sdk.web.base_client : Sending a request - url: https://www.slack.com/api/files.upload, query_params: {}, body_params: {'channel': 'CDKRW33RA', 'filename': 'empty.txt', 'initial_comment': '<https://qiita.com/|QIITA>'}, files: {'file': 'empty.txt'}, ...

files_uploadメソッドで試す

files_uploadメソッドならば、メッセージはリンクになります。
@seratch さんのコメントで教えてもらった回避策です。

In [184]: client.files_upload(channels=channel_id, file="empty.txt", initial_comment=message)
/home/vagrant/.pyenv/versions/3.11.2/lib/python3.11/site-packages/slack_sdk/web/internal_utils.py:450: UserWarning: client.files_upload() may cause some issues like timeouts for relatively large files. Our latest recommendation is to use client.files_upload_v2(), which is mostly compatible and much stabler, instead.
  warnings.warn(message)

引数はchannelでなくchannelsです。

分からないこと

ファイルをアップロード時に投稿するメッセージに、リンクを含める方法が分かりませんでした。
Slackアプリでは実現できるので、技術的には可能だと思うのですが。。。

@seratch さんに教えていただきました。
https://qiita.com/yuji38kwmt/items/67e386750f5950d86e4c#comment-3c22a3e7fc249b3a9b18

1
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0