v5 inital commit

This commit is contained in:
Thomas Sickert 2022-08-21 11:57:14 -04:00
parent ceada18383
commit cfabd065ad
30 changed files with 18937 additions and 297 deletions

4
.eslintignore Normal file
View file

@ -0,0 +1,4 @@
dist/
lib/
node_modules/
jest.config.js

55
.eslintrc.json Normal file
View file

@ -0,0 +1,55 @@
{
"plugins": ["jest", "@typescript-eslint"],
"extends": ["plugin:github/recommended"],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 9,
"sourceType": "module",
"project": "./tsconfig.json"
},
"rules": {
"i18n-text/no-en": "off",
"eslint-comments/no-use": "off",
"import/no-namespace": "off",
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": "error",
"@typescript-eslint/explicit-member-accessibility": ["error", {"accessibility": "no-public"}],
"@typescript-eslint/no-require-imports": "error",
"@typescript-eslint/array-type": "error",
"@typescript-eslint/await-thenable": "error",
"@typescript-eslint/ban-ts-comment": "error",
"camelcase": "off",
"@typescript-eslint/consistent-type-assertions": "error",
"@typescript-eslint/explicit-function-return-type": ["error", {"allowExpressions": true}],
"@typescript-eslint/func-call-spacing": ["error", "never"],
"@typescript-eslint/no-array-constructor": "error",
"@typescript-eslint/no-empty-interface": "error",
"@typescript-eslint/no-explicit-any": "error",
"@typescript-eslint/no-extraneous-class": "error",
"@typescript-eslint/no-for-in-array": "error",
"@typescript-eslint/no-inferrable-types": "error",
"@typescript-eslint/no-misused-new": "error",
"@typescript-eslint/no-namespace": "error",
"@typescript-eslint/no-non-null-assertion": "warn",
"@typescript-eslint/no-unnecessary-qualifier": "error",
"@typescript-eslint/no-unnecessary-type-assertion": "error",
"@typescript-eslint/no-useless-constructor": "error",
"@typescript-eslint/no-var-requires": "error",
"@typescript-eslint/prefer-for-of": "warn",
"@typescript-eslint/prefer-function-type": "warn",
"@typescript-eslint/prefer-includes": "error",
"@typescript-eslint/prefer-string-starts-ends-with": "error",
"@typescript-eslint/promise-function-async": "error",
"@typescript-eslint/require-array-sort-compare": "error",
"@typescript-eslint/restrict-plus-operands": "error",
"semi": "off",
"@typescript-eslint/semi": ["error", "never"],
"@typescript-eslint/type-annotation-spacing": "error",
"@typescript-eslint/unbound-method": "error"
},
"env": {
"node": true,
"es6": true,
"jest/globals": true
}
}

1
.gitattributes vendored Normal file
View file

@ -0,0 +1 @@
dist/** -diff linguist-generated=true

11
.github/dependabot.yml vendored Normal file
View file

@ -0,0 +1,11 @@
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: daily
- package-ecosystem: npm
directory: /
schedule:
interval: daily

53
.github/workflows/check-dist.yml vendored Normal file
View file

@ -0,0 +1,53 @@
# `dist/index.js` is a special file in Actions.
# When you reference an action with `uses:` in a workflow,
# `index.js` is the code that will run.
# For our project, we generate this file through a build process from other source files.
# We need to make sure the checked-in `index.js` actually matches what we expect it to be.
name: Check dist/
on:
push:
branches:
- main
paths-ignore:
- '**.md'
pull_request:
paths-ignore:
- '**.md'
workflow_dispatch:
jobs:
check-dist:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set Node.js 16.x
uses: actions/setup-node@v3.4.1
with:
node-version: 16.x
- name: Install dependencies
run: npm ci
- name: Rebuild the dist/ directory
run: |
npm run build
npm run package
- name: Compare the expected and actual dist/ directories
run: |
if [ "$(git diff --ignore-space-at-eol dist/ | wc -l)" -gt "0" ]; then
echo "Detected uncommitted changes after build. See status below:"
git diff
exit 1
fi
id: diff
# If index.js was different than expected, upload the expected version as an artifact
- uses: actions/upload-artifact@v3
if: ${{ failure() && steps.diff.conclusion == 'failure' }}
with:
name: dist
path: dist/

71
.github/workflows/codeql-analysis.yml vendored Normal file
View file

@ -0,0 +1,71 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"
on:
push:
branches: [ main ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ main ]
schedule:
- cron: '31 7 * * 3'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'TypeScript' ]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
# Learn more about CodeQL language support at https://git.io/codeql-language-support
steps:
- name: Checkout repository
uses: actions/checkout@v3
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
source-root: src
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v2
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2

View file

@ -1,33 +0,0 @@
name: Operating System Compatability Test
on:
workflow_dispatch:
inputs:
action_version:
description: Version
default: v4.0.0
type: string
required: false
jobs:
test-all-os:
strategy:
matrix:
os:
- windows-latest
- windows-2022
- windows2019
- ubuntu-22.04
- ubuntu-20.04
- ubuntu-18.04
- macos-12
- macos-11
- macos-10.15
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
- name: Discord Webhook Action
uses: tsickert/discord-webhook@${{ github.event.inputs.action_version }}
with:
webhook-url: ${{ secrets.WEBHOOK_URL }}
content: Foobar

74
.github/workflows/test.yml vendored Normal file
View file

@ -0,0 +1,74 @@
name: "Build + Test"
on:
pull_request:
push:
branches:
- main
- 'releases/*'
workflow_dispatch:
jobs:
build: # make sure build/ci work properly
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- run: |
npm install
- run: |
npm run all
test: # make sure the action works on a clean machine without building
strategy:
matrix:
os:
- windows-latest
- windows-2022
- windows2019
- ubuntu-22.04
- ubuntu-20.04
- ubuntu-18.04
- macos-12
- macos-11
- macos-10.15
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- name: Basic Content Test
uses: ./
with:
webhook-url: ${{ secrets.WEBHOOK_URL }}
content: test
- name: Test `@ping`
uses: ./
with:
webhook-url: ${{ secrets.WEBHOOK_URL }}
content: Hey there <@211894927997534208>
- name: Test with JSON Payload Provided
uses: ./
with:
webhook-url: ${{ secrets.WEBHOOK_URL }}
raw-data: __tests__/data/content-only.json
- name: Upload File
uses: ./
with:
webhook-url: ${{ secrets.WEBHOOK_URL }}
filename: __tests__/data/content-only.json
username: Bill
content: You should definintely be able to do this
avatar-url: https://cdn.discordapp.com/avatars/742807869023322232/dd41912939ffccbea0276f70688fa0ec.webp?size=256
- name: Discord Webhook Action With Embed
uses: ./
with:
webhook-url: ${{ secrets.WEBHOOK_URL }}
username: Bill
avatar-url: https://cdn.discordapp.com/avatars/742807869023322232/dd41912939ffccbea0276f70688fa0ec.webp?size=256
embed-title: "Foo"
embed-description: "Bar [test](https://google.com)"
embed-author-name: "Bill"
embed-author-icon-url: "https://cdn.discordapp.com/avatars/742807869023322232/dd41912939ffccbea0276f70688fa0ec.webp?size=256"
embed-author-url: "https://google.com"
embed-thumbnail-url: "https://cdn.discordapp.com/avatars/742807869023322232/dd41912939ffccbea0276f70688fa0ec.webp?size=256"
embed-image-url: "https://cdn.discordapp.com/avatars/742807869023322232/dd41912939ffccbea0276f70688fa0ec.webp?size=256"
embed-footer-icon-url: "https://cdn.discordapp.com/avatars/742807869023322232/dd41912939ffccbea0276f70688fa0ec.webp?size=256"
embed-footer-text: "Foot text [test](https://google.com)"
embed-color: 15430476
embed-timestamp: "2021-09-24T02:17:53+0000"

102
.gitignore vendored
View file

@ -1,3 +1,99 @@
*.idea
.history
__pycache__
# Dependency directory
node_modules
# Rest pulled from https://github.com/github/gitignore/blob/master/Node.gitignore
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# next.js build output
.next
# nuxt.js build output
.nuxt
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# OS metadata
.DS_Store
Thumbs.db
# Ignore built ts files
__tests__/runner/*
lib/**/*

3
.prettierignore Normal file
View file

@ -0,0 +1,3 @@
dist/
lib/
node_modules/

10
.prettierrc.json Normal file
View file

@ -0,0 +1,10 @@
{
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"semi": false,
"singleQuote": true,
"trailingComma": "none",
"bracketSpacing": false,
"arrowParens": "avoid"
}

View file

@ -1,7 +0,0 @@
FROM ghcr.io/tsickert/python
ADD webhook.py /webhook.py
RUN chmod 755 /webhook.py
ENTRYPOINT ["python3", "/webhook.py" ]

22
LICENSE Normal file
View file

@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2018 GitHub, Inc. and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -165,7 +165,7 @@ Add file to your repository or workspace via an action (for this example, this f
- uses: actions/checkout@v2
```
This will allow the action see any files from the repository in the workspace.
This will allow the action see any files from the repository in the workspace.
The final action will look something like this:
@ -195,11 +195,11 @@ jobs:
**Q**: Help, something is wrong, my webhook isn't sending!
**A**: Sorry to hear that! The discord webhook API is complicated and has a long list of conditions and restrictions.
The implementation of the webhook provides a few guard rails against misuse, but does not protect against them all.
Restrictions are set by Discord and may change--therefore the Discord API should ultimately be the source of truth for
those restrictions. If you run into issues, please be sure to check the action outputs. The payload is printed there,
so feel free to use it with curl or postman to first validate that the issue is not with the payload. If it's not,
**A**: Sorry to hear that! The discord webhook API is complicated and has a long list of conditions and restrictions.
The implementation of the webhook provides a few guard rails against misuse, but does not protect against them all.
Restrictions are set by Discord and may change--therefore the Discord API should ultimately be the source of truth for
those restrictions. If you run into issues, please be sure to check the action outputs. The payload is printed there,
so feel free to use it with curl or postman to first validate that the issue is not with the payload. If it's not,
please open an issue in this repository and I'll take a look!
**Q**: What does "Near-full" support of the webhook API mean?

View file

@ -0,0 +1,3 @@
{
"content": "Content-only `rawdata` test"
}

View file

@ -0,0 +1,6 @@
import {executeWebhook} from '../src/webhook'
import {expect, test} from '@jest/globals'
test('fails with missing URL', async () => {
await expect(executeWebhook()).rejects.toThrow('Invalid URL')
})

View file

@ -11,7 +11,7 @@ inputs:
content:
description: 'Message that is sent via the webhook.'
required: true
username:
username:
description: 'The username that should appear to send the message. Note: username will have the "bot" badge next to their name.'
required: false
avatar-url:
@ -60,40 +60,5 @@ inputs:
description: 'Embed author icon'
required: false
runs:
using: 'docker'
image: 'Dockerfile'
args:
- -w
- ${{ inputs.webhook-url }}
- -c
- ${{ inputs.content }}
- -u
- ${{ inputs.username }}
- -a
- ${{ inputs.avatar-url }}
- -d
- ${{ inputs.raw-data }}
- -f
- ${{ inputs.filename }}
- --embed-title
- ${{ inputs.embed-title }}
- --embed-description
- ${{ inputs.embed-description }}
- --embed-timestamp
- ${{ inputs.embed-timestamp }}
- --embed-color
- ${{ inputs.embed-color }}
- --embed-footer-text
- ${{ inputs.embed-footer-text }}
- --embed-footer-icon-url
- ${{ inputs.embed-footer-icon-url }}
- --embed-image-url
- ${{ inputs.embed-image-url }}
- --embed-thumbnail-url
- ${{ inputs.embed-thumbnail-url }}
- --embed-author-name
- ${{ inputs.embed-author-name }}
- --embed-author-url
- ${{ inputs.embed-author-url }}
- --embed-author-icon-url
- ${{ inputs.embed-author-icon-url }}
using: 'node16'
main: 'dist/index.js'

BIN
dist/index.js generated vendored Normal file

Binary file not shown.

BIN
dist/index.js.map generated vendored Normal file

Binary file not shown.

BIN
dist/licenses.txt generated vendored Normal file

Binary file not shown.

BIN
dist/sourcemap-register.js generated vendored Normal file

Binary file not shown.

9
jest.config.js Normal file
View file

@ -0,0 +1,9 @@
module.exports = {
clearMocks: true,
moduleFileExtensions: ['js', 'ts'],
testMatch: ['**/*.test.ts'],
transform: {
'^.+\\.ts$': 'ts-jest'
},
verbose: true
}

18293
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

46
package.json Normal file
View file

@ -0,0 +1,46 @@
{
"name": "typescript-action",
"version": "0.0.0",
"private": true,
"description": "TypeScript template action",
"main": "lib/webhook.js",
"scripts": {
"build": "tsc",
"format": "prettier --write '**/*.ts'",
"format-check": "prettier --check '**/*.ts'",
"lint": "eslint src/**/*.ts",
"package": "ncc build --source-map --license licenses.txt",
"test": "jest",
"all": "npm run build && npm run format && npm run lint && npm run package && npm test"
},
"repository": {
"type": "git",
"url": "git+https://github.com/actions/typescript-action.git"
},
"keywords": [
"actions",
"node",
"setup"
],
"author": "",
"license": "MIT",
"dependencies": {
"@actions/core": "^1.6.0",
"@actions/http-client": "^2.0.1",
"form-data": "^4.0.0"
},
"devDependencies": {
"@types/node": "^18.7.8",
"@typescript-eslint/eslint-plugin": "^5.33.1",
"@typescript-eslint/parser": "^5.33.1",
"@vercel/ncc": "^0.34.0",
"eslint": "^7.32.0",
"eslint-plugin-github": "^4.3.2",
"eslint-plugin-jest": "^25.3.2",
"jest": "^27.2.5",
"js-yaml": "^4.1.0",
"prettier": "2.7.1",
"ts-jest": "^27.1.2",
"typescript": "^4.7.4"
}
}

156
src/webhook.ts Normal file
View file

@ -0,0 +1,156 @@
import * as core from '@actions/core'
import {createReadStream, readFileSync} from 'fs'
import FormData from 'form-data'
import {HttpClient} from '@actions/http-client'
import {TypedResponse} from '@actions/http-client/lib/interfaces'
const WEBHOOK_URL = 'webhook-url'
const CONTENT = 'content'
const USERNAME = 'username'
const AVATAR_URL = 'avatar-url'
const RAW_DATA = 'raw-data'
const TITLE = 'title'
const DESCRIPTION = 'description'
const TIMESTAMP = 'timestamp'
const COLOR = 'color'
const NAME = 'name'
const URL = 'url'
const ICON_URL = 'icon-url'
const TEXT = 'text'
const FILENAME = 'filename'
const TOP_LEVEL_WEBHOOK_KEYS = [CONTENT, USERNAME, AVATAR_URL]
const EMBED_KEYS = [TITLE, DESCRIPTION, TIMESTAMP, COLOR]
const EMBED_AUTHOR_KEYS = [NAME, URL, ICON_URL]
const EMBED_FOOTER_KEYS = [TEXT, ICON_URL]
const EMBED_IMAGE_KEYS = [URL]
const EMBED_THUMBNAIL_KEYS = [URL]
function createPayload(): Record<string, unknown> {
// If raw-data provided, load the file and ignore the other parameters
const rawData = core.getInput(RAW_DATA)
if (rawData.length > 0) {
return JSON.parse(readFileSync(rawData, 'utf-8'))
}
const webhookPayloadMap = parseMapFromParameters(TOP_LEVEL_WEBHOOK_KEYS)
const embedPayloadMap = createEmbedObject()
if (embedPayloadMap.size > 0) {
webhookPayloadMap.set('embeds', [Object.fromEntries(embedPayloadMap)])
}
const webhookPayload = Object.fromEntries(webhookPayloadMap)
core.info(JSON.stringify(webhookPayload))
return webhookPayload
}
function createEmbedObject(): Map<string, unknown> {
const embedPayloadMap = parseMapFromParameters(EMBED_KEYS, 'embed')
if (embedPayloadMap.size > 0) {
const embedAuthorMap = parseMapFromParameters(
EMBED_AUTHOR_KEYS,
'embed-author'
)
if (embedAuthorMap.size > 0) {
embedPayloadMap.set('author', Object.fromEntries(embedPayloadMap))
}
const embedFooterMap = parseMapFromParameters(
EMBED_FOOTER_KEYS,
'embed-footer'
)
if (embedFooterMap.size > 0) {
embedPayloadMap.set('footer', Object.fromEntries(embedFooterMap))
}
const embedImageMap = parseMapFromParameters(
EMBED_IMAGE_KEYS,
'embed-image'
)
if (embedImageMap.size > 0) {
embedPayloadMap.set('image', Object.fromEntries(embedImageMap))
}
const embedThumbnailMap = parseMapFromParameters(
EMBED_THUMBNAIL_KEYS,
'embed-thumbnail'
)
if (embedThumbnailMap.size > 0) {
embedPayloadMap.set('thumbnail', Object.fromEntries(embedThumbnailMap))
}
}
return embedPayloadMap
}
function parseMapFromParameters(
parameters: string[],
inputObjectKey = ''
): Map<string, unknown> {
// Parse action inputs into discord webhook execute payload
const parameterMap = new Map<string, unknown>()
core.info(`inputObjectKey: ${inputObjectKey}`)
for (const parameter of parameters) {
const inputKey =
inputObjectKey !== '' ? `${inputObjectKey}-${parameter}` : parameter
let value = core.getInput(inputKey)
if (value === '') {
continue
}
if (parameter === TIMESTAMP) {
const parsedDate = new Date(value)
value = parsedDate.toISOString()
}
core.info(`${inputKey}: ${value}`)
if (value.length > 0) parameterMap.set(parameter.replace('-', '_'), value)
}
return parameterMap
}
async function handleResponse(response: TypedResponse<unknown>): Promise<void> {
core.info(
`Webhook returned ${response.statusCode} with message: ${response.result}. Please see discord documentation at https://discord.com/developers/docs/resources/webhook#execute-webhook for more information`
)
if (response.statusCode >= 400) {
core.error(
'Discord Webhook Action failed to execute webhook. Please see logs above for details. Error printed below:'
)
core.error(JSON.stringify(response))
}
}
export async function executeWebhook(): Promise<void> {
const client = new HttpClient()
const webhookUrl = core.getInput(WEBHOOK_URL)
const filename = core.getInput(FILENAME)
const payload = createPayload()
if (filename !== '') {
const formData = new FormData()
formData.append('upload-file', createReadStream(filename))
formData.append('payload_json', JSON.stringify(payload))
formData.submit(webhookUrl, function (error, response) {
if (error != null) {
core.error(`failed to upload file: ${error.message}`)
} else {
core.info(
`successfully uploaded file with status code: ${response.statusCode}`
)
}
})
} else {
const response = await client.postJson(webhookUrl, payload)
await handleResponse(response)
}
}
async function run(): Promise<void> {
try {
core.info('Running discord webhook action...')
await executeWebhook()
} catch (error) {
if (error instanceof Error) core.setFailed(error.message)
}
}
run()

View file

@ -1,18 +0,0 @@
#!/bin/bash
if [ "$#" -ne 1 ]; then
echo "Illegal number of parameters"
fi
DISCORD_WEBHOOK_URL=$1
python3 webhook.py -w "$DISCORD_WEBHOOK_URL" -c "Just Content"
python3 webhook.py -w "$DISCORD_WEBHOOK_URL" -c "With User" -u "User"
python3 webhook.py -w "$DISCORD_WEBHOOK_URL" -c "Test" -u "User with Avatar" -a https://github.com/tsickert.png
python3 webhook.py -w "$DISCORD_WEBHOOK_URL" -c "Test" -u "User with File" -f test/test.json
python3 webhook.py -w "$DISCORD_WEBHOOK_URL" -c "Test" -u "User with File and Embed (multi-message behavior)" -f test/test.json --embed-title "Test"
python3 webhook.py -w "$DISCORD_WEBHOOK_URL" -u "User with File and Embed with Color (multi-message behavior)" -f test/test.json --embed-color 1752220 --embed-title "Yay"
python3 webhook.py -w "$DISCORD_WEBHOOK_URL" -d test/test.json
#python3 webhook.py -w "$DISCORD_WEBHOOK_URL" -u "User with File and Embed with Color (multi-message behavior)" -f test/test.json --embed-color 1752220

View file

@ -1 +0,0 @@
test file contents

View file

@ -1,4 +0,0 @@
{
"content": "See greeting below",
"embeds": [{"title":"Hello","description":"World"}]
}

12
tsconfig.json Normal file
View file

@ -0,0 +1,12 @@
{
"compilerOptions": {
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"outDir": "./lib", /* Redirect output structure to the directory. */
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
},
"exclude": ["node_modules", "**/*.test.ts"]
}

View file

@ -1,187 +0,0 @@
import datetime
import requests
import argparse
import json
DISCORD_EMBED_LIMIT = 1
DISCORD_INFORMATION = """
This action executes discord webhooks. Discord has a lot of conditions on the proper structure of webhooks. For a full
list of those conditions, please see: https://discord.com/developers/docs/resources/webhook#execute-webhook.
When debugging this workflow, please be sure to check the status code and the message and check for answers from discord
initially. If you believe that this action failed because of a bug, or you would like to add functionality,
please feel free to open an issue in https://github.com/tsickert/discord-webhook/issues.
Thanks for using this action!
"""
# Actions provide arguments as empty strings
def present(field):
return field is not None and field != ""
def has_values(obj: dict):
values = list(obj.values())
for value in values:
if present(value):
return obj
return None
def construct_author(args, index):
return {
'name': args[f'embed_{index}author_name'],
'url': args[f'embed_{index}author_url'],
'icon_url': args[f'embed_{index}author_icon_url']
}
def construct_footer(args, index):
return {
'text': args[f'embed_{index}footer_text'],
'icon_url': args[f'embed_{index}footer_icon_url']
}
def construct_payload(args):
if present(args['raw_data']):
data_file = open(args['raw_data'])
payload = json.load(data_file)
else:
payload = {}
if present(args['content']):
payload['content'] = args['content']
if present(args['username']):
payload['username'] = args['username']
if present(args['avatar_url']):
payload['avatar_url'] = args['avatar_url']
if present(args['tts']):
payload['tts'] = args['tts']
for i in range(DISCORD_EMBED_LIMIT):
index = ''
if i > 0:
index = f'{i + 1}_'
embed = {}
title = args[f'embed_{index}title']
if present(title):
embed['title'] = title
footer = construct_footer(args, index)
if has_values(footer):
embed['footer'] = footer
description = args[f'embed_{index}description']
if present(description):
embed['description'] = description
timestamp = args[f'embed_{index}timestamp']
if present(timestamp):
date = datetime.datetime.strptime(timestamp, '%m/%d/%Y %H:%M:%S')
embed['timestamp'] = date.isoformat()
color = args[f'embed_{index}color']
if present(color):
embed['color'] = color
image_url = args[f'embed_{index}image_url']
if present(image_url):
embed['image'] = {'url': image_url}
thumbnail_url = args[f'embed_{index}thumbnail_url']
if present(thumbnail_url):
embed['thumbnail'] = {'url': thumbnail_url}
author = construct_author(args, index)
if has_values(author):
embed['author'] = author
if has_values(embed):
if 'embeds' not in payload:
payload['embeds'] = []
payload['embeds'].append(embed)
return payload
def split_payload_for_multi_message(payload: dict):
embed_payload = {'embeds': payload.pop('embeds')}
if 'username' in payload:
embed_payload['username'] = payload['username']
if 'avatar_url' in payload:
embed_payload['avatar_url'] = payload['avatar_url']
# TODO: Not sure if embed only messages will be read with text to speech, find out
if 'tts' in payload:
embed_payload['tts'] = payload['tts']
return payload, embed_payload
def execute_webhook(payload, filename=None):
print(payload)
# Use multipart/form-data
if present(filename):
if 'embeds' in payload:
payload, embeds_payload = split_payload_for_multi_message(payload)
execute_webhook(embeds_payload)
response = requests.post(args['webhook'], data=payload, files={'upload_file': open(filename, 'rb')})
# Use application/json
else:
response = requests.post(args['webhook'], json=payload)
handle_response(response)
def handle_response(response):
print(f'Webhook returned {response.status_code} with message: {response.content}. '
f'Please see discord documentation at https://discord.com/developers/docs/resources/webhook#execute-webhook '
f'for more information')
if response.status_code >= 400:
print('Discord Webhook Action failed to execute webhook. Please see logs above for details.')
exit(1)
def add_embed_arguments(p: argparse.ArgumentParser, num: int = DISCORD_EMBED_LIMIT):
for i in range(num):
index = ''
if i > 0:
index = f'{i + 1}-'
p.add_argument(f'--embed-{index}title')
p.add_argument(f'--embed-{index}description')
p.add_argument(f'--embed-{index}timestamp')
p.add_argument(f'--embed-{index}color')
p.add_argument(f'--embed-{index}footer-text')
p.add_argument(f'--embed-{index}footer-icon-url')
p.add_argument(f'--embed-{index}image-url')
p.add_argument(f'--embed-{index}thumbnail-url')
p.add_argument(f'--embed-{index}author-name')
p.add_argument(f'--embed-{index}author-url')
p.add_argument(f'--embed-{index}author-icon-url')
# TODO: fields
# p.add_argument(f'--embed-{index}fields')
if __name__ == "__main__":
print(DISCORD_INFORMATION)
# Register arguments
parser = argparse.ArgumentParser(description='Call Discord Webhooks.')
parser.add_argument('-w', '--webhook', type=str, required=True)
parser.add_argument('-c', '--content', type=str, required=False)
parser.add_argument('-u', '--username', type=str, required=False)
parser.add_argument('-a', '--avatar-url', type=str, required=False)
parser.add_argument('-t', '--tts', type=bool, required=False)
parser.add_argument('-f', '--filename', type=str, required=False)
add_embed_arguments(parser)
# TODO: allowed mentions
# TODO: rename raw-data to something less curl-y and more discord-y
parser.add_argument('-d', '--raw-data', type=str, required=False)
args = vars(parser.parse_args())
payload = construct_payload(args)
execute_webhook(payload, args['filename'])