科学の箱

科学・IT・登山の話題

Python

Python + Slack Bot – 3

投稿日:2018年9月7日 更新日:

さてリアルタイムでとりあえずうまくいったので、もう少し違うサンプルコードを試してみる。

参考にしたのはこちら。

https://www.fullstackpython.com/blog/build-first-slack-bot-python.html

ただしこのコードが書かれた当時とSlackのレスポンスが変わっているようなのでそのままでは動かない。

下記は変更後。これによりdoを入力すると別のレスポンスが返ってくるようになった。


import os
import time
import re
from slackclient import SlackClient
# instantiate Slack client
slack_client = SlackClient("xoxp-")
# starterbot's user ID in Slack: value is assigned after the bot starts up
starterbot_id = None

# constants
RTM_READ_DELAY = 1 # 1 second delay between reading from RTM
EXAMPLE_COMMAND = "do"
MENTION_REGEX = "^<@(|[WU].+?)>(.*)"

def parse_bot_commands(slack_events):

  print(slack_events)
  for event in slack_events:
    if event["type"] == "message" and not "subtype" in event:
      message = event["text"]
      user_id = event["user"]
      print(user_id + ":" + starterbot_id)
    if user_id == starterbot_id:
      return message, event["channel"]
  return None, None

def handle_command(command, channel):

  # Default response is help text for the user
  default_response = "Not sure what you mean. Try *{}*.".format(EXAMPLE_COMMAND)

  # Finds and executes the given command, filling in response
  response = None

  # This is where you start to implement more commands!
  if command.startswith(EXAMPLE_COMMAND):
    response = "Sure...write some more code then I can do that!"

  # Sends the response back to the channel
  slack_client.api_call(
    "chat.postMessage",
    channel=channel,
    text=response or default_response
  )

if __name__ == "__main__":
  if slack_client.rtm_connect(with_team_state=False):
    print("Starter Bot connected and running!")
    # Read bot's user ID by calling Web API method `auth.test`
    starterbot_id = slack_client.api_call("auth.test")["user_id"]
    while True:
      command, channel = parse_bot_commands(slack_client.rtm_read())
      if command:
        handle_command(command, channel)
      time.sleep(RTM_READ_DELAY)
  else:
    print("Connection failed. Exception traceback printed above.")

 

 

メタ情報

inarticle



メタ情報

inarticle



-Python
-

執筆者:


comment

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

関連記事

no image

pythonでTensorFlowを使うまで

TensorFlowが利用できるまでの設定手順をまとめる。 まず基本となるインストラクションはこちらにある。 https://www.tensorflow.org/install/pip このインスト …

no image

automated the boring – day5

さて、ここまででフロー、文字列、型、ファイル等を扱い、基礎プログラミングとしては一段落できた。 今日からは後半戦にはいり、開発をするうえで実践で必要になる技術を学んでいく。 まずはデバッグからである。 …

no image

配列のインデックス

インデックスとは配列に対して[]で要素を抜き出す方法である。 マニュアルは以下になる。 Indexing Indexing Routines インデックスの方法としては以下がある。 整数値を使ったイン …

no image

タイタニックデータでEDA-2

前回は、タイタニックデータについてはビジュアライズしてデータについて理解を深めた。 今回はデータをいじって機械学習に使えるようにする。 機械学習をするために必要な処理は3つある。 null値の置換 余 …

no image

Pythonまとめ

環境設定 環境設定 基本 Hello Worldを実行 数字、計算、文字列を画面出力   文字列 Pythonで文字列を生成するときの方法についてまとめる 制御フロー if ループ イテレー …

2018年9月
« 6月   10月 »
 12
3456789
10111213141516
17181920212223
24252627282930

side bar top



アーカイブ

カテゴリー