class Discord::Client

Overview

The basic client class that is used to connect to Discord, send REST requests, or send or receive gateway messages. It is required for doing any sort of interaction with Discord.

A new simple client that does nothing yet can be created like this:

client = Discord::Client.new(token: "Bot token", client_id: 123_u64)

With this client, REST requests can now be sent. (See the Discord::REST module.) A gateway connection can also be started using the #run method.

Included Modules

Defined in:

discordcr/client.cr

Constant Summary

DEFAULT_PROPERTIES = Gateway::IdentifyProperties.new(os: "Crystal", browser: "discordcr", device: "discordcr", referrer: "", referring_domain: "")

Default analytics properties sent in IDENTIFY

OP_DISPATCH = 0
OP_HEARTBEAT = 1
OP_HEARTBEAT_ACK = 11
OP_HELLO = 10
OP_IDENTIFY = 2
OP_INVALID_SESSION = 9
OP_RECONNECT = 7
OP_REQUEST_GUILD_MEMBERS = 8
OP_RESUME = 6
OP_STATUS_UPDATE = 3
OP_VOICE_SERVER_PING = 5
OP_VOICE_STATE_UPDATE = 4

Constructors

Instance Method Summary

Instance methods inherited from module Discord::REST

accept_invite(code : String) accept_invite, add_guild_member(guild_id : UInt64, user_id : UInt64, access_token : String, nick : String? = nil, roles : Array(UInt64)? = nil, mute : Bool? = nil, deaf : Bool? = nil) add_guild_member, add_guild_member_role(guild_id : UInt64, user_id : UInt64, role_id : UInt64) add_guild_member_role, add_pinned_channel_message(channel_id : UInt64 | Snowflake, message_id : UInt64 | Snowflake) add_pinned_channel_message, begin_guild_prune(guild_id : UInt64 | Snowflake, days : UInt32) begin_guild_prune, bulk_delete_messages(channel_id : UInt64 | Snowflake, message_ids : Array(UInt64 | Snowflake)) bulk_delete_messages, create_channel_invite(channel_id : UInt64 | Snowflake, max_age : UInt32 = 0_u32, max_uses : UInt32 = 0_u32, temporary : Bool = false) create_channel_invite, create_channel_webhook(channel_id : UInt64 | Snowflake, name : String, avatar : String) create_channel_webhook, create_dm(recipient_id : UInt64 | Snowflake) create_dm, create_guild_ban(guild_id : UInt64 | Snowflake, user_id : UInt64 | Snowflake) create_guild_ban, create_guild_channel(guild_id : UInt64 | Snowflake, name : String, type : ChannelType, bitrate : UInt32?, user_limit : UInt32?) create_guild_channel, create_guild_emoji(guild_id : UInt64 | Snowflake, name : String, image : String) create_guild_emoji, create_guild_integration(guild_id : UInt64 | Snowflake, type : String, id : UInt64 | Snowflake) create_guild_integration, create_guild_role(guild_id : UInt64 | Snowflake, name : String? = nil, permissions : Permissions? = nil, colour : UInt32 = 0_u32, hoist : Bool = false, mentionable : Bool = false) create_guild_role, create_message(channel_id : UInt64 | Snowflake, content : String, embed : Embed? = nil, tts : Bool = false) create_message, create_reaction(channel_id : UInt64 | Snowflake, message_id : UInt64 | Snowflake, emoji : String) create_reaction, delete_all_reactions(channel_id : UInt64 | Snowflake, message_id : UInt64 | Snowflake) delete_all_reactions, delete_channel(channel_id : UInt64 | Snowflake) delete_channel, delete_channel_permission(channel_id : UInt64 | Snowflake, overwrite_id : UInt64 | Snowflake) delete_channel_permission, delete_guild(guild_id : UInt64 | Snowflake) delete_guild, delete_guild_integration(guild_id : UInt64 | Snowflake, integration_id : UInt64 | Snowflake) delete_guild_integration, delete_guild_role(guild_id : UInt64 | Snowflake, role_id : UInt64 | Snowflake) delete_guild_role, delete_invite(code : String) delete_invite, delete_message(channel_id : UInt64 | Snowflake, message_id : UInt64 | Snowflake) delete_message, delete_own_reaction(channel_id : UInt64 | Snowflake, message_id : UInt64 | Snowflake, emoji : String) delete_own_reaction, delete_pinned_channel_message(channel_id : UInt64 | Snowflake, message_id : UInt64 | Snowflake) delete_pinned_channel_message, delete_user_reaction(channel_id : UInt64 | Snowflake, message_id : UInt64 | Snowflake, emoji : String, user_id : UInt64 | Snowflake) delete_user_reaction, delete_webhook(webhook_id : UInt64 | Snowflake, token : String)
delete_webhook(webhook_id : UInt64 | Snowflake)
delete_webhook
, edit_channel_permissions(channel_id : UInt64 | Snowflake, overwrite_id : UInt64 | Snowflake, type : String, allow : Permissions, deny : Permissions) edit_channel_permissions, edit_message(channel_id : UInt64 | Snowflake, message_id : UInt64 | Snowflake, content : String, embed : Embed? = nil) edit_message, execute_webhook(webhook_id : UInt64 | Snowflake, token : String, content : String? = nil, file : String? = nil, embeds : Array(Embed)? = nil, tts : Bool? = nil, avatar_url : String? = nil, username : String? = nil, wait : Bool? = false) execute_webhook, get_channel(channel_id : UInt64 | Snowflake) get_channel, get_channel_invites(channel_id : UInt64 | Snowflake) get_channel_invites, get_channel_message(channel_id : UInt64 | Snowflake, message_id : UInt64 | Snowflake) get_channel_message, get_channel_messages(channel_id : UInt64 | Snowflake, limit : UInt8 = 50, before : UInt64 | Snowflake | Nil = nil, after : UInt64 | Snowflak | Nil = nil, around : UInt64 | Snowflake | Nil = nil) get_channel_messages, get_channel_webhooks(channel_id : UInt64 | Snowflake) get_channel_webhooks, get_current_user get_current_user, get_current_user_guilds(limit : UInt8 = 100_u8, before : UInt64 | Snowflake = 0_u64, after : UInt64 | Snowflake = 0_u64) get_current_user_guilds, get_gateway get_gateway, get_gateway_bot get_gateway_bot, get_guild(guild_id : UInt64 | Snowflake) get_guild, get_guild_bans(guild_id : UInt64 | Snowflake) get_guild_bans, get_guild_channels(guild_id : UInt64 | Snowflake) get_guild_channels, get_guild_embed(guild_id : UInt64 | Snowflake) get_guild_embed, get_guild_emojis(guild_id : UInt64 | Snowflake) get_guild_emojis, get_guild_integrations(guild_id : UInt64 | Snowflake) get_guild_integrations, get_guild_member(guild_id : UInt64 | Snowflake, user_id : UInt64 | Snowflake) get_guild_member, get_guild_prune_count(guild_id : UInt64 | Snowflake, days : UInt32) get_guild_prune_count, get_guild_roles(guild_id : UInt64 | Snowflake) get_guild_roles, get_guild_vanity_url(guild_id : UInt64 | Snowflake) get_guild_vanity_url, get_guild_voice_regions(guild_id : UInt64 | Snowflake) get_guild_voice_regions, get_guild_webhooks(guild_id : UInt64 | Snowflake) get_guild_webhooks, get_invite(code : String) get_invite, get_oauth2_application get_oauth2_application, get_pinned_messages(channel_id : UInt64 | Snowflake) get_pinned_messages, get_reactions(channel_id : UInt64 | Snowflake, message_id : UInt64 | Snowflake, emoji : String) get_reactions, get_user(user_id : UInt64 | Snowflake) get_user, get_user_dms get_user_dms, get_users_connections get_users_connections, get_webhook(webhook_id : UInt64 | Snowflake, token : String)
get_webhook(webhook_id : UInt64 | Snowflake)
get_webhook
, leave_guild(guild_id : UInt64 | Snowflake) leave_guild, list_guild_members(guild_id : UInt64 | Snowflake, limit : Int32 = 1000, after : UInt64 | Snowflake = 0_u64) list_guild_members, list_voice_regions list_voice_regions, modify_channel(channel_id : UInt64 | Snowflake, name : String? = nil, position : UInt32? = nil, topic : String? = nil, bitrate : UInt32? = nil, user_limit : UInt32? = nil, nsfw : Bool? = nil) modify_channel, modify_current_user(username : String? = nil, avatar : String? = nil) modify_current_user, modify_current_user_nick(guild_id : UInt64, nick : String) modify_current_user_nick, modify_guild(guild_id : UInt64 | Snowflake, name : String? = nil, region : String? = nil, verification_level : UInt8? = nil, afk_channel_id : UInt64 | Snowflake | Nil = nil, afk_timeout : Int32? = nil, icon : String? = nil, owner_id : UInt64 | Snowflake | Nil = nil, splash : String? = nil) modify_guild, modify_guild_channel_positions(guild_id : UInt64 | Snowflake, positions : Array(ModifyChannelPositionPayload)) modify_guild_channel_positions, modify_guild_embed(guild_id : UInt64 | Snowflake, enabled : Bool, channel_id : UInt64 | Snowflake) modify_guild_embed, modify_guild_emoji(guild_id : UInt64 | Snowflake, emoji_id : UInt64 | Snowflake, name : String) modify_guild_emoji, modify_guild_integration(guild_id : UInt64 | Snowflake, integration_id : UInt64 | Snowflake, expire_behaviour : UInt8, expire_grace_period : Int32, enable_emoticons : Bool) modify_guild_integration, modify_guild_member(guild_id : UInt64 | Snowflake, user_id : UInt64 | Snowflake, nick : String? = nil, roles : Array(UInt64 | Snowflake)? = nil, mute : Bool? = nil, deaf : Bool? = nil, channel_id : UInt64 | Snowflake | Nil = nil) modify_guild_member, modify_guild_role(guild_id : UInt64 | Snowflake, role_id : UInt64 | Snowflake, name : String? = nil, permissions : Permissions? = nil, colour : UInt32? = nil, position : Int32? = nil, hoist : Bool? = nil) modify_guild_role, modify_guild_vanity_url(guild_id : UInt64 | Snowflake, code : String) modify_guild_vanity_url, modify_webhook(webhook_id : UInt64 | Snowflake, name : String? = nil, avatar : String? = nil, channel_id : UInt64 | Snowflake | Nil = nil) modify_webhook, modify_webhook_with_token(webhook_id : UInt64 | Snowflake, token : String, name : String? = nil, avatar : String? = nil) modify_webhook_with_token, raw_request(route_key : Symbol, major_parameter : Snowflake | UInt64 | Nil, method : String, path : String, headers : HTTP::Headers, body : String?) raw_request, remove_guild_ban(guild_id : UInt64 | Snowflake, user_id : UInt64 | Snowflake) remove_guild_ban, remove_guild_member(guild_id : UInt64 | Snowflake, user_id : UInt64 | Snowflake) remove_guild_member, remove_guild_member_role(guild_id : UInt64, user_id : UInt64, role_id : UInt64) remove_guild_member_role, request(route_key : Symbol, major_parameter : Snowflake | UInt64 | Nil, method : String, path : String, headers : HTTP::Headers, body : String?) request, sync_guild_integration(guild_id : UInt64 | Snowflake, integration_id : UInt64 | Snowflake) sync_guild_integration, trigger_typing_indicator(channel_id : UInt64 | Snowflake) trigger_typing_indicator, upload_file(channel_id : UInt64 | Snowflake, content : String?, file : IO, filename : String? = nil) upload_file

Constructor Detail

def self.new(token : String, client_id : UInt64? = nil, shard : Gateway::ShardKey? = nil, large_threshold : Int32 = 100, compress : Bool = false, properties : Gateway::IdentifyProperties = DEFAULT_PROPERTIES, logger = Logger.new(STDOUT)) #

Creates a new bot with the given token and optionally the client_id. Both of these things can be found on a bot's application page; the token will need to be revealed using the "click to reveal" thing on the token (not the OAuth2 secret!)

If the shard key is set, the gateway will operate in sharded mode. This means that this client's gateway connection will only receive packets from a part of the guilds the bot is connected to. See here for more information.

The large_threshold defines the minimum member count that, if a guild has at least that many members, the client will only receive online members in GUILD_CREATE. The default value 100 is what the Discord client uses; the maximum value is 250. To get a list of offline members as well, the #request_guild_members method can be used.

If compress is true, packets will be sent in a compressed manner. discordcr doesn't currently handle packet decompression, so until that is implemented, setting this to true will cause the client to fail to parse anything.

The properties define what values are sent to Discord as analytics properties. It's not recommended to change these from the default values, but if you desire to do so, you can.


[View source]

Instance Method Detail

def cache : Cache? #

If this is set to any Cache, the data in the cache will be updated as the client receives the corresponding gateway dispatches.


[View source]
def cache=(cache : Cache?) #

If this is set to any Cache, the data in the cache will be updated as the client receives the corresponding gateway dispatches.


[View source]
def client_id #

Returns this client's ID as provided in its associated Oauth2 application. A getter for @client_id, this will make a REST call to obtain it if it was not provided in the initializer.


[View source]
def inject(packet : Discord::WebSocket::Packet) #

Injects a packet into the packet handler.


[View source]
def on_channel_create(&handler : Channel -> ) #

Called when a channel has been created on a server the bot has access to, or when somebody has started a DM channel with the bot.

API docs for this event


[View source]
def on_channel_delete(&handler : Channel -> ) #

Called when a channel the bot has access to is deleted. This is not called for other users closing the DM channel with the bot, only for the bot closing the DM channel with a user.

API docs for this event


[View source]
def on_channel_pins_update(&handler : Gateway::ChannelPinsUpdatePayload -> ) #

Called when a channel's pinned messages are updated, where a pin was either added or removed.

API docs for this event


[View source]
def on_channel_update(&handler : Channel -> ) #

Called when a channel's properties are updated, like the name or permission overwrites.

API docs for this event


[View source]
def on_dispatch(&handler : ::Tuple(String, IO::Memory) -> ) #

Called when the bot receives any kind of dispatch at all, even one that is otherwise unsupported. This can be useful for statistics, e. g. how many gateway events are received per second. It can also be useful to handle new API changes not yet supported by the lib.

The parameter passed to the event will be a tuple of {type, data}, where type is the event type (e.g. "MESSAGE_CREATE") and data is the unprocessed JSON event data.


[View source]
def on_guild_ban_add(&handler : Gateway::GuildBanPayload -> ) #

Called when somebody is banned from a guild. A #on_guild_member_remove event is also called.

API docs for this event


[View source]
def on_guild_ban_remove(&handler : Gateway::GuildBanPayload -> ) #

Called when somebody is unbanned from a guild.

API docs for this event


[View source]
def on_guild_create(&handler : Gateway::GuildCreatePayload -> ) #

Called when the bot is added to a guild, a guild unavailable due to an outage becomes available again, or the guild is streamed after READY. To verify that it is the first case, you can check the unavailable property in Gateway::GuildCreatePayload.

API docs for this event


[View source]
def on_guild_delete(&handler : Gateway::GuildDeletePayload -> ) #

Called when the bot leaves a guild or a guild becomes unavailable due to an outage. To verify that it is the former case, you can check the unavailable property.

API docs for this event


[View source]
def on_guild_emoji_update(&handler : Gateway::GuildEmojiUpdatePayload -> ) #

Called when a guild's emoji are updated.

API docs for this event


[View source]
def on_guild_integrations_update(&handler : Gateway::GuildIntegrationsUpdatePayload -> ) #

Called when a guild's integrations (Twitch, YouTube) are updated.

API docs for this event


[View source]
def on_guild_member_add(&handler : Gateway::GuildMemberAddPayload -> ) #

Called when somebody other than the bot joins a guild.

API docs for this event


[View source]
def on_guild_member_remove(&handler : Gateway::GuildMemberRemovePayload -> ) #

Called when somebody other than the bot leaves a guild.

API docs for this event


[View source]
def on_guild_member_update(&handler : Gateway::GuildMemberUpdatePayload -> ) #

Called when a member object is updated. This happens when somebody changes their nickname or has their roles changed.

API docs for this event


[View source]
def on_guild_members_chunk(&handler : Gateway::GuildMembersChunkPayload -> ) #

Called when Discord sends a chunk of member objects after a #request_guild_members call. If a Cache is set up, this is handled automatically.

API docs for this event


[View source]
def on_guild_role_create(&handler : Gateway::GuildRolePayload -> ) #

Called when a role is created on a guild.

API docs for this event


[View source]
def on_guild_role_delete(&handler : Gateway::GuildRoleDeletePayload -> ) #

Called when a role is deleted.

API docs for this event


[View source]
def on_guild_role_update(&handler : Gateway::GuildRolePayload -> ) #

Called when a role's properties are updated, for example name or colour.

API docs for this event


[View source]
def on_guild_update(&handler : Guild -> ) #

Called when a guild's properties, like name or verification level, are updated.

API docs for this event


[View source]
def on_message_create(&handler : Message -> ) #

Called when a message is sent to a channel the bot has access to. This may be any sort of text channel, no matter private or guild.

API docs for this event


[View source]
def on_message_delete(&handler : Gateway::MessageDeletePayload -> ) #

Called when a single message is deleted.

API docs for this event


[View source]
def on_message_delete_bulk(&handler : Gateway::MessageDeleteBulkPayload -> ) #

Called when multiple messages are deleted at once, due to a bot using the bulk_delete endpoint.

API docs for this event


[View source]
def on_message_reaction_add(&handler : Gateway::MessageReactionPayload -> ) #

Called when a reaction is added to a message.


[View source]
def on_message_reaction_remove(&handler : Gateway::MessageReactionPayload -> ) #

Called when a reaction is removed from a message.


[View source]
def on_message_reaction_remove_all(&handler : Gateway::MessageReactionRemoveAllPayload -> ) #

Called when all reactions are removed at once from a message.


[View source]
def on_message_update(&handler : Gateway::MessageUpdatePayload -> ) #

Called when a message is updated. Most commonly this is done for edited messages, but the event is also sent when embed information for an existing message is updated.

API docs for this event


[View source]
def on_presence_update(&handler : Gateway::PresenceUpdatePayload -> ) #

Called when a user updates their status (online/idle/offline), the game they are playing, or their streaming status. Also called when a user's properties (user/avatar/discriminator) are changed.

API docs for this event


[View source]
def on_ready(&handler : Gateway::ReadyPayload -> ) #

Called when the bot has successfully initiated a session with Discord. It marks the point when gateway packets can be set (e. g. #status_update).

Note that this event may be called multiple times over the course of a bot lifetime, as it is also called when the client reconnects with a new session.

API docs for this event


[View source]
def on_resumed(&handler : Gateway::ResumedPayload -> ) #

Called when the client has successfully resumed an existing connection after reconnecting.

API docs for this event


[View source]
def on_typing_start(&handler : Gateway::TypingStartPayload -> ) #

Called when somebody starts typing in a channel the bot has access to.

API docs for this event


[View source]
def on_user_update(&handler : User -> ) #

Called when the user properties of the bot itself are changed.

API docs for this event


[View source]
def on_voice_server_update(&handler : Gateway::VoiceServerUpdatePayload -> ) #

Called when a guild's voice server changes. This event is called with the current voice server when initially connecting to voice, and it is called again with the new voice server when the current server fails over to a new one, or when the guild's voice region changes.

API docs for this event


[View source]
def on_voice_state_update(&handler : VoiceState -> ) #

Called when somebody joins or leaves a voice channel, moves to a different one, or is muted/unmuted/deafened/undeafened.

API docs for this event


[View source]
def on_webhooks_update(&handler : Gateway::WebhooksUpdatePayload -> ) #

Sent when a guild channel's webhook is created, updated, or deleted.

API docs for this event


[View source]
def reconnect(should_suspend = false, backoff_override = nil) #

Reconnects the websocket connection entirely. If should_suspend is set, the session will be suspended, which means (unless other factors prevent this) that the session will be resumed after reconnection. If backoff_override is set to anything other than nil, the reconnection backoff will not use the standard formula and instead wait the value provided; use 0.0 to skip waiting entirely.


[View source]
def request_guild_members(guild_id : UInt64, query : String = "", limit : Int32 = 0) #

Requests a full list of members to be sent for a specific guild. This is necessary to get the entire members list for guilds considered large (what is considered large can be changed using the large_threshold parameter in #initialize).

The list will arrive in the form of GUILD_MEMBERS_CHUNK dispatch events, which can be listened to using #on_guild_members_chunk. If a cache is set up, arriving members will be cached automatically.


[View source]
def resume(sequence : Int64? = nil) #

Sends a resume packet from the given sequence number, or alternatively the current session's last received sequence if none is given. This will make Discord replay all events since that sequence.


[View source]
def run #

Connects this client to the gateway. This is required if the bot needs to do anything beyond making REST API calls. Calling this method will block execution until the bot is forcibly stopped.


[View source]
def session : Gateway::Session? #

The internal session the client is currently using, necessary to create a voice client, for example


[View source]
def status_update(status : String? = nil, game : GamePlaying? = nil, afk : Bool = false, since : Int64? = nil) #

Sends a status update to Discord. The status can be "online", "idle", "dnd", or "invisible". Setting the game to a GamePlaying object makes the bot appear as playing some game on Discord. since and afk can be used in conjunction to signify to Discord that the status change is due to inactivity on the bot's part – this fulfills no cosmetic purpose.


[View source]
def stop(message = nil) #

Closes the gateway connection permanently


[View source]
def voice_state_update(guild_id : UInt64, channel_id : UInt64?, self_mute : Bool, self_deaf : Bool) #

Sends a voice state update to Discord. This will create a new voice connection on the given guild_id and channel_id, update an existing one with new self_mute and self_deaf status, or disconnect from voice if the channel_id is nil.

discordcr doesn't support sending or receiving any data from voice connections yet - this will have to be done externally until that happens.


[View source]
def wait_for_reconnect #

Separate method to wait an ever-increasing amount of time before reconnecting after being disconnected in an unexpected way


[View source]
def websocket #

The internal websocket the client is currently using


[View source]