Develop slack bot in python using chat.postMessage

In the previous article, I created a bot that returns a specific string to a mention. https://qiita.com/tokoroten_346/items/0aa9c04d5d3f2a956cd2

This time, we will give the bot a little more functionality.

The structure of the file looks like this like last time

hello
 ├ hello.py              #File to launch the bot
 ├ slackbot_settings.py  #File to write bot settings(slack token etc.)。
 └─plugins
   └┬ __init__.py          #It seems that the sky is okay ...
    └ bot_module.py        #This time I will describe it here and add the functions of the bot

Immediately describe it in bot_module.py and add the bot's response. First, create the following functions. · Responses to specific words in mentions (using respond_to) · Responses to specific words in the channel (using listen_to)

The code looks like this

bot_module.py


from slackbot.bot import respond_to
from slackbot.bot import listen_to

# respond_to responds when mentioning
@respond_to('Hello')
def mention_function(message):
    #Return a response to slack
    message.reply('World')

# listen_to responds to words in the channel
@listen_to('Good morning')
def lesten_function(message):
    #Return a response to slack
   message.reply('Japanese Gowakarimasen')

Respond to mention with @respond_to. @listen_to describes the response to the channel.

Other codes are the same as last time

hello.py


from slackbot.bot import Bot

def main():
    bot = Bot()
    bot.run()

if __name__ == "__main__":
    print("Hello bot")
    main()

slackbot_settings.py


#Specify the token of the bot account you got earlier
API_TOKEN = "xxxx-xxxxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxxxxxxx"

#Write the default response for this bot
DEFAULT_REPLY = "Good morning"

#List of subdirectory names where plugin scripts are located
PLUGINS = ['plugins']

When you run this bot, it will look like this: botの返事追加.png

"World" is returned for "Hello" mentions, "Nihongowakarimasen" is returned for "Good morning" in the channel, and "No reply ..." is returned for unregistered mentions. By the way, if the mention and the post in the channel are reversed, it will not respond well. botの返事エラー例.png

Now that we can reply with listen_to and respond_to, we will use the api of chat.postMessage next. https://api.slack.com/methods/chat.postMessage

Change bot_module.py as follows.

bot_module.py


from slackbot.bot import respond_to
from slackbot.bot import listen_to
import json
import requests

# respond_to responds when mentioning
@respond_to('Hello')
def mention_function(message):
    post_url = 'https://slack.com/api/chat.postMessage'
    token = 'xxxx-xxxxxxxxx…'  #Describe Bot User OAuth Access Token
    channel = 'xxxxxxx'        #The string at the end of the channel URL
    username = 'Greeting bot'       #bot name
    icon_emoji = ':ghost:'     #Display icon(This time I will make it a ghost)
    text       =  'Good morning ~'    #Return a response to slack

    #Described in json format
    attachments = [{
        'text': text,
    }]

    payload = {
        'token': token,
        'channel': channel,
        'username': username,
        'icon_emoji': icon_emoji,
        'attachments': json.dumps(attachments)
    }

    res = requests.post(post_url, data=payload)
    print (res.status_code)

# listen_to responds to words in the channel
@listen_to('Good morning')
def lesten_function(message):
    #Return a response to slack
   message.reply('Japanese Gowakarimasen')

Do this and send Hello and mention to slacktest ゴースト.png

The icon is a ghost greeting bot and you will return good morning. By using chat.postMessage, you can change the icon and write in json.

Recommended Posts

Develop slack bot in python using chat.postMessage
Log in to Slack using requests in Python
Create a data collection bot in Python using Selenium
Implement Slack chatbot in Python
How to develop in Python
Translate using googletrans in Python
Using Python mode in Processing
Post to Slack in Python
Asynchronous processing using LINE BOT: RQ (Redis Queue) in Python
GUI programming in Python using Appjar
Try using LevelDB in Python (plyvel)
Develop an investment algorithm in Python 2
Using global variables in python functions
Let's see using input in python
Infinite product in Python (using functools)
Edit videos in Python using MoviePy
Easy with Slack using Bot #NowPlaying
Handwriting recognition using KNN in Python
Try using Leap Motion in Python
Depth-first search using stack in Python
When using regular expressions in Python
GUI creation in python using tkinter 2
Mouse operation using Windows API in Python
Notes using cChardet and python3-chardet in Python 3.3.1.
GUI creation in python using tkinter part 1
(Bad) practice of using this in Python
Try using the Kraken API in Python
Using venv in Windows + Docker environment [Python]
[FX] Hit oanda-API in Python using Docker
Tweet using the Twitter API in Python
[Python] [Windows] Serial communication in Python using DLL
I tried using Bayesian Optimization in Python
Using physical constants in Python scipy.constants ~ constants e ~
Write python modules in fortran using f2py
Draw a tree in Python 3 using graphviz
Notes for using python (pydev) in eclipse
Disease classification in Random Forest using Python
Download files in any format using Python
Parallel task execution using concurrent.futures in Python
Notes on using code formatter in Python
Meaning of using DI framework in Python
Tweet in Chama Slack Bot ~ How to make a Slack Bot using AWS Lambda ~
Quadtree in Python --2
Python in optimization
CURL in python
Geocoding in python
SendKeys in Python
Create a GIF file using Pillow in Python
Meta-analysis in Python
Email attachments using your gmail account in python.
Unittest in python
Develop and deploy Python APIs using Kubernetes and Docker
Try using the BitFlyer Ligntning API in Python
Epoch in Python
Discord in Python
Get image URL using Flickr API in Python
Start using Python
Sudoku in Python
DCI in Python
Notes on using dict in python [Competition Pro]
quicksort in python