Skip to content

Instantly share code, notes, and snippets.

@NotoriousArnav
Created September 19, 2022 19:10
Show Gist options
  • Save NotoriousArnav/918e20fe1a64bd2b423374d250a25b25 to your computer and use it in GitHub Desktop.
Save NotoriousArnav/918e20fe1a64bd2b423374d250a25b25 to your computer and use it in GitHub Desktop.
A Sample Discord Webhook Bot
#!/usr/bin/env python3
import requests
import os
"""
This Script Faciliates with Easy Sending of Messages using WebHooks for Discord Channels.
For Example Use Case, NASA APOD Integration has been Done here.
To send a Message to Specified Channel, Just grab the webhook of the Channel and use the brodcast_message function to send the Message.
To grab latest NASA APOD Response Use apod_response function.
The Only Dependencies of this Script is requests and os
$ pip3 install requests
Note: os module is Installed By Default
"""
def apod_response():
"""
Grab Latest Response from NASA Astronomical Picture of the Day (APOD) API
"""
res = requests.get(
"https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY"
)
return res.json()
def brodcast_message(webhook_url, content, username, avatar_url=''):
"""
Brodcast User Specified Message to a Specific Server's Channel Via the webhook url provided in ```webhook-url``` argument.
ARGS:
webhook_url : str #This is Important, since this URL is unique to the Server and the Channel
content : str #This is Important, since this is the Body of the Message
username: str #This is the Username that will be shown in the Message user
avatar_url : str #The Profile Picture That will be Used for that Message
"""
res = requests.post(
webhook_url,
json = {
'username': username,
'avatar_url': avatar_url,
'content': content
})
if res.text == '':
return True # Empty Response Signifies Success
return False
if __name__ == "__main__":
url = os.getenv('DISCORD_WEBHOOK_URL', None) # Grab Webhook URL from ENV
username = os.getenv('DISCORD_WEBHOOK_URL_USERNAME', 'NASA APOD')
req = apod_response() # refer help(apod_response)
Title = req['title']
Date = req['date']
Copyright = req['copyright']
Image = req['hdurl']
content = f"""
{Title}
{Date}
{Copyright}
{Image}
""" #Content Construction
r = brodcast_message(
url,
content,
username,
os.getenv('DISCORD_WEBHOOK_URL_AVATAR', Image)
)
if r:
print('Success')
else:
print('Failure')
print(content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment