Python Slack Bot Tutorial #3 - Slash Commands

Tech With Tim · Beginner ·🧠 Large Language Models ·5y ago

Key Takeaways

This video tutorial demonstrates how to use slash commands in Slack using Python and the Slack API, covering the creation of slash commands, handling requests, and replying to users with meaningful messages. The tutorial utilizes tools such as Flask and ngrok for local development and API requests.

Full Transcript

[Music] hello everybody and welcome back to part three of the slack bot tutorial so in this video we're gonna be going over commands this one will be a little bit shorter than the previous one i apologize that one was about 20 minutes long but i did need to cover everything and this will show us how we can use like slash commands inside of slack and send that to a specific endpoint on our server that can handle that and do something with it now i want to make it very clear that commands are different than events so if we look actually at the slack api here or if we even just look at our slack thing right whenever we do something in the channel that's kind of an event right like if i react to this message so say i go here and i you know add a reaction or maybe i even edit this message right so maybe i mark it as unread or i pin it to the channel or edit it then is that is an example of an event now a command is something like this right if i go slash slash message or slash me or whatever these are commands so how can we add specific commands custom commands to our bot well what we can actually do is we can go here we can go to slash commands and we can create a new command now it's actually pretty straightforward what we do is we add the command that we want so in this case the first command that i'm going to show us is how we can get the amount of messages that a user has sent so i'm going to say message hyphen count is going to be this command now it's asking me for a request url the request url is what we're going to send the command to or send this event to whatever you want to call it when this command is called so this needs to be the same thing that we used for our events so if we look at our forwarding we see that we have this address right here so we're going to add that as the base of our url so we're going to put that like that and then we need to make some endpoint on our server that can handle this specific request so if i go back to my app here what i need to do is make a new route or make a new endpoint whatever you want to call it an endpoint is just like you know slash home or slash back or slash login those are all examples of endpoints that we can hit with this request so i'm going to say at app.root and this is the basic way that we add a new route or we add a new endpoint to our server so at app.root and i'm going to say slash and in this case what am i going to call it message hyphen count all right so there we go we're going to add that endpoint and we're going to say define message underscore account like that and then inside of here we're going to return a response and then 200. now i'll explain what this is in a second but go up to the top of our program and from flask what we need to do is we need to import request and we need to import response with a capital so if we go down here now what we're doing is returning response 200 all this is saying is okay i think we actually need brackets here my apologies we're going to return some empty response whenever we hit this endpoint and we're going to return the status code 200 which simply stands for okay now you may be familiar with the status code 404 you know endpoint not found or url not found this is just saying hey we're just going to tell whatever hits this that yep we're all good even though we haven't even really done anything inside of this function right so let's get out of this for one second and let's go back to the thing right here and now what we're going to do is add the endpoint message hyphen count so we're going to add that base url right which is what we use for the events and our callback and all that stuff and then we're going to say slash message hyphen count we can add a short description in this case returns your current message count you can tell i've already prepared doing this before and what i will do is simply save this all right so you've changed the permission scope of your app please reinstall your app okay great so we got to do that let's go reinstall press allow and now we are good all right so if we go back now to our ngrok thing we should actually won't see any because it hasn't hit yet but essentially we need to run this server so let's rerun this and now if we hit uh this slash message count you know endpoint something will happen so let's go back to slack and let's go slash message hyphen count let's hit that and we failed with error dispatch failed so something happened here inside of message count let's actually have a look here it says 405 method not allowed so what does that mean well what happened here is we sent what's known as a post request to this route now by default when we set up a root in flask it only accepts the method of get so there's all these different http methods right we have post we have get we have put we have delete what we need to do here is simply define that we are allowed to send a post request so i'm going to say methods inside of here and all capitals inside of a list i'm going to put post now let's say that we wanted to potentially receive a get and a post request well we would simply do get comma post right pretty straightforward in our case we only want post and post the reason we have that is because we're just going to be looking for some data to be posted to this endpoint so now that i added this if i rerun the server and we go back to ngrok or sorry we go back to slack my bad we resend this we should actually be good so we have a look here we can see in our flask console we actually got the post request to slash message count if we go to ngrok we can see that 200 okay happened when we sent the post request to message count so now the question is how do we actually do something with this command right you know i want to keep track of all the messages that a user sent and then tell them how many that they've sent back well there's a few different steps here it doesn't really matter what order we do these in but first i will show you how we can get information about the user from this route right because we no longer have a payload like we had previously let me go back to full screen so i can't really do the same thing i did before where i print out the payload and then i get the event and all of that i can't do that i don't have a payload so what i actually need to do is i need to get the information from the post request form is what it's called so it's kind of like the data that was sent with the post request it wasn't sent as a payload it was sent in a different way so what i'm going to do here is i'm going to say okay data in lowercase equals request dot in this case form now form is going to give me a dictionary of all of the key value pairs that were sent here so let me just print out data and show you what it looks like so print data and now let's go back to slack and let's type hi like that oops what am i saying hi slash message count let's run that the command happened and well it would be helpful if our server was running so am i bad about that go back to slack again slash message count and now you can see that we print out all of this stuff so if we have a look here we get an immutable multi-dictionary you don't have to know what that means but that's just the data type that essentially we're getting when we look at the form and we can see we have a token we have a team id domain channel id channel name user id and all of this other information right so the username is tech with tim this was the command this was the text because we could technically do something like slash message count and then add you know some arguments afterwards we're not doing that in this situation but we could do that if we wanted to so what we need to do now is get the user id from this immutable dictionary so we're going to do is we're going to say all right user or user underscore id equals data dot get and then inside of here what are we going to type well you guessed it user id now of course we also can check to make sure this wasn't the bot but we know the bot's not really going to be doing a command right so that's not something we need to be worried about and then we can return to them the amount of messages that they have so in this case let's just actually print something to the screen or let's send a message back into that channel and just tell them some random thing for now just to make sure this is working and then we'll actually make it send them the amount of messages so we actually want the channel id as well so let's grab the channel id while we're at it we'll say channel underscore id equals data dot get channel underscore id and then for the text let's send back i got the command all right so running let's go back to slack and let's see slash message count and i got the command gets returned to us awesome so that indeed is working so now we need a way to actually track how many messages that they've sent so this is pretty straightforward we could do this in a database but i'm not going to be worrying about the database right now we might do that later on in the series i'm just going to make a dictionary here and i'm just going to say message underscore counts equals this what we're going to store inside of this dictionary is keys that are equal to the user id and values that are equal to the number of messages that they've sent so i'm going to say user id colon and then whatever the number of messages is now to do this is pretty straightforward we're going to go inside of the message function here and same thing here if the bot is not here so if it's not the bot then what we will do is we'll say okay if user id in message counts then what we'll do is we will say message counts user id plus equals 1. the reason i'm doing this is because i'm essentially saying is all right if we've already added this user id into our message counts dictionary and notice that it starts off blank then all we have to do is increment the value that's stored for this key right we just need to increment that number otherwise what we need to do is say message counts user id equals one because if this is the first time that we are like keeping track of this user maybe it's the first time they sent a message we need to add them into this dictionary and then we'll just default or instantiate their value to one because this is the first message that they sent so hopefully that makes sense but this will simply add up all of the messages we'll add in users if they're not already in there and if they're already in there we'll simply increment the value now keep in mind this is going to be stored in memory right so in ram so if we ever stop this server and re-run it then this value is going to reset so obviously this would make sense to put in a database but that's a little bit beyond the scope of this tutorial so maybe we'll handle that later on but anyways what we can do now is go back to message counts and now rather than just returning text we can simply return that user's number of messages so the first thing that we're going to check is we're going to make sure that the user id is inside of the message counts right so we can do this in a few different ways but actually what i'll do is i'll say message underscore count equals and then message underscore counts dot get and we'll do user underscore id comma 0. now what this is saying is okay let's look inside of the message count's dictionary trying to find the user id if we don't find that and only if we don't find that return 0. if we do find that return the value that was stored for our user id hopefully that makes sense and then for the text we can say messages colon and i'm actually going to use an f string again you need to be using python 3.6 or above for this to work we'll say message and then inside of here message underscore cat what this will do is simply just replace inside of the string whatever number this this value is equal to hopefully that makes sense but we'll run this and you guys will see in a second so let's run this and let's go to slack and let's just type a bunch of messages and just do a bunch of gibberish and oh i forgot that it was going to return to us all of those messages that's funny but let's go slash message count and let's run this and it says we have five messages now let's send another message okay and let's go slash message count and how many do we have now we have six and we'll send two more and then slash message count and we get eight right so it makes sense that is how the command works now i actually think i'm going to leave the video there i will quickly just remove the fact that we're sending this post message i actually don't want to do that the reason i set up this message event previously was so that we could kind of transition into this keeping track of how many messages were sent but with that being said that has been this tutorial so if you guys enjoyed make sure to leave a like subscribe to the channel and again i will see you in another slack bot [Music] tutorial

Original Description

This python slack bot tutorial covers how to use slash commands in slack. We will be working on creating slash commands, handling them when they are invoked and replying to the user with some kind of meaningful message. 💻 Ngrok Download: https://ngrok.com/ 📖 Full Series Code: https://github.com/techwithtim/Slack-Bot/blob/main/bot.py 📕 Slack API Website: https://api.slack.com/ 📗 Slack Website: https://slack.com/intl/en-ca/ 📚 Playlist: https://www.youtube.com/playlist?list=PLzMcBGfZo4-kqyzTzJWCV6lyK-ZMYECDc ◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾ 🔊 Subscribe to my second channel for weekly podcasts! https://www.youtube.com/channel/UCSATlCAUi7R0Ik-wsZb2gOA 💰 Courses & Merch 💰 💻 The Fundamentals of Programming w/ Python: https://tech-with-tim.teachable.com/p/the-fundamentals-of-programming-with-python 👕 Merchandise: https://teespring.com/stores/tech-with-tim-merch-shop 🔗 Social Medias 🔗 📸 Instagram: https://www.instagram.com/tech_with_tim 📱 Twitter: https://twitter.com/TechWithTimm ⭐ Discord: https://discord.gg/twt 📝 LinkedIn: https://www.linkedin.com/in/tim-ruscica-82631b179/ 🌎 Website: https://techwithtim.net 📂 GitHub: https://github.com/techwithtim 🔊 Podcast: https://anchor.fm/tech-with-tim 🎬 My YouTube Gear 🎬 🎥 Main Camera (EOS Canon 90D): https://amzn.to/3cY23y9 🎥 Secondary Camera (Panasonic Lumix G7): https://amzn.to/3fl2iEV 📹 Main Lens (EFS 24mm f/2.8): https://amzn.to/2Yuol5r 🕹 Tripod: https://amzn.to/3hpSprv 🎤 Main Microphone (Rode VideoMic Pro): https://amzn.to/3d0KKMG 🎤 Secondary Microphone (Synco Wireless Lapel System): https://amzn.to/3e07Swl 🎤 Third Microphone (Blue Yeti USB Mic): https://amzn.to/3hoD625 ☀️ Lights: https://amzn.to/2ApeiXr ⌨ Keyboard (Daskeyboard 4Q): https://amzn.to/2YpN5vm 🖱 Mouse (Steelseries Rival 300): https://amzn.to/3cVTqnD 📸 Webcam (Logitech 1080p Pro): https://amzn.to/2B2IXcQ 📢 Speaker (Beats Pill): https://amzn.to/2XYc5ef 🎧 Headphones (Bose Quiet Comfort 35): https://amzn.to/2MWbl3e 🌞 Lamp (BenQ E-reading La
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Tech With Tim · Tech With Tim · 0 of 60

← Previous Next →
1 A* Path Finding Algorithm(Visualization)
A* Path Finding Algorithm(Visualization)
Tech With Tim
2 Python Programming Tutorial #1 - Variables and Data Types
Python Programming Tutorial #1 - Variables and Data Types
Tech With Tim
3 Python Programming Tutorial #2 - Basic Operators and Input
Python Programming Tutorial #2 - Basic Operators and Input
Tech With Tim
4 Python Programming Tutorial #3 - Conditions
Python Programming Tutorial #3 - Conditions
Tech With Tim
5 Python Programming Tutorial #4 - IF/ELIF/ELSE
Python Programming Tutorial #4 - IF/ELIF/ELSE
Tech With Tim
6 Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Tech With Tim
7 Python Programming Tutorial #6 - For Loops
Python Programming Tutorial #6 - For Loops
Tech With Tim
8 Python Programming Tutorial #7 - While Loops
Python Programming Tutorial #7 - While Loops
Tech With Tim
9 Python Programming Tutorial #8 - Lists and Tuples
Python Programming Tutorial #8 - Lists and Tuples
Tech With Tim
10 Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Tech With Tim
11 Python Programming Tutorial #10 - String Methods
Python Programming Tutorial #10 - String Methods
Tech With Tim
12 How to Overclock a NVIDIA GPU
How to Overclock a NVIDIA GPU
Tech With Tim
13 Python Programming Tutorial #11 - Slice Operator
Python Programming Tutorial #11 - Slice Operator
Tech With Tim
14 Python Programming Tutorial #12 - Functions
Python Programming Tutorial #12 - Functions
Tech With Tim
15 Python Programming Tutorial #13 - How to Read a Text File
Python Programming Tutorial #13 - How to Read a Text File
Tech With Tim
16 Python Programming Tutorial #14 - Writing to a Text File
Python Programming Tutorial #14 - Writing to a Text File
Tech With Tim
17 Python Programming Tutorial #15 - Using .count() and .find()
Python Programming Tutorial #15 - Using .count() and .find()
Tech With Tim
18 Python Programming Tutorial #16 - Introduction to Modular Programming
Python Programming Tutorial #16 - Introduction to Modular Programming
Tech With Tim
19 Python Programming Tutorial #17 - Optional Parameters
Python Programming Tutorial #17 - Optional Parameters
Tech With Tim
20 Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Tech With Tim
21 Python Programming Tutorial #19 - Global vs Local Variables
Python Programming Tutorial #19 - Global vs Local Variables
Tech With Tim
22 Python Programming Tutorial #20 - Classes and Objects
Python Programming Tutorial #20 - Classes and Objects
Tech With Tim
23 Cool VBS Script to Prank Your Friends!
Cool VBS Script to Prank Your Friends!
Tech With Tim
24 How to Overclock an AMD GPU
How to Overclock an AMD GPU
Tech With Tim
25 Best GPU'S For Mining Ethereum (2018)
Best GPU'S For Mining Ethereum (2018)
Tech With Tim
26 Recursion and Memoization Tutorial Python
Recursion and Memoization Tutorial Python
Tech With Tim
27 Ethereum Mining Rig - Hardware Guide
Ethereum Mining Rig - Hardware Guide
Tech With Tim
28 Pygame Tutorial #1 - Basic Movement and Key Presses
Pygame Tutorial #1 - Basic Movement and Key Presses
Tech With Tim
29 How to Install Pygame (Windows 8/10)
How to Install Pygame (Windows 8/10)
Tech With Tim
30 How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
Tech With Tim
31 How to Mine Ethereum 2018 - WORKING (Super-Easy)
How to Mine Ethereum 2018 - WORKING (Super-Easy)
Tech With Tim
32 Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Tech With Tim
33 Pygame Tutorial #2 - Jumping and Boundaries
Pygame Tutorial #2 - Jumping and Boundaries
Tech With Tim
34 Pygame Tutorial #3 - Character Animation & Sprites
Pygame Tutorial #3 - Character Animation & Sprites
Tech With Tim
35 Pygame Tutorial #4 - Optimization & OOP
Pygame Tutorial #4 - Optimization & OOP
Tech With Tim
36 OBS Studio Tutorial - Best OBS Settings
OBS Studio Tutorial - Best OBS Settings
Tech With Tim
37 Linear Search Algorithm - Python Example and Code
Linear Search Algorithm - Python Example and Code
Tech With Tim
38 Make Any Mic Sound AMAZING! (WITH OBS)
Make Any Mic Sound AMAZING! (WITH OBS)
Tech With Tim
39 Binary Search Algorithm - Python Example & Code
Binary Search Algorithm - Python Example & Code
Tech With Tim
40 Pygame Tutorial #5 - Projectiles
Pygame Tutorial #5 - Projectiles
Tech With Tim
41 Pygame Game - Mini Golf
Pygame Game - Mini Golf
Tech With Tim
42 Pygame Tutorial - Projectile Motion (Part 1)
Pygame Tutorial - Projectile Motion (Part 1)
Tech With Tim
43 Pygame Tutorial - Projectile Motion (Part 2)
Pygame Tutorial - Projectile Motion (Part 2)
Tech With Tim
44 Pygame Tutorial #6 - Enemies
Pygame Tutorial #6 - Enemies
Tech With Tim
45 Pygame Tutorial #7 - Collision and Hit Boxes
Pygame Tutorial #7 - Collision and Hit Boxes
Tech With Tim
46 Pygame Tutorial #8 - Scoring and Health Bars
Pygame Tutorial #8 - Scoring and Health Bars
Tech With Tim
47 Cloud Mining vs. Hardware Mining - 2018
Cloud Mining vs. Hardware Mining - 2018
Tech With Tim
48 How to Install Pygame on Mac OSX (Fast-Simple)
How to Install Pygame on Mac OSX (Fast-Simple)
Tech With Tim
49 Pygame Tutorial #9 - Sound Effects, Music & More Collision
Pygame Tutorial #9 - Sound Effects, Music & More Collision
Tech With Tim
50 Pygame Tutorial #10 - Finishing Touches & Next Steps
Pygame Tutorial #10 - Finishing Touches & Next Steps
Tech With Tim
51 How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
Tech With Tim
52 How to Create a Button in Pygame [CODE IN DESCRIPTION]
How to Create a Button in Pygame [CODE IN DESCRIPTION]
Tech With Tim
53 Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Tech With Tim
54 Pygame Side-Scroller Tutorial #2 - Random Object Generation
Pygame Side-Scroller Tutorial #2 - Random Object Generation
Tech With Tim
55 Pygame Side-Scroller Tutorial #3 - Collision
Pygame Side-Scroller Tutorial #3 - Collision
Tech With Tim
56 Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Tech With Tim
57 How to Create A Message Box in Python - Tkinter
How to Create A Message Box in Python - Tkinter
Tech With Tim
58 Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Tech With Tim
59 How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
Tech With Tim
60 Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Tech With Tim

This video tutorial teaches how to create a Slack bot with slash commands using Python and the Slack API. It covers creating slash commands, handling API requests, and replying to users with meaningful messages. The tutorial provides hands-on experience with tools such as Flask and ngrok.

Key Takeaways
  1. Create a new command in the Slack API
  2. Specify the command name and request URL
  3. Create a new endpoint on the server to handle the request
  4. Add a new route to the server to handle the request
  5. Define a POST request handler for slash commands
  6. Use request.form to access data sent with the POST request
  7. Get user ID from data dictionary
  8. Check if user ID is in message_counts dictionary
  9. Increment message count for existing users, set to 1 for new users
  10. Return user's message count from message_counts dictionary
💡 The tutorial demonstrates how to use dictionaries to store user message counts and how to update the message count when a new message is sent.

Related AI Lessons

Up next
5 Levels of AI Agents - From Simple LLM Calls to Multi-Agent Systems
Dave Ebbelaar (LLM Eng)
Watch →