create account

Part 4: Coding on Hive With Python - Sending Messages to Discord by learncode

View this thread on: hive.blogpeakd.comecency.com
· @learncode · (edited)
$1.31
Part 4: Coding on Hive With Python - Sending Messages to Discord
Part 4 includes how to define a Python function, how to send messages to Discord channels, how to use the dotenv module to store and load secrets.

Part 4 requires some knowledge from parts 1,2,3. If you already know how to install Python modules, import Python modules, and run Python scripts from your terminal, you are good to go.

### Set Up - Install Two Modules

First, we need to install a few modules using pip. For a quick refresher on using pip (python package manager) see [Part 2](https://peakd.com/programming/@learncode/part-2-coding-on-hive-with-python-installing-modules-and-fetching-some-data-from-hive).

List of required modules to install with pip:
* python-dotenv
* requests

Today’s example uses `dotenv` for storage or secrets, and `requests` for sending data to Discord.

---

### Setting up a Webhook and Storing it Safely

Webhooks are an easy way to send data to Discord. All we need to do is generate a unique URL, and then make an HTTP request to the URL. The payload of the request contains the message content.

To generate a Webhook URL, you need to be a Discord server admin, or need to ask a friend who is an admin. For the channel of interest, go to “Edit Channel”, switch to the “Integrations” tab, and click “Create Webhook”. Optionally, change the avatar and the name of the Webhook. 


![image.png](https://files.peakd.com/file/peakd-hive/learncode/48RMhj7BxTo8k7b4mPxgcApjKkxJoBYQZXn1tm6HXF6zyAMesznPxduoSvdZge83iC.png)


Next, we need to copy the Webhook URL and save it somewhere. We could save it directly in a python script. Then anyone who gets a copy of the script can use the same webhook and send messages to discord. Instead, we will save it in a `.env.` folder, so our python script can be shared freely without fear of leaking the secret URL.

To do this all we need to do is create a file called `.env` in the project folder where our python script will be run from.

For example:

```
DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/854752330439065601/ei19hfobnLw7fLMmyxYNSqifm4gHre9P7yUeuQ12DUYiNJOprTH66h5oWfdYIySExuAT

```

---

### Loading the Webhook URL Using dotenv()

With a few lines of code, the `DISCORD_WEBHOOK_URL` value is loaded from our `.env` file. 

```
import dotenv
import os
dotenv.load_dotenv()
DISCORD_WEBHOOK_URL = os.getenv('DISCORD_WEBHOOK_URL')
```

First, we import the `dotenv` and `os` modules. Then, call into dotenv’s `load_dotenv()` to read the `.env` file and make the variables accessible in the current operating environment.  Finally copy the environment variable’s value to a local python variable called `DISCORD_WEBHOOK_URL` for convenience. The example uses this variable later on.

---

### Defining a Function - send_discord_message()

The next thing to do is define our first function. This is done using the `def` keyword, followed by the function name, and a list of parameters in parens, concluded with a colon.

The inner code blocks of the function must be single-indented. Python’s interpreter is sensitive to whitespace/indentation, which is a neat way to make the code look clean while reducing the amount of punctation characters.

```
def send_discord_message(username, message_body):

    payload = {
        "username": username,
        "content": message_body
    }

    try:
        requests.post(DISCORD_WEBHOOK_URL, data=payload)
    except:
        print('Error while sending discord message. Check configuration.')

```

We create a function called `send_discord_message()` with 2 named parameters. The parameters are named `username` and `message_body`. Unlike other programming languages, we don’t need to declare the parameter types. Python interpreter will infer the types from the data. Another neat way to make the code more concise.

The function will take the two parameters and pack them into a dictionary named ‘payload’.  Then, the requests module’s `post()` function is called to send the payload to the DISCORD_WEBHOOK_URL. If anything goes wrong, such as an invalid URL being set, an exception is thrown and an error message printed.

---

### Calling the send_discord_message() Function

The last step is to call the function we defined. 

```
send_discord_message(‘MyBot’, ‘Hello World!’)
```

If all goes well, the message shows up in Discord!


![8334A78F-245D-45E1-9436-F0A67EAB8ECD.png](https://files.peakd.com/file/peakd-hive/learncode/23wWkixKim7ktske9HFDnyKfKu8kD7dLjwzkCFBHbfGrkPv9hXUmJFrCr9qKa9VunbcWN.png)

From here, ‘Hello World!’ can be replaced with any string. Using `beem` like Part 2 and 3, some interesting Hive data can be fetched and forwarded to your Discord channel.

---

### Putting it all together - The Whole Script

```
import dotenv
import requests
import os

dotenv.load_dotenv()
DISCORD_WEBHOOK_URL = os.getenv('DISCORD_WEBHOOK_URL')

def send_discord_message(username, message_body):

    payload = {
        "username": username,
        "content": message_body
    }

    try:
        requests.post(DISCORD_WEBHOOK_URL, data=payload)
    except:
        print('Error while sending discord message. Check configuration.')


send_discord_message('MyBot', 'Hello World!')

```


### Conclusion

In this example we first created a Discord Webhook. Then we stored it’s URL in a .env file, and loaded it from there into our Python script.

A function was defined for sending messages to discord using the `requests` module. This function can be copy-pasted and reused in other scripts.

Finally, the function is called and a message pops up in the Discord channel.

---

Thanks for reading! Please let me know if anything is unclear or incorrect. This is intended to be a living document to be improved and maintained over time.

A [channel for #learn-code](https://discord.gg/AucZk6h5Pf) is set up in the [Hive.pizza discord](https://discord.gg/AucZk6h5Pf) for discussing these lessons.

<center>
This blog is brought to you by the [Hive.Pizza](https://hive.pizza) team.


![hivepizza-200px.png](https://files.peakd.com/file/peakd-hive/learncode/23xyfw2j4NRMrCpGh8VpMHjeSbQ6TnZXzVNEJSdjR9m5T9B9dTZhRBGZ9fzm6C6X9dVSg.png)


</center>



![poweredbyhive.png](https://files.peakd.com/file/peakd-hive/learncode/23tw3b4AofQAZ2DE5T9gjWwZAp6RrQh5Z8KZgzwRhxa3QQjRUy9bRSKyYie7RwcieGvpK.png)
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 7 others
properties (23)
authorlearncode
permlinkpart-4-coding-on-hive-with-python-sending-messages-to-discord
categoryprogramming
json_metadata"{"app":"peakd/2021.06.2","format":"markdown","author":"hive.pizza","description":"Using python scripts to send messages into Discord","tags":["programming","coding","hive","python","beem","ctp","palnet","proofofbrain","stem","broadhive"],"users":["learncode"],"image":["https://files.peakd.com/file/peakd-hive/learncode/23wWkixKim7ktske9HFDnyKfKu8kD7dLjwzkCFBHbfGrkPv9hXUmJFrCr9qKa9VunbcWN.png","https://files.peakd.com/file/peakd-hive/learncode/48RMhj7BxTo8k7b4mPxgcApjKkxJoBYQZXn1tm6HXF6zyAMesznPxduoSvdZge83iC.png","https://files.peakd.com/file/peakd-hive/learncode/23xyfw2j4NRMrCpGh8VpMHjeSbQ6TnZXzVNEJSdjR9m5T9B9dTZhRBGZ9fzm6C6X9dVSg.png","https://files.peakd.com/file/peakd-hive/learncode/23tw3b4AofQAZ2DE5T9gjWwZAp6RrQh5Z8KZgzwRhxa3QQjRUy9bRSKyYie7RwcieGvpK.png"]}"
created2021-06-16 17:14:06
last_update2021-06-16 19:05:45
depth0
children11
last_payout2021-06-23 17:14:06
cashout_time1969-12-31 23:59:59
total_payout_value0.673 HBD
curator_payout_value0.636 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length6,247
author_reputation682,726,195,093
root_title"Part 4: Coding on Hive With Python - Sending Messages to Discord"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd0
post_id104,370,356
net_rshares4,220,652,044,704
author_curate_reward""
vote details (71)
@enjar ·
One of these days I'm going get around to make a Discord bot like I keep telling myself I will one day. 
👍  , , ,
properties (23)
authorenjar
permlinkre-learncode-qut6jl
categoryprogramming
json_metadata{"tags":["programming"],"app":"peakd/2021.06.2"}
created2021-06-16 19:09:24
last_update2021-06-16 19:09:24
depth1
children1
last_payout2021-06-23 19:09:24
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length104
author_reputation860,294,188,202,808
root_title"Part 4: Coding on Hive With Python - Sending Messages to Discord"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id104,372,265
net_rshares45,782,138,485
author_curate_reward""
vote details (4)
@pizzabot ·
Thanks for the feedback. We can go deeper to explain how we built our Discord bots. We have 2 now :P
properties (22)
authorpizzabot
permlinkre-enjar-qut6mn
categoryprogramming
json_metadata{"tags":["programming"],"app":"peakd/2021.06.2"}
created2021-06-16 19:11:12
last_update2021-06-16 19:11:12
depth2
children0
last_payout2021-06-23 19:11:12
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length100
author_reputation6,157,049,145,447
root_title"Part 4: Coding on Hive With Python - Sending Messages to Discord"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id104,372,291
net_rshares0
@hivebuzz ·
Congratulations @learncode! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s) :

<table><tr><td><img src="https://images.hive.blog/60x70/http://hivebuzz.me/@learncode/upvoted.png?202106161805"></td><td>You received more than 300 upvotes.<br>Your next target is to reach 400 upvotes.</td></tr>
</table>

<sub>_You can view your badges on [your board](https://hivebuzz.me/@learncode) and compare yourself to others in the [Ranking](https://hivebuzz.me/ranking)_</sub>
<sub>_If you no longer want to receive notifications, reply to this comment with the word_ `STOP`</sub>

properties (22)
authorhivebuzz
permlinkhivebuzz-notify-learncode-20210616t181605000z
categoryprogramming
json_metadata{"image":["http://hivebuzz.me/notify.t6.png"]}
created2021-06-16 18:16:03
last_update2021-06-16 18:16:03
depth1
children0
last_payout2021-06-23 18:16:03
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length630
author_reputation367,870,644,930,125
root_title"Part 4: Coding on Hive With Python - Sending Messages to Discord"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id104,371,434
net_rshares0
@huzzah ·
This is so comprehensive. Thank you for taking the time to compile your knowledge like this so others can learn from it! I have always been curious about discord bots. So this series is very informative. 

!PIZZA
👍  , , , , , ,
properties (23)
authorhuzzah
permlinkre-learncode-qutfr4
categoryprogramming
json_metadata{"tags":["programming"],"app":"peakd/2021.06.2"}
created2021-06-16 22:28:18
last_update2021-06-16 22:28:18
depth1
children2
last_payout2021-06-23 22:28:18
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length212
author_reputation8,263,743,014,055
root_title"Part 4: Coding on Hive With Python - Sending Messages to Discord"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id104,375,295
net_rshares53,811,906,444
author_curate_reward""
vote details (7)
@learncode ·
Thanks for reading!
👍  
properties (23)
authorlearncode
permlinkre-huzzah-qutftp
categoryprogramming
json_metadata{"tags":["programming"],"app":"peakd/2021.06.2"}
created2021-06-16 22:29:51
last_update2021-06-16 22:29:51
depth2
children0
last_payout2021-06-23 22:29:51
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length19
author_reputation682,726,195,093
root_title"Part 4: Coding on Hive With Python - Sending Messages to Discord"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id104,375,325
net_rshares4,297,300,800
author_curate_reward""
vote details (1)
@pizzabot ·
<div class='pull-right'><center><sup>Connect</sup></center><p><a href="https://discord.gg/Q9bQAKpWGS"><img src="https://files.peakd.com/file/peakd-hive/pizzabot/AKF96fKjnX3wjXERHcKAFHaoHnfTVhXqPjXVz8E1Th9nPiJqmFtaycosVpPBZ7z.png"></a></p></div><div class='pull-right'><center><sup>Trade</sup></center><p><a href='https://hive-engine.com/?p=market&t=PIZZA'><img src="https://files.peakd.com/file/peakd-hive/pizzabot/23sxbi2M4UjELDzQjxPdzubdgfMjHTCtA1xueyxmnhJUrB8136VyK3pqynyWYiZYF9HrC.png"></a></p></div><center><br> <p>@learncode! I sent you a slice of <strong><em>$PIZZA</em></strong> on behalf of @huzzah.</p> <p>Learn more about <strong><em>$PIZZA Token</em></strong> at <a href="https://hive.pizza">hive.pizza</a> <sub>(1/20)</sub></p> </center><div></div>
properties (22)
authorpizzabot
permlinkre-re-learncode-qutfr4-20210616t222930z
categoryprogramming
json_metadata"{"app": "beem/0.24.19"}"
created2021-06-16 22:29:30
last_update2021-06-16 22:29:30
depth2
children0
last_payout2021-06-23 22:29:30
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length761
author_reputation6,157,049,145,447
root_title"Part 4: Coding on Hive With Python - Sending Messages to Discord"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id104,375,319
net_rshares0
@lallo ·
$0.07
Thank you fucking much for this!! Really helpful!!
👍  
properties (23)
authorlallo
permlinkre-learncode-qwpt3s
categoryprogramming
json_metadata{"tags":["programming"],"app":"peakd/2021.07.2"}
created2021-07-23 20:33:36
last_update2021-07-23 20:33:36
depth1
children2
last_payout2021-07-30 20:33:36
cashout_time1969-12-31 23:59:59
total_payout_value0.034 HBD
curator_payout_value0.035 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length50
author_reputation17,853,408,691,521
root_title"Part 4: Coding on Hive With Python - Sending Messages to Discord"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id105,088,624
net_rshares117,277,261,004
author_curate_reward""
vote details (1)
@learncode ·
No problem! Thanks for reading!
properties (22)
authorlearncode
permlinkre-lallo-qwpt6t
categoryprogramming
json_metadata{"tags":["programming"],"app":"peakd/2021.07.2"}
created2021-07-23 20:35:18
last_update2021-07-23 20:35:18
depth2
children1
last_payout2021-07-30 20:35:18
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length31
author_reputation682,726,195,093
root_title"Part 4: Coding on Hive With Python - Sending Messages to Discord"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id105,088,650
net_rshares0
@lallo ·
You opened a world of possibilities in my mind. Thanks!!
I thought was more difficult to interact with Discord
properties (22)
authorlallo
permlinkre-learncode-qwptno
categoryprogramming
json_metadata{"tags":["programming"],"app":"peakd/2021.07.2"}
created2021-07-23 20:45:30
last_update2021-07-23 20:45:30
depth3
children0
last_payout2021-07-30 20:45:30
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length110
author_reputation17,853,408,691,521
root_title"Part 4: Coding on Hive With Python - Sending Messages to Discord"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id105,088,887
net_rshares0
@pizzabot ·
<div class='pull-right'><center><sup>Connect</sup></center><p><a href="https://discord.gg/Q9bQAKpWGS"><img src="https://files.peakd.com/file/peakd-hive/pizzabot/AKF96fKjnX3wjXERHcKAFHaoHnfTVhXqPjXVz8E1Th9nPiJqmFtaycosVpPBZ7z.png"></a></p></div><div class='pull-right'><center><sup>Trade</sup></center><p><a href='https://hive-engine.com/?p=market&t=PIZZA'><img src="https://files.peakd.com/file/peakd-hive/pizzabot/23sxbi2M4UjELDzQjxPdzubdgfMjHTCtA1xueyxmnhJUrB8136VyK3pqynyWYiZYF9HrC.png"></a></p></div><center><br> <p>@learncode! This post has been manually curated by the <strong><em>$PIZZA</em></strong> Token team!</p><p>Learn more about <strong><em>$PIZZA Token</em></strong> at <a href="https://hive.pizza">hive.pizza</a>. Enjoy a slice of $PIZZA on us!</p> </center><div></div>
properties (22)
authorpizzabot
permlinkre-part-4-coding-on-hive-with-python-sending-messages-to-discord-20210616t171847z
categoryprogramming
json_metadata"{"app": "beem/0.24.19"}"
created2021-06-16 17:18:48
last_update2021-06-16 17:18:48
depth1
children0
last_payout2021-06-23 17:18:48
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length785
author_reputation6,157,049,145,447
root_title"Part 4: Coding on Hive With Python - Sending Messages to Discord"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id104,370,436
net_rshares0
@stickupboys ·
nice one, i still don't understand the tip bot lol....and yes I went to the help thingy twice....
properties (22)
authorstickupboys
permlinkre-learncode-quuw2m
categoryprogramming
json_metadata{"tags":["programming"],"app":"peakd/2021.06.2"}
created2021-06-17 17:18:21
last_update2021-06-17 17:18:21
depth1
children0
last_payout2021-06-24 17:18:21
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length97
author_reputation408,866,242,639,441
root_title"Part 4: Coding on Hive With Python - Sending Messages to Discord"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id104,390,737
net_rshares0