Skip to content

Commit

Permalink
Merge pull request #6 from HCookie/develop
Browse files Browse the repository at this point in the history
Update master
  • Loading branch information
HCookie authored Oct 12, 2024
2 parents a207264 + 4f57243 commit 58ad866
Show file tree
Hide file tree
Showing 11 changed files with 251 additions and 28 deletions.
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,27 @@ Copy all the files in `custom_components\webhook_service` to `custom_components\
## Configuration
Simply add `webhook_service:` to your configuration.yaml file

### Or

To add the **Webhook Service** integration to your Home Assistant, use this My button:

<a href="https://my.home-assistant.io/redirect/config_flow_start?domain=webhook_service" class="my badge" target="_blank"><img src="https://my.home-assistant.io/badges/config_flow_start.svg"></a>

<details><summary style="list-style: none"><h3><b style="cursor: pointer">Manual configuration steps</b></h3></summary>

If the above My button doesn’t work, you can also perform the following steps manually:

- Browse to your Home Assistant instance.

- Go to [Settings > Devices & Services](https://my.home-assistant.io/redirect/integrations/).

- In the bottom right corner, select the [Add Integration button.](https://my.home-assistant.io/redirect/config_flow_start?domain=webhook_service)

- From the list, select **Webhook Service**.

- Follow the instructions on screen to complete the setup.

</details>

## Usage
Use the `webhook_service:basic_webhook` service in automations to post json data to a webhook
39 changes: 22 additions & 17 deletions custom_components/webhook_service/__init__.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,28 @@
import logging
import requests
import json
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant

DOMAIN = "webhook_service"
_LOGGER = logging.getLogger(__name__)
from .const import DOMAIN, WEBHOOKS_DATAS

import logging
_LOGGER = logging.getLogger(__name__)

SERVICE_SEND = "basic_webhook"
async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the integration."""
if DOMAIN not in hass.data:
hass.data[DOMAIN] = {}
await _setup_webhooks(hass, config)
return True

def setup(hass, config):
def send_basic_webhook(call):
data = call.data.copy()
if "json" in data:
jsondata = json.loads(data["json"])
else:
jsondata = {}
result = requests.post(data["webhook"], json = jsondata)
_LOGGER.warn('Received data', data["webhook"])
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up the platform."""
if DOMAIN not in hass.data:
hass.data[DOMAIN] = {}
await _setup_webhooks(hass, entry)
return True

hass.services.register(DOMAIN, SERVICE_SEND, send_basic_webhook)

return True
async def _setup_webhooks(hass: HomeAssistant, data: dict | ConfigEntry):
for webhook_data in WEBHOOKS_DATAS:
if "service" in webhook_data and "function" in webhook_data:
hass.services.async_register(DOMAIN, webhook_data["service"], webhook_data["function"])
_LOGGER.info(f'{webhook_data["service"]} set up')
20 changes: 20 additions & 0 deletions custom_components/webhook_service/config_flow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from typing import Any

from homeassistant.config_entries import ConfigFlow, ConfigFlowResult

from .const import DOMAIN, DEFAULT_NAME

class WebhookServiceConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow."""

async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the initial step."""
if self._async_current_entries():
return self.async_abort(reason="single_instance_allowed")

if user_input is None:
return self.async_show_form(step_id="user")

return self.async_create_entry(title=DEFAULT_NAME, data={})
16 changes: 16 additions & 0 deletions custom_components/webhook_service/const.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from typing import Final

DOMAIN = "webhook_service"
DEFAULT_NAME = "Webhook Service Integration"

from .webhook_functions import functions
WEBHOOKS_DATAS: Final = [
{
"service": "basic_webhook",
"function": functions.basic_webhook
},
{
"service": "discord_webhook",
"function": functions.discord_webhook
}
]
7 changes: 4 additions & 3 deletions custom_components/webhook_service/manifest.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
{
"domain": "webhook_service",
"name": "Webhook Service Integration",
"codeowners": [],
"config_flow": true,
"dependencies": [],
"documentation": "https://github.com/HCookie/Webhook-Service-home-assistant",
"iot_class": "local_polling",
"issue_tracker": "https://github.com/HCookie/Webhook-Service-home-assistant/issues",
"dependencies": [],
"codeowners": [],
"requirements": [],
"iot_class": "local_polling",
"version": "0.1.0"
}
73 changes: 65 additions & 8 deletions custom_components/webhook_service/services.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
basic_webhook:
name: Basic Webhook
description: Service Provider to use Webhooks
fields:
webhook:
Expand All @@ -11,20 +12,76 @@ basic_webhook:
name: Json Data
description: Json Data To Send
required: true
selector:
text:
discord_webhook:
name: Discord Webhook
description: Service Provider to use Discord Webhooks
fields:
webhook:
name: Discord Webhook
description: Discord Webhook url
description: Discord Webhook URL
required: true
selector:
text:
content:
name: Content
description: Message Content
type:
title:
name: Title
description: The title of the embed
required: true
selector:
text:
json:
name: Json Data
description: Json Data To Send
template:
title_url:
name: Title URL
description: The URL of embed title
required: false
selector:
template:
description:
name: Description
description: The description of the embed
required: true
selector:
template:
thumbnail:
name: Thumbnail
description: The thumbnail of the embed
required: false
selector:
template:
author:
name: Author
description: The author of the embed
required: false
selector:
template:
fields:
name: Fields
description: List of fields in the embed
required: false
selector:
template:
image:
name: Image
description: The image of the embed
required: false
selector:
template:
color:
name: Color
description: The color of the embed (in decimal format)
required: false
selector:
template:
timestamp:
name: Timestamp
description: The timestamp of the embed
required: false
selector:
template:
footer:
name: Footer
description: The footer of the embed
required: false
selector:
template:
12 changes: 12 additions & 0 deletions custom_components/webhook_service/strings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"config": {
"step": {
"user": {
"description": "Do you want to add Webhook Service?"
}
},
"abort": {
"single_instance_allowed": "Only single instance is allowed."
}
}
}
12 changes: 12 additions & 0 deletions custom_components/webhook_service/translations/en.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"config": {
"step": {
"user": {
"description": "Do you want to add Webhook Service?"
}
},
"abort": {
"single_instance_allowed": "Only single instance is allowed."
}
}
}
16 changes: 16 additions & 0 deletions custom_components/webhook_service/webhook_functions/basic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import logging
import requests
import json

_LOGGER = logging.getLogger(__name__)

def basic_webhook(call):
data = call.data.copy()
if "json" in data:
jsondata = json.loads(data["json"])
elif "jsonObj" in data:
jsondata = data["jsonObj"]
else:
jsondata = {}
result = requests.post(data["webhook"], json = jsondata)
_LOGGER.warn('Received data', data["webhook"])
60 changes: 60 additions & 0 deletions custom_components/webhook_service/webhook_functions/discord.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import logging
import requests
import json

_LOGGER = logging.getLogger(__name__)

def discord_webhook(call):
data = call.data.copy()
title = data.get("title", "Embed Title")
title_url = data.get("title_url")
description = data.get("description", "Embed Description")
thumbnail = data.get("thumbnail")
author = data.get("author")
fields = data.get("fields")
image = data.get("image")
color = data.get("color")
timestamp = data.get("timestamp")
footer = data.get("footer")
webhook_url = data.get("webhook")
if not webhook_url:
_LOGGER.error("No webhook URL provided.")
return

output_data = {
"title": title,
"description": description
}

if title_url:
output_data["url"] = title_url
if thumbnail:
output_data["thumbnail"] = thumbnail
if author:
try:
output_data["author"] = json.loads(str(author))
except Exception as e:
_LOGGER.error(e)
if fields:
try:
output_data["fields"] = json.loads(str(fields))[:25]
except Exception as e:
_LOGGER.error(e)
if image:
output_data["image"] = image
if color:
output_data["color"] = color
if timestamp:
output_data["timestamp"] = timestamp
if footer:
output_data["footer"] = footer

embed_data = {
"embeds": [output_data]
}

result = requests.post(webhook_url, json=embed_data)
if result.status_code == 200:
_LOGGER.info("Embed sent successfully.")
else:
_LOGGER.error("Failed to send embed: %s", result.text)
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
from .basic import basic_webhook
from .discord import discord_webhook

0 comments on commit 58ad866

Please sign in to comment.