• Skip to main content
  • Skip to header right navigation
  • Skip to site footer
Maker Hacks

Maker Hacks

Ideas, news & tutorials for makers and hackers – Arduino/Raspberry Pi, 3D printing, robotics, laser cutting, and more

  • Home
  • About
  • YouTube
  • Recommendations
  • Contact

Linux Automation Tip: Process Discord Messages and Launch Shell Commands in Python

You are here: Home / Hacks, Tips, and Tutorials / Linux Automation Tip: Process Discord Messages and Launch Shell Commands in Python
FacebookTweetPin
Author: Chris Garrett

Run Shell Commands with a Python Discord BotIn the previous Discord article we set up a listener, but really that was just the foundation – enough to listen for “hello” and greet the user. Now we need a real-world example.

Previously

Linux Automation Tip: Listen for Commands with your Discord Bot using Python

Workflow

Here is our to-do list:

  1. Listen for our specific command in the stream of messages
  2. Extract the required information from the command message
  3. Act on that information
  4. Respond back to the user

We saw in the previous article that Discord sends us message objects, and from that object we can easily take three pieces of valuable information (and more):

  • The author (if only to greet them)
  • The channel (eg. General, or the user might be using a Direct Message)
  • The Message Content (the text string containing the message content)

Listening out for the messages

In our previous example we simply created the “hello world” of Discord bots, like so:

# listen for specific messages
@client.event
async def on_message(message):
    if message.content.startswith("/hello"):
        await client.send_message(message.channel, "BY YOUR COMMAND!")

If the message string starts with our command then we reply. Easy.

In the real world, however, we want to pass more complex messages, and we need some more action. We need to break the command down into components.

We can do this by “splitting” the string. Assuming the parameters are separated by spaces, we can do this easily in Python:

args = message.content.split(" ")

Args becomes a list of the pieces of message content, essentially we took each word in order and put it in its own little box, ready to take back out again.

Real, Useful Example – Bookmark Bot

An increasing part of my blogging workflow is curation. That means I am on the look out for cool links across my blog topics. I made a database and an associated Python script, but I am not always at a terminal. Enter Bookmark Bot!

This bot takes the following command:

/add-link makerhacks http://example.com
  • The add-link command
  • The blog to associate the link with
  • The link

He looks like this:

Taking Action

Recall I already had a Python script that added to the bookmarks database?

Rather than duplicate that code, I can call it as a Shell command. For convenience, I wrapped it in a .SH Bash script so that it went to the correct directory and used the correct Python version command.

So what we are saying is your Discord can become a UI for your existing scripts!

Now, obviously, there are security impacts to this, but we are big boys and girls, we already understand that.

We put that split function into a function so we can pass the message and get back the arguments, just in case I want to do more later, perhaps keep a log?

The Python script is called using Subprocess, so you need an import subprocess line at the start of your code.

if message.content.startswith("/add-link"):
    args = process_message(message)
    blog = args[1]
    link = args[2]
    result = subprocess.check_output(['/home/chrisg/steemit/add-link.sh', blog, link])
    await client.send_message(message.channel, "@{} Link added: {}".format(message.author,link))

Nice, eh?

That’s pretty much it – just expand the list of commands to your heart’s delight 😀

Check out the full code in this Gist.

 

Related

Category: Hacks, Tips, and TutorialsTag: making, programming, python, technology
FacebookTweetPin

About Chris Garrett

Marketing Director by day, maker, retro gaming, tabletop war/roleplaying nerd by night. Co-author of the Problogger Book with Darren Rowse. Husband, Dad, 🇨🇦 Canadian.

Check out Retro Game Coders for retro gaming/computing.

☕️ Support Maker Hacks on Ko-Fi and get exclusive content and rewards!

Previous Post:Linux Automation Tip: Listen for Commands with your Discord Bot using Python
Next Post:Creality Ender 2 3D Printer Kit Reviewender2

Sidebar

  • Facebook
  • Twitter
  • Instagram
  • YouTube

Recently Popular

  • Gweike Cloud Review
  • How to choose the right 3D printer for you
  • Glowforge Review – Glowforge Laser Engraver Impressions, Plus Glowforge Versus Leading Laser Cutters
  • Original Prusa i3 Mk3S Review
  • Best 3D Printing Facebook Groups
  • Elegoo Mars Review – Review of the Elegoo Mars MSLA Resin 3D Printer
  • Glowforge ‘Pass-Through’ Hack: Tricking the Front Flap of the Glowforge with Magnets to Increase Capacity
  • How to Make a DIY “Internet of Things” Thermometer with ESP8266/Arduino
  • Wanhao Duplicator i3 Review
  • IKEA 3D Printer Enclosure Hack for Wanhao Di3
  • Creality CR-10 3d printer review – Large format, quality output, at a low price!
  • 3D Printed Tardis with Arduino Lights and Sounds
  • Anet A8 Review – Budget ($200 or less!) 3D Printer Kit Review
  • Make your own PEI 3D printer bed and get every print to stick!
  • Upgrading the Wanhao Di3 from Good to Amazing
  • How to Install and Set Up Octopi / Octoprint
  • Creality CR-10 S5 Review

Copyright © 2023 · Maker Hacks · All Rights Reserved · Powered by Mai Theme