NAME
WebService::Discord::Webhook - A module for posting messages to Discord chat service
VERSION
version 1.10
SYNOPSIS
use WebService::Discord::Webhook;
my $webhook = WebService::Discord::Webhook->new( $url );
$webhook->get();
print "Webhook posting as '" . $webhook->{name} .
"' in channel " . $webhook->{channel_id} . "\n";
$webhook->execute( content => 'Hello, world!', tts => 1 );
sleep(30);
$webhook->execute( 'Goodbye, world!' );
DESCRIPTION
This module posts messages to the Discord chat service, using their Webhook interface. Webhooks are a simple way to add post-only functions to external clients, without the need to create a full-fledged client or "bot".
Normally, Webhooks are used to issue a notification to chat channels when an external event from another site or service occurs, e.g. when a commit is made to a Git repository, a story is posted to a news site, or a player is fragged in a game.
An example Discord Webhook URL looks like this:
https://discord.com/api/webhooks/2237...5344/3d89...cf11
where the first magic number ("2237...5344") is the id
and the second ("3d89...cf11") is the token
.
For more information on Discord Webhooks, see the Discord API documentation located at https://discord.com/developers/docs/resources/webhook.
METHODS
new
Constructs and returns a new WebService::Discord::Webhook object using the specified parameters.
This function should be passed a hash, containing either a url
key, or token
plus id
keys, with values matching the Webhook created via the Discord web UI.
The following optional parameters are also available:
timeout
Override the default timeout of the underlying HTTP::Tiny object used for making web requests.
verify_SSL
Enable SSL certificate verification on the underlying HTTP::Tiny object. Note that this will probably require a trusted CA certificate list installed.
wait
Webhook execution will block before returning, until the server confirms that he message was sent. By default this is disabled (webhook execution is NOT synchronized), so the function may return success although a message does not actually post. See
execute
for more details.
As a special case, if new
is called with a scalar parameter, it is assumed to be a url
.
get
Retrieves server-side information for the Webhook, and caches the result in the WebService::Discord::Webhook object. No parameters are expected.
Information which can be returned from the remote service include:
guild_id: The guild ("server") which the Webhook currently posts to, if set
channel_id: The specific channel which the Webhook posts to
name: The current display name of the Webhook
avatar: A URL pointing to the current avatar used by the Webhook
A hash containing the data is returned. Additionally, the hash values are copied into the object itself, so they can be later retrieved by calling code (as in $webhook->{channel_id}
).
modify
Modifies the server-side information for the Webhook. This can be used to alter the name the Webhook uses, the avatar, or both.
This function should be passed a hash, containing (at least) a name
key or avatar
key (or both).
For avatar
, the value should be the raw data bytes of a png, jpeg, or gif image.
As a special case, if modify
is called with a scalar parameter, it is assumed to be a new username.
The return value for this function is the same as get
, and the results are also cached as above.
destroy
Deletes the Webhook from the Discord service. There is no return value.
Warning! Once a Webhook is deleted, the existing token and ID are no longer valid. A server administrator will need to re-create the endpoint through the Discord UI. Unless you have very good reason to do this, it is probably best to leave this function alone.
execute
Executes a Webhook (posts a message).
The function should be passed a hash containing a Discord webhook structure. Discord allows several different methods to post to a channel. At least one of the following components is required:
content
Post a message to the channel. The message can be up to 2000 Unicode characters in length. Discord may format the message after receipt according to its usual Markdown rules.
The value should be a scalar containing the message to post.
content
can be combined with the other post methods as well, to attach a message along with an embed or file.file
Upload a file to the channel.
The value should be a hash reference with two keys:
name
for the desired filename, anddata
for the raw data bytes of the file. Discord uses the file extension to determine whether to display it as an image, video, download, etc.file
cannot be combined withembed
.files
Similar to
file
, but accepts an array of file hashref instead. (Do not combinefile
withfiles
.)Discord allows up to 10 file attachments in one request.
embed
Post "embedded rich content" to the channel. This is useful for posting messages with image attachments, colorful borders or backgrounds, etc.
The value should be an embed object (hashref) to post. These values are not checked by WebService::Discord::Webhook. For information on the expected data structure, refer to Discord's documentation on Channel Embed Objects: https://discord.com/developers/docs/resources/channel#embed-object
embed
cannot be combined withfile
.embeds
Similar to
embed
, but accepts an array of embed hashref instead. (Do not combineembed
withembeds
.)
Additionally, these optional parameters can be used to change the behavior of the webhook:
username: Override the default username of the webhook (i.e. post this message under a different name). To make a permanent username change, see
modify
.avatar_url: Override the default avatar of the webhook (i.e. post this message using the avatar at avatar_url). To upload a new avatar to Discord, see
modify
.tts: If set, posts as a TTS message. TTS messages appear as normal, but will also be read aloud to users in the channel (if permissions allow).
allowed_mentions: Customize behavior of pings ("at mentions") in a message. By default, Discord will parse the message content looking for users, roles, and groups to notify. Sometimes this is undesired - for example, when reposting content into the channel, it would be impolite to let a news summary that includes "@everyone" to ping the entire channel. This parameter instructs Discord on how to correctly parse (or suppress) mentions from the posted message.
The value should be an allowed_mentions object (hashref) to post. These values are not checked by WebService::Discord::Webhook. For details about the data structure, refer to Discord's documentation on Allowed Mentions Objects: https://discord.com/developers/docs/resources/channel#allowed-mentions-object
As a special case, if a scalar is passed to this function, it is assumed to be a regular text message to post via the "content" method.
The return value for this function depends on the setting of wait
during webhook construction. If wait
is False (default), the function returns immediately: parameters are checked for validity, but no attempt is made to verify that the message actually posted to the channel. There is no return value in this case.
If wait
is True, function return is delayed until the message successfully posts. The return value in this case is a hashref containing details about the posted message.
execute_slack
Executes a Slack-compatible Webhook.
The function should be passed either a scalar (assumed to be the JSON string contents of the Slack webhook), or a hash containing a Slack webhook structure (will be encoded to JSON using JSON::PP
).
More information about the format of a Slack webhook is available on the Slack API reference at https://api.slack.com/incoming-webhooks.
This function's return behavior is similar to execute()
, in that it is also affected by the value of wait
. Typically a Slack webhook returns the string "ok"
on success.
execute_github
Executes a Github-compatible Webhook.
The function should be passed a hash containing two keys: json
as the JSON string of a Github webhook, and event
as the string containing the name of the Github event. The value for event
is passed to Discord in the X-GitHub-Event
header.
More information about the format of a Github webhook is available on the Github API reference at https://developer.github.com/webhooks.
This function's return behavior is similar to execute()
, in that it is also affected by the value of wait
.
Note: Posting a message using the execute_github
function is currently a specially-cased feature of Discord. The webhook always appears as a user named "GitHub" with a custom avatar, ignoring any existing styling. Thus, it should NOT be used as a general-purpose posting function. However, it may be useful to proxy messages from GitHub and repost them on Discord.
ERRORS
All errors in WebService::Discord::Webhook are handled by throwing exceptions using croak()
. This includes both local errors (e.g. invalid parameters) as well as remote service errors (e.g. upload too large, name invalid).
Errors are returned as a single string. Some attempt is made to standardize the wording, so that they can be parsed by regex if the caller wants to inspect the error and retry or continue.
If you wish to trap errors, the traditional Perl way to catch the exceptions is to wrap them in an eval
block, as in:
my $result = eval {
$webhook->execute(...);
};
if ($@) {
# do something with the error here
warn "Execute failed with error: $@";
}
# execution continues...
Also consider using Try::Tiny, which provides the familiar try
/ catch
constructs to help with exception handling.
LICENSE
This is released under the Artistic License. See perlartistic.
AUTHOR
Greg Kennedy - https://greg-kennedy.com/